Core Concepts
HTTP Server Configuration
Soklet applications do not deploy on traditional application servers like Jetty or Tomcat. There is no concept of a Servlet Container or a WAR file (although Soklet does offer Servlet integration for legacy code).
Instead, Soklet provides its own transport servers out-of-the-box. A Soklet application can be configured with any combination of:
- a regular HTTP
HttpServerfor ordinary Resource Methods - a
SseServerfor SSE handshakes and streams - an
McpServerfor Model Context Protocol transport
At least one of those three must be configured.
SokletConfig.Builder.jvmShutdownHookEnabled(Boolean) controls the automatic JVM shutdown hook for the whole application. Its default is Boolean.TRUE, and null restores the default. Keep it enabled for ordinary standalone and container applications. Hosts that need to control when draining begins can set Boolean.FALSE and own the JVM shutdown sequence, including requesting and synchronously awaiting Soklet shutdown before their hook returns. This option does not change transport settings or scoped teardown.
Startup and shutdown deadlines belong to the shared LifecyclePolicy, configured with SokletConfig.Builder.lifecyclePolicy(...), rather than to individual transport builders. The default gracefulShutdownTimeout is 15 seconds, followed by a separate 3-second forcedShutdownTimeout. These are shared owner-level budgets, not fresh allowances for each server or executor. Forced shutdown closes remaining response paths and requests interruption; it cannot guarantee that noncooperative application code stops. See Graceful Shutdown for deployment budgeting.
Duration.ZERO gives a lifecycle phase an immediate deadline. It provides no waiting allowance and does not disable supervision. Zero startup can time out immediately; zero graceful drain moves unresolved work to force; zero forced shutdown can leave an incomplete result even for an idle listener. See Zero Lifecycle Budgets before selecting these values.
Runtime Concurrency Model
Soklet keeps socket/event-loop work separate from application request handling. Standard HTTP event loops accept connections, parse request bytes, dispatch request handling, and write finalized response bytes. The request-handler executor runs Resource Method execution, RequestInterceptor::interceptRequest, RequestBodyMarshaler, and ResponseMarshaler work. StreamingResponseBody producers run on the streaming executor so long-lived producers do not occupy request-handler threads; event loops write the queued stream bytes to sockets.
requestHandlerConcurrency and requestHandlerQueueCapacity apply to request-handler work, not to accept loops, connection event loops, or already-established streaming writes. If you supply requestHandlerExecutorServiceSupplier, Soklet uses your executor directly and does not wrap it with the standard concurrency and queue-capacity controls.
SSE uses request-handler executor capacity for handshake Resource Methods. Established SSE streams run on a virtual-thread-per-connection executor and are controlled by connection caps, queue capacity, heartbeat, write timeout, and shutdown settings rather than by handshake concurrency.
Custom HTTP request-handler executors must dispatch asynchronously. A direct executor or saturated caller-runs policy is rejected with 503 and connection closure before resource handling begins. Use a throwing rejection policy; your executor remains responsible for its concurrency and queue limits. Custom SSE handshake executors must likewise dispatch asynchronously to avoid blocking connection admission.
HTTP requestHandlerTimeout includes time spent queued. Already-admitted requests retain their original deadlines during graceful shutdown. Expiry claims a 503 response and requests interruption of a running handler; application code that ignores interruption remains tracked until it exits or is reported as residual work. The request deadline scheduler retires after handler termination or when forced shutdown begins.
MCP application handlers run behind server-wide execution-slot and queue bounds. Request-scoped SSE responses and subscriptions have their own bounded message queues; see the MCP section below.
HTTP Server
If your application serves ordinary HTTP Resource Methods, configure a HttpServer. The minimum required configuration is the port number on which to listen.
Soklet will pick sensible defaults, shown below, for other settings.
// The only required configuration is port number
HttpServer httpServer = HttpServer.withPort(8080 /* port */)
// Host on which we are listening
.host("0.0.0.0")
// The number of connection-handling event loops to run concurrently.
// You likely want the number of CPU cores as per below
.concurrency(Runtime.getRuntime().availableProcessors())
// Absolute request-line/header budget; also the keep-alive idle limit
.requestHeaderTimeout(Duration.ofSeconds(60))
// How long to permit the request body to arrive after headers
.requestBodyTimeout(Duration.ofSeconds(60))
// Policy for transparently decompressing eligible gzip request bodies.
// Disabled by default.
.requestDecompressionPolicy(RequestDecompressionPolicy.disabledInstance())
// Maximum idle duration while writing a non-streaming response.
// Defaults to 60 seconds; Duration.ZERO disables this timeout.
.responseWriteIdleTimeout(Duration.ofSeconds(60))
// Plans compression for eligible finalized in-memory responses.
// Disabled by default.
.responseCompressor(ResponseCompressor.disabledInstance())
// How long to permit your request handler logic to run
// (Resource Method + Response Marshaling)
.requestHandlerTimeout(Duration.ofSeconds(60))
// Maximum number of request handler tasks that may run concurrently.
// Defaults to concurrency * 16.
.requestHandlerConcurrency(Runtime.getRuntime().availableProcessors() * 16)
// Maximum queued request handler tasks before rejecting with 503.
// Defaults to requestHandlerConcurrency * 64.
.requestHandlerQueueCapacity(Runtime.getRuntime().availableProcessors() * 16 * 64)
// Per-stream producer queue capacity for StreamingResponseBody.
// Defaults to 1 MB per stream.
.streamingQueueCapacityInBytes(1_024 * 1_024)
// Maximum streaming payload chunk size.
// Defaults to 16 KB.
.streamingChunkSizeInBytes(1_024 * 16)
// Retained streaming lifetimes, managed callback workers, and cleanup budget.
.streamingLifecycleCapacity(256)
.streamingCallbackConcurrency(4)
.streamingCleanupTimeout(Duration.ofSeconds(5))
// Maximum total duration for a streaming response.
// Duration.ZERO disables this timeout.
.streamingResponseTimeout(Duration.ZERO)
// Maximum idle duration between bytes produced for a streaming response.
// Defaults to requestBodyTimeout; Duration.ZERO disables this timeout.
.streamingResponseIdleTimeout(Duration.ofSeconds(60))
// Maximum selector wait; must be positive.
// Pending socket deadlines can shorten it.
.socketSelectTimeout(Duration.ofMillis(100))
// The biggest HTTP request we permit clients to make (10 MB)
// This includes request line, headers, transfer framing, and body bytes.
.maximumRequestSizeInBytes(1_024 * 1_024 * 10)
// Biggest received body payload (10 MB), before optional decompression.
// Defaults to the aggregate limit above and cannot exceed it.
.maximumRequestBodySizeInBytes(1_024 * 1_024 * 10)
// Maximum number of header fields accepted in one request.
.maximumHeaderCount(100)
// Maximum header-section size accepted in one request (64 KB).
.maximumHeadersSizeInBytes(64 * 1_024)
// Maximum request-target length accepted in bytes.
.maximumRequestTargetLengthInBytes(8_192)
// Requests are read into a byte buffer of this size.
// Adjust down if you expect tiny requests.
// Adjust up if you expect larger requests.
.requestReadBufferSizeInBytes(1_024 * 64)
// The maximum number of pending connections on the socket
// (values < 1 use JVM platform default)
.socketPendingConnectionLimit(0)
// Maximum concurrent connections (0 disables the cap)
.concurrentConnectionLimit(8_192)
// Request ID generator
.idGenerator(IdGenerator.defaultInstance())
// Multipart parser
.multipartParser(MultipartParser.defaultInstance())
.build();
// Use our custom server
SokletConfig config = SokletConfig.withHttpServer(httpServer)
// Shared lifecycle deadlines (the defaults shown here apply to every transport)
.lifecyclePolicy(LifecyclePolicy.builder()
.gracefulShutdownTimeout(Duration.ofSeconds(15))
.forcedShutdownTimeout(Duration.ofSeconds(3))
.build())
// Not shown: other Soklet builder customizations
.build();
// Start once, then wait for JVM shutdown.
Soklet soklet = Soklet.run(config);
System.out.println("Soklet is ready");
ShutdownResult result = soklet.awaitShutdown();
// The only required configuration is port number
HttpServer httpServer = HttpServer.withPort(8080 /* port */)
// Host on which we are listening
.host("0.0.0.0")
// The number of connection-handling event loops to run concurrently.
// You likely want the number of CPU cores as per below
.concurrency(Runtime.getRuntime().availableProcessors())
// Absolute request-line/header budget; also the keep-alive idle limit
.requestHeaderTimeout(Duration.ofSeconds(60))
// How long to permit the request body to arrive after headers
.requestBodyTimeout(Duration.ofSeconds(60))
// Policy for transparently decompressing eligible gzip request bodies.
// Disabled by default.
.requestDecompressionPolicy(RequestDecompressionPolicy.disabledInstance())
// Maximum idle duration while writing a non-streaming response.
// Defaults to 60 seconds; Duration.ZERO disables this timeout.
.responseWriteIdleTimeout(Duration.ofSeconds(60))
// Plans compression for eligible finalized in-memory responses.
// Disabled by default.
.responseCompressor(ResponseCompressor.disabledInstance())
// How long to permit your request handler logic to run
// (Resource Method + Response Marshaling)
.requestHandlerTimeout(Duration.ofSeconds(60))
// Maximum number of request handler tasks that may run concurrently.
// Defaults to concurrency * 16.
.requestHandlerConcurrency(Runtime.getRuntime().availableProcessors() * 16)
// Maximum queued request handler tasks before rejecting with 503.
// Defaults to requestHandlerConcurrency * 64.
.requestHandlerQueueCapacity(Runtime.getRuntime().availableProcessors() * 16 * 64)
// Per-stream producer queue capacity for StreamingResponseBody.
// Defaults to 1 MB per stream.
.streamingQueueCapacityInBytes(1_024 * 1_024)
// Maximum streaming payload chunk size.
// Defaults to 16 KB.
.streamingChunkSizeInBytes(1_024 * 16)
// Retained streaming lifetimes, managed callback workers, and cleanup budget.
.streamingLifecycleCapacity(256)
.streamingCallbackConcurrency(4)
.streamingCleanupTimeout(Duration.ofSeconds(5))
// Maximum total duration for a streaming response.
// Duration.ZERO disables this timeout.
.streamingResponseTimeout(Duration.ZERO)
// Maximum idle duration between bytes produced for a streaming response.
// Defaults to requestBodyTimeout; Duration.ZERO disables this timeout.
.streamingResponseIdleTimeout(Duration.ofSeconds(60))
// Maximum selector wait; must be positive.
// Pending socket deadlines can shorten it.
.socketSelectTimeout(Duration.ofMillis(100))
// The biggest HTTP request we permit clients to make (10 MB)
// This includes request line, headers, transfer framing, and body bytes.
.maximumRequestSizeInBytes(1_024 * 1_024 * 10)
// Biggest received body payload (10 MB), before optional decompression.
// Defaults to the aggregate limit above and cannot exceed it.
.maximumRequestBodySizeInBytes(1_024 * 1_024 * 10)
// Maximum number of header fields accepted in one request.
.maximumHeaderCount(100)
// Maximum header-section size accepted in one request (64 KB).
.maximumHeadersSizeInBytes(64 * 1_024)
// Maximum request-target length accepted in bytes.
.maximumRequestTargetLengthInBytes(8_192)
// Requests are read into a byte buffer of this size.
// Adjust down if you expect tiny requests.
// Adjust up if you expect larger requests.
.requestReadBufferSizeInBytes(1_024 * 64)
// The maximum number of pending connections on the socket
// (values < 1 use JVM platform default)
.socketPendingConnectionLimit(0)
// Maximum concurrent connections (0 disables the cap)
.concurrentConnectionLimit(8_192)
// Request ID generator
.idGenerator(IdGenerator.defaultInstance())
// Multipart parser
.multipartParser(MultipartParser.defaultInstance())
.build();
// Use our custom server
SokletConfig config = SokletConfig.withHttpServer(httpServer)
// Shared lifecycle deadlines (the defaults shown here apply to every transport)
.lifecyclePolicy(LifecyclePolicy.builder()
.gracefulShutdownTimeout(Duration.ofSeconds(15))
.forcedShutdownTimeout(Duration.ofSeconds(3))
.build())
// Not shown: other Soklet builder customizations
.build();
// Start once, then wait for JVM shutdown.
Soklet soklet = Soklet.run(config);
System.out.println("Soklet is ready");
ShutdownResult result = soklet.awaitShutdown();
Start this configuration with Soklet.run(config). For scoped execution, embedded hosts, console input, and bounded application cleanup, see Application Lifecycle. For process signals and deployment budgets, see Graceful Shutdown.
Effective streaming total and idle timeouts must be nonnegative and representable in nanoseconds (at most Duration.ofNanos(Long.MAX_VALUE), about 292 years). build() rejects larger values, including an oversized idle timeout inherited from requestBodyTimeout. Zero disables a timeout; null restores the total timeout’s disabled default or the idle timeout’s effective request-body default.
Additional notes: requestHeaderTimeout also bounds idle time between requests on a persistent connection. After a response completes, the timer starts again; the next request must finish its line and headers within the remaining budget, and incoming header bytes do not renew it. A timeout with no request bytes closes quietly; a partial request receives the default 408 response. Coordinate this setting with upstream keep-alive reuse: the 60-second HTTP/MCP default is not safely above common proxy idle defaults. Set it comfortably above the proxy's idle reuse window with round-trip/jitter margin, or reduce that window; see production timeout coordination. requestBodyTimeout controls total body-read time after headers have been received. requestBodyTimeout is not an idle-progress timeout: a slow upload can exceed it even if bytes keep arriving. responseWriteIdleTimeout controls how long a non-streaming response may go without socket-write progress; it protects fixed-length and file responses from stalled readers, resets when Soklet successfully writes response bytes, defaults to 60 seconds, and can be disabled with Duration.ZERO. requestHandlerTimeout caps the total time your handler code is allowed to run. requestHandlerConcurrency and requestHandlerQueueCapacity provide backpressure by limiting how many requests can be actively processed or queued. During shutdown, the standard HTTP server stops accepting new connections, closes idle keep-alives, lets already-dispatched handlers flush responses with Connection: close, and then force-closes remaining connections when the shared gracefulShutdownTimeout expires. streamingQueueCapacityInBytes, streamingChunkSizeInBytes, streamingResponseTimeout, and streamingResponseIdleTimeout apply to StreamingResponseBody responses only. The streaming idle timeout measures time with neither producer output nor socket-write progress. Accepted producer output, including scalar writes buffered in an output view, and successful socket writes renew it during and after production. Client reads alone do not renew it; writes that reach the socket do. Streaming producers run on a separate executor so long-lived streams do not occupy request handler threads; provide streamingExecutorServiceSupplier if you need to own that executor. maximumRequestSizeInBytes applies to the whole received HTTP request, including request line, headers, transfer framing, and body bytes. maximumHeaderCount, maximumHeadersSizeInBytes, and maximumRequestTargetLengthInBytes bound request shape independently from total byte size; maximumHeadersSizeInBytes counts the header section after the request line, including header-field line endings and the terminating blank line. Leave headroom if you are thinking in terms of payload size: a body exactly equal to the configured limit may be rejected once request metadata is counted. If a client exceeds the content-size limit after Soklet has enough data to identify the request, the usual 413 Content Too Large marshaling path runs. Request-target length violations receive 414 URI Too Long; header count and header-section size violations receive 431 Request Header Fields Too Large. If a limit is exceeded before a request target can be parsed, Soklet may close the connection instead. The concurrentConnectionLimit knob can be used to shed load; its default is 8_192, and 0 disables Soklet's standard HTTP connection cap. Tune the production value based on your file-descriptor limit and edge connection policy. idGenerator controls the values surfaced via Request::getId. Your IdGenerator receives the Request, so you can incorporate request data - for example, X-Amzn-Trace-Id.
responseCompressor is the single setting for dynamic response compression. It is disabled by default; pass ResponseCompressor::fromDefaultsWithMinimumBodySizeInBytes to select gzip for common text-like media types, or supply a compressor that returns ResponseCompressionPlan::none or a plan selecting a codec and optional compressed-body cache callback. Passing null or ResponseCompressor.disabledInstance() disables it again. Soklet checks the client's acceptance of the selected encoding and owns Vary: Accept-Encoding, validators, and response framing. Only finalized in-memory byte-array and ByteBuffer responses are eligible; streaming, file, file-channel, already-encoded, ranged, bodyless, and transfer-encoded responses are excluded. Otherwise eligible responses with Content-Digest, Repr-Digest, Digest, or Content-MD5 retain their original bytes without invoking the compressor; identity coding must still be acceptable to the client. When planning applies to HEAD, it uses the uncompressed representation without invoking its codec or cache callback. See Response Compression for examples, the custom codec contract, and application-owned caching.
maximumRequestBodySizeInBytes independently caps received body payload bytes after HTTP transfer framing is removed and before optional Content-Encoding decompression. Chunk delimiters and trailers do not count toward this body-only bound, but remain part of maximumRequestSizeInBytes. The body-only value cannot exceed the aggregate request limit; when omitted or reset to null, it tracks that limit regardless of setter order. This lets an application reserve aggregate headroom for the request line, headers, and transfer framing without accepting a payload of the same size.
Input failures before the standard HTTP server can construct a valid Request use ResponseMarshaler::forUnparsedRequest. This includes malformed requests, overlong targets, unsupported expectations, header limits, partial read timeouts, early aggregate-size failures, URI/encoding validation and body decompression failures. Soklet first invokes LifecycleObserver::didRejectUnparsedRequest and then the marshaler if budget remains. Both operations run on the request-handler executor and share requestHandlerTimeout, using its remaining duration for later construction failures. Neither callback runs inline on a selector. Saturation, timeout or invalid output uses a bodyless fallback. Idle timeouts and EOF before complete headers close quietly; admission, shutdown and broken-socket failsafes bypass the hook. See Unparsed HTTP Requests for all eight reasons, bounded capture details and response customization. The same hook also handles eligible SSE handshake rejections.
requestDecompressionPolicy enables opt-in transparent request-body decompression for the standard HTTP server. Enabled policies support a single Content-Encoding: gzip or x-gzip coding using JDK gzip, remove Content-Encoding and Transfer-Encoding, and replace Content-Length with the decompressed byte count before handlers see the Request. Handlers receive those decompressed bytes through Request::getBody; Request::getEncodedBodySizeInBytes retains the pre-decompression payload size for wire-oriented telemetry. Unsupported codings and coding chains return 415 Unsupported Media Type; malformed gzip bodies return 400 Bad Request; decompressed-size or compression-ratio violations return 413 Content Too Large through the usual ResponseMarshaler::forContentTooLarge path. The decompressed-size cap defaults to maximumRequestSizeInBytes, and the wire request is still bounded by maximumRequestSizeInBytes before decompression. SSE, MCP, and simulator requests are not decompressed by this setting.
After finishing an HTTP response that closes the connection, the built-in server closes promptly when the request was fully consumed and no surplus input was observed. Before taking that path, one bounded nonblocking read checks for input already queued on the socket while the handler ran. If unread input may remain, such as after an early rejection, malformed framing, or detected trailing input, it half-closes its output and discards further input using a one-second absolute deadline and a 16 MiB additional-input ceiling. Any byte consumed by the closing probe counts toward that ceiling. The deadline is not renewed by incoming bytes; discarded bytes are never dispatched as another request. A lingering connection retains its connection-limit slot and consumes the graceful shutdown budget until the socket closes. Forced shutdown bypasses this drain wait. This bounded close helps clients receive an early response while uploading, but cannot guarantee delivery for arbitrarily large or slow uploads or bytes that race the final close.
For browser uploads, validate file sizes before sending and handle both HTTP 413 and a network error. A browser may surface a reset instead of the rejection response if it continues uploading beyond the bounded discard budget; the behavior depends on the browser and transport. Client-side checks improve feedback but do not replace Soklet's limits or limits at the edge.
The HTTP builder provides streamingLifecycleCapacity (default 256), streamingCallbackConcurrency (default 4), and streamingCleanupTimeout (default five seconds) for managed HTTP response production and resource cleanup. The SSE builder provides streamingLifecycleCapacity (default 256) for admitted connections and synchronous initialization. When capacity is exhausted, a new stream receives 503 before its producer or initializer is invoked. A lifecycle slot stays occupied while its admitted work is physically running. HTTP cleanup timeout bounds application finalization, with healthy output-queue waits excluded while response and idle deadlines continue to apply. It cannot forcibly stop a blocked provider or make its slot reusable.
Rejected HTTP streams receive their finite response and finish request handling independently of termination observers. Unadmitted-stream notification uses a separately bounded allowance on the managed callback executor; accepted work remains physically tracked through shutdown. Capacity exhaustion while accepting omits that notification and logs RESPONSE_STREAM_CANCELED; omissions during graceful drain or forced shutdown are not logged. It does not consume admitted streams' reserved jobs. Request write/finish callbacks receive the actual finite response; the stream termination handle retains the original rejected stream.
HTTP callback concurrency cannot exceed HTTP lifecycle capacity; both counts must be positive, and the HTTP cleanup timeout must be positive and representable in nanoseconds. SSE lifecycle capacity must be positive. Passing null to a lifecycle setter restores its default. These controls are independent of payload queues, connection limits, and total response deadlines. SSE's 128-element queue limit counts events and comments, not bytes; size application payloads separately.
streamingCallbackConcurrency bounds HTTP cancelation batches and unadmitted rejection observers. Admitted termination notifications and streaming cleanup diagnostics use separate executors, each with at most streamingLifecycleCapacity workers and one termination observation per admitted lifetime. Observations can run more concurrently than the callback setting. A blocked observer retains its own slot while other admitted streams can deliver their observations and retire. Blocking all cancelation workers can still queue later cancelation batches; a cleanup timeout cannot terminate blocked application code or free its slot. Size lifecycle capacity for the resulting producer and observation concurrency.
The default HTTP streaming executor gives each admitted producer its own virtual thread, bounded by lifecycle admission. Exhausted lifecycle capacity rejects a new stream with 503 before streaming headers. A custom streaming executor must dispatch asynchronously and start accepted producers promptly. Direct handoff and rejection avoid queuing behind long-lived producers; inline or caller-runs dispatch is rejected.
Additional defaults not shown above: requestHandlerExecutorServiceSupplier and streamingExecutorServiceSupplier use virtual threads, bounded by their respective request or streaming admission controls, and multipartParser defaults to MultipartParser::defaultInstance. If you supply your own requestHandlerExecutorServiceSupplier, Soklet will use that executor and ignore requestHandlerConcurrency and requestHandlerQueueCapacity.
Virtual Threads
Soklet requires JDK 21 or newer for HTTP, MCP, and SSE. The default application executors use Virtual Threads, subject to their admission and lifecycle bounds. No preview flags are required.
If you prefer not to use Virtual Threads, provide your own ExecutorService to HttpServer.Builder::requestHandlerExecutorServiceSupplier as shown above.
References:
The standard HTTP parser has two additional fixed bounds: method tokens are limited to 64 bytes, and each chunk-size line, including extensions and excluding the terminating CRLF, is limited to 8,192 bytes. These bounds apply independently of the configured request-size limits. Violations receive HTTP 400 and close the connection.
Server-Sent Event Server
If your application supports Server-Sent Events, configure a SseServer. This is a separate server (and port) dedicated to SSE connections. A regular HTTP HttpServer is only needed if the same app also exposes ordinary HTTP Resource Methods. See the Server-Sent Events documentation for details.
The minimum required configuration is the port number on which to listen.
Soklet will pick sensible defaults, shown below, for other settings.
// The only required configuration is port number
SseServer sseServer = SseServer.withPort(8081 /* port */)
// Host on which we are listening
.host("0.0.0.0")
// How long to permit the SSE handshake request line and headers to arrive
.requestHeaderTimeout(Duration.ofSeconds(60))
// How long to permit your SSE handshake handler logic to run
.requestHandlerTimeout(Duration.ofSeconds(60))
// Maximum number of SSE handshake tasks that may run concurrently.
// Defaults to availableProcessors * 16.
.requestHandlerConcurrency(Runtime.getRuntime().availableProcessors() * 16)
// Maximum queued SSE handshake tasks before rejecting with 503.
// Defaults to requestHandlerConcurrency * 64.
.requestHandlerQueueCapacity(Runtime.getRuntime().availableProcessors() * 16 * 64)
// Bounds SSE data, handshake and rejection-response writes.
// The timeout covers each complete write, so allow for your largest event
// on your slowest client connection.
// Defaults to 30 seconds; Duration.ZERO disables all these write timeouts.
.writeTimeout(Duration.ofSeconds(30))
// Heartbeat interval: at least 1 ms, with a whole-ms value that fits in a long.
.heartbeatInterval(Duration.ofSeconds(15))
// The biggest SSE handshake request we permit clients to make (64 KB)
// This includes request line and headers.
.maximumRequestSizeInBytes(1_024 * 64)
// Maximum number of header fields accepted in one handshake.
.maximumHeaderCount(100)
// Maximum header-section size accepted in one handshake (64 KB).
.maximumHeadersSizeInBytes(64 * 1_024)
// Maximum handshake request-target length accepted in bytes.
.maximumRequestTargetLengthInBytes(8_192)
// Requests are read into a byte buffer of this size
.requestReadBufferSizeInBytes(1_024)
// Transport connection cap; 0 disables only this cap.
// The independent lifecycle limit defaults to 256 retained lifetimes.
// If exceeded, a 503 is returned via ResponseMarshaler::forServiceUnavailable
.concurrentConnectionLimit(8_192)
// Cache sizes for broadcasters (per-resource-path event fanout)
// and resource path declarations (Route pattern lookups).
// Increase if you have many distinct SSE URLs in circulation.
.broadcasterCacheCapacity(1_024)
.resourcePathCacheCapacity(8_192)
// Maximum queued SSE writes per connection
.connectionQueueCapacity(128)
// Maximum admitted SSE connection lifetimes.
.streamingLifecycleCapacity(256)
// Write an initial heartbeat to verify the connection after handshake
.verifyConnectionOnceEstablished(true)
// Request ID generator
.idGenerator(IdGenerator.defaultInstance())
.build();
SokletConfig config = SokletConfig.withSseServer(sseServer)
// Shared lifecycle deadlines (the defaults shown here apply to every transport)
.lifecyclePolicy(LifecyclePolicy.builder()
.gracefulShutdownTimeout(Duration.ofSeconds(15))
.forcedShutdownTimeout(Duration.ofSeconds(3))
.build())
.build();
// The only required configuration is port number
SseServer sseServer = SseServer.withPort(8081 /* port */)
// Host on which we are listening
.host("0.0.0.0")
// How long to permit the SSE handshake request line and headers to arrive
.requestHeaderTimeout(Duration.ofSeconds(60))
// How long to permit your SSE handshake handler logic to run
.requestHandlerTimeout(Duration.ofSeconds(60))
// Maximum number of SSE handshake tasks that may run concurrently.
// Defaults to availableProcessors * 16.
.requestHandlerConcurrency(Runtime.getRuntime().availableProcessors() * 16)
// Maximum queued SSE handshake tasks before rejecting with 503.
// Defaults to requestHandlerConcurrency * 64.
.requestHandlerQueueCapacity(Runtime.getRuntime().availableProcessors() * 16 * 64)
// Bounds SSE data, handshake and rejection-response writes.
// The timeout covers each complete write, so allow for your largest event
// on your slowest client connection.
// Defaults to 30 seconds; Duration.ZERO disables all these write timeouts.
.writeTimeout(Duration.ofSeconds(30))
// Heartbeat interval: at least 1 ms, with a whole-ms value that fits in a long.
.heartbeatInterval(Duration.ofSeconds(15))
// The biggest SSE handshake request we permit clients to make (64 KB)
// This includes request line and headers.
.maximumRequestSizeInBytes(1_024 * 64)
// Maximum number of header fields accepted in one handshake.
.maximumHeaderCount(100)
// Maximum header-section size accepted in one handshake (64 KB).
.maximumHeadersSizeInBytes(64 * 1_024)
// Maximum handshake request-target length accepted in bytes.
.maximumRequestTargetLengthInBytes(8_192)
// Requests are read into a byte buffer of this size
.requestReadBufferSizeInBytes(1_024)
// Transport connection cap; 0 disables only this cap.
// The independent lifecycle limit defaults to 256 retained lifetimes.
// If exceeded, a 503 is returned via ResponseMarshaler::forServiceUnavailable
.concurrentConnectionLimit(8_192)
// Cache sizes for broadcasters (per-resource-path event fanout)
// and resource path declarations (Route pattern lookups).
// Increase if you have many distinct SSE URLs in circulation.
.broadcasterCacheCapacity(1_024)
.resourcePathCacheCapacity(8_192)
// Maximum queued SSE writes per connection
.connectionQueueCapacity(128)
// Maximum admitted SSE connection lifetimes.
.streamingLifecycleCapacity(256)
// Write an initial heartbeat to verify the connection after handshake
.verifyConnectionOnceEstablished(true)
// Request ID generator
.idGenerator(IdGenerator.defaultInstance())
.build();
SokletConfig config = SokletConfig.withSseServer(sseServer)
// Shared lifecycle deadlines (the defaults shown here apply to every transport)
.lifecyclePolicy(LifecyclePolicy.builder()
.gracefulShutdownTimeout(Duration.ofSeconds(15))
.forcedShutdownTimeout(Duration.ofSeconds(3))
.build())
.build();
If you also serve ordinary HTTP Resource Methods, add httpServer(HttpServer) with a server from HttpServer.fromPort(Integer).
requestHeaderTimeout independently bounds request-line and header reading once the admitted header-reading phase begins. requestHandlerTimeout starts when the connection is accepted and covers queue wait plus application handshake handling. Header reading and parsing pause that handler budget; successful parsing resumes its remaining duration, without refunding queue wait. Input rejections use that same remaining duration for lifecycle observation and unparsed-request marshaling. Partial-header read expiry routes through forUnparsedRequest, with a default 408 Request Timeout. Idle read expiry and EOF before complete headers close quietly. Queue or parsed application expiry produces 503 Service Unavailable; expiry while marshaling an input rejection uses its original bodyless fallback, with cooperative interruption of a running handshake worker. These timeouts govern the handshake, not the established event stream. Unlike reusable standard HTTP/MCP connections, a dedicated SSE connection does not use the handshake header timer as its stream idle limit; coordinate stream heartbeats, write timeouts, and edge idle timeouts separately. Header reading runs separately from application handshake workers, but pending header-reading and parsed/queued handshake phases share a bound of requestHandlerConcurrency + requestHandlerQueueCapacity; slow or idle header phases consume that same allowance. SSE handshakes do not accept request bodies, so there is no SSE request-body timeout.
Additional notes: maximumRequestSizeInBytes bounds the handshake request and, separately, the surplus inbound bytes tolerated after acceptance. It does not cap outbound event bytes. Exceeding the inbound budget terminates the connection. maximumHeaderCount, maximumHeadersSizeInBytes, and maximumRequestTargetLengthInBytes bound handshake request shape independently from total byte size. Request-target length violations receive 414 URI Too Long; header count and header-section size violations receive 431 Request Header Fields Too Large. writeTimeout defaults to 30 seconds and bounds stream, handshake and rejection-response writes; Duration.ZERO disables all of these write deadlines, including failsafe response writes. requestHandlerConcurrency and requestHandlerQueueCapacity provide backpressure for SSE handshakes (they do not limit active SSE connections). During shutdown, active SSE streams are terminated with StreamTerminationReason.SERVER_STOPPING, and queued application events may be discarded. Managed cleanup is awaited within the shared gracefulShutdownTimeout. Soklet then requests interruption of remaining work and waits within the separate forcedShutdownTimeout; noncooperative application code may outlive that budget.
SSE lifecycle capacity is a separate admission bound: the default allows at most 256 retained SSE lifetimes even though the transport connection ceiling is 8,192. Retained cleanup also consumes those slots. Exhausting either the connection or lifecycle cap returns 503 before the accepted response or initializer, and reports SseConnection.HandshakeFailureReason.CAPACITY_EXCEEDED to lifecycle observers and metrics collectors.
concurrentConnectionLimit(0) leaves lifecycle admission bounded. When the connection cap is positive, admitted connections cannot exceed the smaller limit; pending initialization and cleanup may leave fewer slots available. Configure both limits when increasing client capacity. Lifecycle admission follows the application's handshake method, so that method may run before a capacity 503. Put work that requires an admitted connection in its client initializer.
heartbeatInterval defaults to 15 seconds and must be at least one millisecond, with a whole-millisecond value that fits in a Java long. Invalid intervals fail when the server is built. Heartbeat waits discard fractional milliseconds; zero is not accepted, and null restores the default.
SSE connections and broadcasters are node-local. In clustered deployments, a local broadcast only reaches clients connected to that node, so production systems usually publish events to a shared queue or pub/sub system and have each Soklet node perform its own local rebroadcast. If you support Last-Event-ID catch-up, the replay data should come from a shared durable store or log.
Additional defaults not shown above: requestHandlerExecutorServiceSupplier uses a bounded virtual-thread executor for handshakes, header reading uses a separate executor within the shared pending-handshake admission bound, and established SSE connections are processed on a virtual-thread-per-connection executor. If you supply your own requestHandlerExecutorServiceSupplier, that executor controls its worker and queue sizing. requestHandlerConcurrency and requestHandlerQueueCapacity still bound pending header-reading and application-handshake admission through their sum.
References:
Custom HTTP and SSE Transports
A bind failure is a failed startup, even when all rollback cleanup completes. Built-in HTTP, SSE and MCP preserve the real failure cause; rollback completed within the grace period yields StartupDisposition.FAILED with a component GRACEFUL_TERMINATION. The cleanup disposition also holds through transparent, termination-owning and nested HTTP/SSE decorators. An independent transport failure before shutdown intent remains UNEXPECTED_TERMINATION.
Request-handler decorators should pass through the returned HttpRequestResult, or modify it using copy().finish(). This preserves the dispatch association used to pair stream observations, including when the decorator copies the request. Reconstructing the result from scratch drops that association; observers may then treat stream termination as an independent observation.
For custom HTTP/SSE runtimes, TransportRuntime::start must throw a synchronous startup error and let the owner deliver rollback phases. Keep both shutdown methods safe after a partial bind, initiate cleanup promptly, and report TransportTerminationSignal::signalTerminated only when owned work ends. Reporting failure/proof before throwing instead describes independent premature termination. Separate worker failures should still be signaled immediately, including before readiness. A termination-owning decorator also drives its child's shutdown, whose proof remains independently required.
Soklet does not invoke shutdown phases concurrently with a runtime's ongoing start(). If startup finishes after the forced boundary, Soklet attempts forced cleanup with the original deadline and no fresh waiting allowance. Late termination proof or failure does not change the immutable shutdown result. Honor startup cancelation, keep phase methods prompt, and retain responsibility for any resources still active after an incomplete shutdown.
MCP Server
Soklet exposes Model Context Protocol through a dedicated McpServer and port. Clients using 2026-07-28 send direct versioned POST requests without initialization. An endpoint can also explicitly select 2025-06-18 or 2025-11-25; those clients start with initialize and can use tools, prompts, resources, completion, POST progress and pagination. The 2025 profiles are session-disabled by default. Explicit session configuration adds remembered public client information/capabilities and active-request cancelation. HTTP transport admission additionally enables DELETE and, with selected subscriptions and effective change sources, leased GET notification delivery and independently authorized resource subscriptions. See Compatibility and Scope for the exact limits. A regular HttpServer is needed only when the same application also exposes ordinary HTTP Resource Methods.
Start with a fresh mcpServerBuilder carrying the settings from MCP Server Configuration, then adjust the transport bounds:
McpServer mcpServer = mcpServerBuilder
// Absolute client-visible deadline and bounded application-handler capacity.
.requestTimeout(Duration.ofSeconds(60))
.requestHandlerConcurrency(32)
.requestHandlerQueueCapacity(128)
// Request-scoped SSE and subscription delivery bounds.
.streamQueueCapacity(128)
.writeTimeout(Duration.ofSeconds(30))
.keepAliveInterval(Duration.ofSeconds(15))
.build();
SokletConfig config = SokletConfig.withMcpServer(mcpServer)
.build();
McpServer mcpServer = mcpServerBuilder
// Absolute client-visible deadline and bounded application-handler capacity.
.requestTimeout(Duration.ofSeconds(60))
.requestHandlerConcurrency(32)
.requestHandlerQueueCapacity(128)
// Request-scoped SSE and subscription delivery bounds.
.streamQueueCapacity(128)
.writeTimeout(Duration.ofSeconds(30))
.keepAliveInterval(Duration.ofSeconds(15))
.build();
SokletConfig config = SokletConfig.withMcpServer(mcpServer)
.build();
If you also serve ordinary HTTP Resource Methods, add httpServer(HttpServer) with a server from HttpServer.fromPort(Integer).
By default, Soklet discovers the endpoint registry from generated classpath metadata and accepts requests anonymously. Use endpointRegistry(...) for an explicit registry and admissionController(...) when the server requires authentication or authorization. Tool rate limiting is optional; configure a tool, endpoint, or server limiter when an application quota is needed. The listener binds to 127.0.0.1 by default. Requests carrying Origin are rejected unless a shared CorsAuthorizer is configured; absent origins are allowed by default through McpAbsentOriginPolicy. Configure host(...) and allowedHosts(...) deliberately for remote deployments.
HTTP and SSE bind to 0.0.0.0 by default. Container and remote MCP deployments need an explicit bind address and a nonempty allowed-host set for a non-loopback bind. See MCP listener binding for the public Host and proxy-port rules.
The MCP builder also controls cursor size, request-wide rate limiting, handler interception, tool-output sanitization, subscription limits, request-state protection, mirrored-header policy, and trace correlation. See the MCP documentation for the complete defaults, invariants, security model, and shutdown behavior.
For deployment boundaries, threading details, shutdown behavior, and multi-node guidance, see Production Readiness.
References:
The API reference is in MCP, including McpServer, McpServer.Builder, McpEndpointRegistry, McpAdmissionController, and McpRateLimiter.
Wire compatibility boundaries
Send requests with a normal request line. When specifying a Host port suffix, supply its numeric value. The built-in parsers reject leading blank lines, empty port suffixes such as localhost:, and malformed request-line whitespace. The SSE listener requires HTTP/1.1; unsupported or malformed handshakes are rejected. These strict parsing choices remain in place.
Response-header validation also rejects percent-encoded control bytes, including in Location values. Avoid redirect targets containing encoded newlines or other control bytes. A file that cannot be opened when the response is written can terminate the connection without an HTTP error response; keep static roots stable and monitor file-descriptor capacity.

