Soklet Logo

Core Concepts

Server-Sent Events

Server-Sent Events (or SSE) is a technology that enables efficient data "pushes" to clients over a regular HTTP or HTTPS connection. Conceptually, a web browser tells a server that it's interested in receiving events from a particular URL. A TCP socket that speaks HTTP is established between the two and held open indefinitely. The server writes text/event-stream-formatted data to the socket as needed, and the client listens for data events using standard JavaScript functionality available in all major browsers.

SSE is appropriate for many scenarios that were traditionally solved by client polling. For example, after a record is updated in your database, you might want to securely send a "record changed" notification to anyone who is viewing the record in their web browser - the webpage can then refresh itself and display the updated data. SSE is also a great fit for AI-backed applications that stream LLM responses while they reason.

Soklet uses virtual threads for SSE. Like the rest of Soklet, SSE requires JDK 21 or newer; preview features are not needed.

The built-in SSE listener requires HTTP/1.1 on the proxy-to-Soklet connection. Ensure your edge forwards streamed bytes without buffering; see load balancers and streaming. For nginx, proxy_http_version 1.1; makes the upstream protocol explicit: HTTP/1.1 has been the default since 1.29.7, while older versions defaulted to HTTP/1.0 (nginx documentation).

Why Not WebSockets?

SSE technology is similar to WebSockets, which Soklet does not support. After an initial handshake over HTTP, WebSockets switch to a special protocol on top of TCP for high-performance bidirectional communication. This design is well-suited for systems like games which require low-latency interactions between two parties, but comes with complexity costs that might not be worth paying for a traditional CRUD application.

Compared to WebSockets, SSE keeps end-to-end encryption for the lifetime of the connection when you use HTTPS, offers a very small browser API surface through EventSource, gives browsers automatic reconnect behavior, and avoids the deployment friction of a custom bidirectional protocol that may be blocked by intermediaries.


Client Implementation

Let's look at how SSE works from the client's perspective.

The code below is vanilla JavaScript and will run in any modern web browser. No dependencies are required.

First, an EventSource is acquired:

// We want to listen to events for a specific chat...
const EVENT_SOURCE_URL = '/chats/123/event-source'

// ...so we register an EventSource for it.
let eventSource = new EventSource(EVENT_SOURCE_URL)

This URL is relative to the page's origin. When using separate HTTP and SSE listener ports, route this path to the SSE listener at your edge. A different scheme, hostname, or port requires an explicit CORS allowlist for the page's origin; the default policy does not grant cross-origin reads. Cookie-authenticated cross-origin clients also need withCredentials: true and a credentialed server grant.

Then, event listeners are added:

// When the connection is opened
eventSource.addEventListener('open', (e) => {
  console.log(`EventSource connection opened for ${EVENT_SOURCE_URL}`)
})

// When the connection encounters an error
eventSource.addEventListener('error', (e) => {
  console.log(`Error for ${EVENT_SOURCE_URL}`, e)
})

// SSE connection streams can include named events.
// Here, we listen specifically for those named "chat-message"
eventSource.addEventListener('chat-message', (e) => {
  console.log(`Chat message received: ${e.data}`)
})

When you're done with your EventSource, shut it down:

eventSource.close()

That's it - the standard JavaScript SSE API has a tiny footprint and almost no learning curve.

Server-Side Implementation

Server-side, you must do 3 things:

  1. Configure an SseServer
  2. Define one or more Event Source Methods to "handshake" with clients
  3. (sometime later) Broadcast events to clients

Configuration

A Soklet app that supports Server-Sent Events must be configured with an SseServer. A regular HttpServer is only required if the same app also exposes ordinary HTTP Resource Methods.

// Special SSE-specific server
SseServer sseServer = SseServer.fromPort(8081);

// Provide the SSE server to Soklet.
// If you also serve ordinary HTTP resources,
// add .httpServer(HttpServer.fromPort(8080))
SokletConfig config = SokletConfig.withSseServer(sseServer).build();

// Run one standalone lifecycle with automatic JVM shutdown handling
System.out.println("Starting Soklet");
Soklet soklet = Soklet.run(config);
soklet.awaitShutdown();

By default every run owns its JVM shutdown hook. The explicit Soklet.run(config) form returns a handle after readiness; awaitShutdown() waits for full finalization. Soklet does not read console input. For tests and finite embedded work, use Soklet.run(config, () -> { /* application work */ }); ending that callback requests shutdown and joins finalization. Application-owned input handlers can request shutdown explicitly. See scoped and console examples and process shutdown guidance.

Detailed SseServer configuration options are available in the Server Configuration documentation.

Heads Up!

HttpServer and SseServer are distinct and cannot share the same port.

In production environments, you might have your REST API resolvable at api.example.com and your SSE API resolvable at sse.example.com.

Soklet's SSE support is designed to work seamlessly with your existing setup. Your configured CorsAuthorizer still applies cross-domain security rules for SSE handshakes, your ResponseMarshaler still handles writing response data for rejected handshakes (and regular requests, if you also configured an HTTP server), your InstanceProvider and your Value Converters still work as you would expect, and so on.

Handshake queue wait and application handling share one timeout budget; request-line and header reading have an independent budget. A partial-header read timeout routes through ResponseMarshaler::forUnparsedRequest, whose default is 408 Request Timeout, before a complete request exists. Other eligible input rejections use that hook as well. Idle read timeouts and EOF before complete headers close quietly, including TCP health checks. See Server Configuration for the deadline settings.

References:

Event Source Methods

Event Source Methods are how SSE clients connect and "handshake" with your server. They look and code like regular Resource Methods, but have the following special characteristics:

An Event Source Method handles GET. A HEAD request to its SSE route receives a bodyless 405 through ResponseMarshaler::forMethodNotAllowed, without invoking the method, client initializer, or stream admission. OPTIONS advertises GET and OPTIONS. Ordinary HTTP routes retain their automatic HEAD-to-GET fallback.

Aside from the SSE-specific annotation and return type, parameter binding works the same way as for ordinary Resource Methods. @PathParameter, @QueryParameter, @RequestHeader, and @RequestCookie values still flow through Soklet's ValueConverterRegistry, so typed handshake inputs like Long chatId, Optional<UUID> tenantId, or Locale locale work as expected.

Event source methods can also accept the original Request. That request exposes parsed W3C trace data through Request::getTraceContext, and SseConnection::getRequest preserves the same request for lifecycle observers. Broadcast work is not automatically request-scoped; if fan-out work needs a trace, carry the relevant TraceContext explicitly in your own domain object.

Here's a minimal implementation:

public class ChatResource {
  // Use @SseEventSource, not @GET.
  // Return type must be declared as SseHandshakeResult
  @SseEventSource("/chats/{chatId}/event-source")
  public SseHandshakeResult chatEventSource(@PathParameter Long chatId) {
    // Accept the client handshake.
    // Soklet can now broadcast server-sent events to this client
    return SseHandshakeResult.accept();
  }
}

Accepting Handshakes

In the event of an accepted handshake, Soklet will write an HTTP 200 OK response to the client, along with a set of default headers - but no response body. The socket is then held open to support subsequent Event Broadcasting.

Here are the default headers:

  • Content-Type: text/event-stream; charset=UTF-8
  • Cache-Control: no-cache, no-transform
  • Connection: keep-alive
  • X-Accel-Buffering: no

When accepting a handshake, you may optionally specify your own headers and cookies.

Soklet owns the streaming connection framing. Application-provided Connection and Keep-Alive headers are ignored in favor of the canonical Connection: keep-alive header above. Framing-dangerous headers such as Content-Length and Transfer-Encoding, along with other unsupported hop-by-hop headers, cause the accepted handshake to fail closed.

A Content-Type supplied by SseHandshakeResult.Accepted must have exactly one value with the media type text/event-stream (case-insensitive); omit it to use the default above.

@SseEventSource("/chats/{chatId}/event-source")
public SseHandshakeResult chatEventSource(@PathParameter Long chatId) {
  // Declare some response headers
  Map<String, List<String>> headers = Map.of(
    "X-Powered-By", List.of("Soklet"),
    // Here we override a default header
    "X-Accel-Buffering", List.of("yes")
  );

  // Declare a response cookie
  List<ResponseCookie> cookies = List.of(
    ResponseCookie.withName("lastRequest")
      .value(Instant.now().toString())
      .httpOnly(true)
      .secure(true)
      .maxAge(Duration.ofMinutes(5))
      .sameSite(SameSite.LAX)
      .build()
  );

  // Supply to the "accepted" SseHandshakeResult builder
  return SseHandshakeResult.Accepted.builder()
    .headers(headers)
    .cookies(cookies)
    .build();
}

Post-Handshake Client Initialization

Soklet can "prime" one client through its initializer after an accepted handshake. Initializer writes reach that client before broadcaster deliveries. Broadcasts published before that client becomes active are not buffered for it, so replay-to-live continuity needs an application cursor or reconciliation protocol. An illustrative bounded replay using the browser's Last-Event-ID header appears in Client Initialization below.

References:

Rejecting Handshakes

Handshakes can be rejected when:

  1. You explicitly reject the handshake
  2. An exception bubbles out of your Event Source Method (or occurs during upstream/downstream request processing)
  3. Soklet cannot admit the connection, or its handshake budget expires

The default streamingLifecycleCapacity allows 256 retained SSE lifetimes, including pending initialization and cleanup. The separate concurrentConnectionLimit defaults to 8,192; setting it to zero leaves lifecycle admission bounded. Capacity rejection returns 503 before accepted headers or initialization, though the application's handshake method may already have run. Configure both limits for larger deployments; see SSE server configuration.

A rejected handshake writes a response - which might or might not include a response body - using the normal Soklet Response Marshaling workflow. Unlike accepted handshakes, the connection is closed immediately after writing the response.

Soklet owns rejected-response framing. It removes application Connection, Keep-Alive, Content-Length, Transfer-Encoding, TE, Trailer, Upgrade, and Proxy-Connection headers, along with fields named by Connection. It emits one Connection: close and computes Content-Length from the finite body, including an empty body. Status codes that forbid a body or a length retain those restrictions. Other response headers and cookies are preserved.

Finite SSE responses require a final status from 200 through 599, including responses supplied by custom timeout or capacity marshalers. Informational 1xx statuses cannot terminate a handshake. If capacity-response preparation fails, the server attempts a finite 500 response and reports the original failure.

Explicit Rejection

Here's how you can explicitly reject a handshake:

@SseEventSource("/chats/{chatId}/event-source")
public SseHandshakeResult chatEventSource(@PathParameter Long chatId) {
  // Choose a final status and optional headers, cookies, and finite body
  Response response = Response.withStatusCode(403)
    .body("You're not authorized")
    .build();

  // Goes through ResponseMarshaler::forResourceMethod, as normal
  return SseHandshakeResult.rejectWithResponse(response);
}

Implicit Rejection

With the default marshaler, returning null sends 204 No Content and rejects the handshake without an internal-error diagnostic. Browser EventSource clients stop reconnecting after 204. Prefer an explicit SseHandshakeResult acceptance or rejection so this decision is visible in your code.

You may also implicitly reject a handshake by throwing an exception:

@SseEventSource("/chats/{chatId}/event-source")
public SseHandshakeResult chatEventSource(@PathParameter Long chatId) {
  // Goes through ResponseMarshaler::forThrowable, as normal
  if(!userIsAuthorized(chatId))
    throw new ExampleException("You're not authorized");

  return SseHandshakeResult.accept();
}

References:

Event Broadcasting

You may broadcast SseEvent instances to clients by acquiring a handle to a SseBroadcaster. Any thread can broadcast while the transport is running. Acquisition may be unavailable before startup or after transport termination. During graceful shutdown, the default server can return a handle while it remains started; this does not admit new connections. A sibling HTTP handler can outlive SSE drain: use ifPresent for optional notifications so a completed transaction does not fail because the SSE transport has stopped. A retained handle with no recipients is a no-op. For example, your service layer might choose to fire off a broadcast after it persists a chat message, so anyone who is "listening" to the chat will see the update almost immediately.

Broadcasters are tied to concrete resource paths like /chats/123/event-source - not resource path declarations like /chats/{chatId}/event-source. Conceptually you are expressing: "I want to push SSE data to anyone who's listening to this particular URL." Every client who had a successful handshake with that URL and is still reachable will receive the broadcast.

// Get a reference to your SSE server...
SseServer sseServer = ...;

// ...acquire a broadcaster for a specific resource path...
ResourcePath resourcePath =
  ResourcePath.fromPath("/chats/123/event-source");

// ...construct the payload...
SseEvent event = SseEvent.withEvent("chat-message")
  .id(Instant.now().toString()) // any string you like
  .data("Hello, world") // often JSON
  .retry(Duration.ofSeconds(5))
  .build();

// ...and send it to all connected clients.
sseServer.acquireBroadcaster(resourcePath)
  .ifPresent(broadcaster -> broadcaster.broadcastEvent(event));

There is no need to invoke SseBroadcaster::broadcastEvent on a separate thread - you can assume the implementation will enqueue the event and return "immediately". Pushing data to clients over the wire will happen later on separate threads of execution.

Each connection has a bounded queue of pending writes, set by SseServer.Builder::connectionQueueCapacity (128 by default). A broadcast that finds a connection's queue full closes that connection with BACKPRESSURE and discards the writes still queued for it, without a log event. A loop can fill a queue faster than the connection's writer drains it, so a burst larger than the capacity can disconnect clients that are reading normally. Pace large bursts, or raise the capacity to cover the largest burst you send.

Browser EventSource dispatches a message only when the payload includes a data field. SseEvent.withEvent("ready").build() is legal but does not dispatch a browser message. Add .data("") to deliver an event with empty data. ID-only and retry-only payloads update reconnect state without dispatching a message, as specified by the EventSource dispatch rules.

retry sets the client's reconnect delay. Its non-negative whole-millisecond value must fit in a Java long; overflow is rejected when the event is built. The wire value discards fractional milliseconds, so a duration below one millisecond writes retry: 0. getRetry() retains the supplied duration. The client decides when to reconnect; this field does not control Soklet's heartbeat interval.

It's also possible to broadcast SSE "comment" payloads, which are distinct from true Server-Sent Events:

// Acquire broadcaster as usual...
ResourcePath resourcePath =
  ResourcePath.fromPath("/chats/123/event-source");

// ...and send a comment to all listeners on /chats/123/event-source.
// The below comment will write ": testing" to the socket
SseComment comment = SseComment.fromComment("testing");

sseServer.acquireBroadcaster(resourcePath)
  .ifPresent(broadcaster -> broadcaster.broadcastComment(comment));

It's unlikely you will need to broadcast comments in most applications unless you have special debugging or keepalive needs.

Soklet automatically sends periodic comment heartbeats. They keep idle streams active through compatible proxies and can expose a closed socket or failed write. A successful write into the local socket buffer does not prove that the client is still reachable. A silently disconnected peer can retain its connection and lifecycle slot until the transport detects failure, potentially for minutes depending on the OS and network. See dead peers and stream capacity.

Client Context and Memoized Broadcasting

If you'd like to broadcast different payloads to different groups of clients (for example, grouped by Locale), you can attach a per-connection client context during the handshake and then use Soklet's memoization-aware broadcast methods. The broadcaster will memoize payloads per unique key and reuse them across connections.

This is a common requirement in production systems. Your users can have different locales, time zones, roles, etc. and you may need to perform broadcasts which take those combinations into account to efficiently fire off "tailored" broadcasts.

@SseEventSource("/chats/{chatId}/event-source")
public SseHandshakeResult chatEventSource(
  @PathParameter Long chatId,
  Request request
) {
  // Ordered locales via Soklet's Accept-Language parsing
  List<Locale> locales = request.getLocales();
  Locale locale = locales.isEmpty()
    ? Locale.getDefault()
    : locales.get(0);

  // When accepting the handshake, store off the Locale on the connection.
  // The clientContext is of type Object, so use whatever value you like
  return SseHandshakeResult.Accepted.builder()
    .clientContext(locale)
    .build();
}

// Later, when broadcasting:
ResourcePath resourcePath = ResourcePath.fromPath("/chats/123/event-source");

// Group by Locale and memoize payloads per-locale
sseServer.acquireBroadcaster(resourcePath).ifPresent(broadcaster -> broadcaster.broadcastEvent(
  // First, turn the context into a key that represents a unique type of broadcast.
  // Here, it's just a broadcast per-Locale (e.g. US English and Brazilian Portuguese)
  // so we just return the Locale by casting our clientContext Object.
  // Real systems might specify a richer clientContext and map it to
  // a "key" type with Locale, ZoneId, user role, etc.
  (clientContext) -> (Locale) clientContext,
  // ...then, memoization guarantees we construct exactly 1 payload per-Locale
  (locale) -> SseEvent.withEvent("chat-message")
    .data(exampleLocalizedMessageFor(locale))
    .build()
));

This reduces serialization overhead when many clients share the same key. Memoization lasts for one broadcast call and supports null keys. The provider runs once per key even if it throws or its result cannot be serialized. Clients sharing that failed key receive no payload, while other groups continue. The failure does not close those connections; the next broadcast call can try again.

The built-in server logs a generation failure once per key with the affected connection count and original cause. It does not render the grouping key or client contexts in that grouped failure log. A key-selector failure remains per client because no key was obtained. See SSE testing for the corresponding simulator error-handler behavior.

Why Is This Important?

Scalability. Suppose you have 1,000 connected clients and 999 of them have the en-US locale.

Memoization means you only build 2 payloads (one for en-US and one for the remaining locale) instead of 1,000.

References:

Clustered Deployments

SseBroadcaster instances are local to the current Soklet node. A broadcast only reaches clients whose SSE connections are currently attached to that node.

For a clustered deployment, the usual pattern is:

  1. Persist the business event or enqueue it to a shared queue or pub/sub system.
  2. Have each Soklet node consume that shared event.
  3. On each node, acquire the appropriate local SseBroadcaster and perform the broadcast there.

This is usually a better fit than trying to route all clients for a given SSE resource path to a single node. In practice, distributed SSE systems commonly use Redis pub/sub, Kafka, SQS plus consumers, or similar shared infrastructure to fan events out across the cluster.

If you support reconnect catch-up with Last-Event-ID, the replay data should also come from a shared durable store or log, not from memory local to a single Soklet node.

Automated Testing

Soklet offers first-class support for SSE integration testing. See the Testing documentation for details and example code.

SSE GET handshakes must not carry a request body. The simulator rejects body bytes and applies the built-in listener's framing rules: Transfer-Encoding is forbidden, and Content-Length, if supplied, must be a single valid zero value.

Implementation Patterns

Client Initialization

There are scenarios in which it's useful to unicast SSE data to a client immediately after a successful handshake. For example:

  • You might want to push current state to the client right away
  • You might want to send an initial message for diagnostic or debugging purposes
  • The client temporarily lost network connectivity and now needs to "catch up" on missed messages via Last-Event-ID

Let's examine the "catch up" scenario below. Browser EventSource instances will keep track of the most-recent SSE id field they've seen, and in the event of a connection drop (network outage, laptop goes to sleep, etc.) and subsequent reconnect, the Last-Event-ID header will be set to the value of the most-recently-seen id.

Reconnection behavior depends on the client and failure. For example, Node's Undici EventSource can enter the permanent CLOSED state after a proxy 502 during deployment, so automatic reconnect is not a guarantee. If your client reports a terminal close, recreate it at the application level with bounded backoff and an application-owned resume cursor; a new instance does not inherit the old instance's last event ID. Test this through the deployed proxy.

The built-in SSE server decodes Last-Event-ID as UTF-8 and rejects malformed UTF-8. Prefer ASCII IDs, such as decimal sequence numbers or UUIDs, for interoperability with clients and proxies that handle non-ASCII HTTP header bytes differently.

It's the job of your server-side code to look for this header and provide whatever data the client needs to reconstitute itself.

Soklet provides a Client Initializer - a one-time function run after the SSE handshake is accepted and before broadcaster deliveries reach that client. A SseUnicaster lets the initializer queue SSE payloads for just this client.

Initializer payloads precede later SseBroadcaster deliveries to this connection. That is an ordering guarantee, not a gap-free replay guarantee: broadcasts published while the initializer is running are not retained for the newly connecting client. Applications that need exact continuity must define an event cursor or durable log and reconcile the replay with the live stream, including any duplicates.

Initializer writes are buffered until the connection becomes active and are hard-bounded by SseServer.Builder::connectionQueueCapacity (128 application writes by default). An initializer may fill that capacity exactly; Soklet's optional connection-verification heartbeat is accounted for separately and does not consume an application slot. Exceeding the bound throws IllegalStateException and terminates the already-accepted connection with BACKPRESSURE, even if the initializer catches the exception. Buffered writes may be discarded. Configure the capacity for the largest expected catch-up page with headroom for live broadcasts arriving before it drains, and paginate or otherwise limit larger Last-Event-ID replays before accepting the handshake.

@SseEventSource("/chats/{chatId}/event-source")
public SseHandshakeResult chatEventSource(
  @PathParameter Long chatId,
  // Browsers will send this header automatically on reconnects
  @RequestHeader(name="Last-Event-ID", optional=true) String lastEventId
) {
  Chat chat = myChatService.find(chatId);

  // Exceptions that bubble out will reject the handshake and go through the
  // ResponseMarshaler::forThrowable path, same as non-SSE Resource Methods
  if (chat == null)
    throw new NoSuchChatException();

  // Illustrative replay page: at most 64 events with the default 128-slot
  // queue. A durable cursor and replay/live reconciliation are needed for
  // gap-free delivery, including any additional replay pages.
  List<ChatMessage> catchupMessages = new ArrayList<>();

  if(lastEventId != null)
    catchupMessages.addAll(myChatService.findCatchups(chatId, lastEventId, 64));

  // Customize "accept" handshake with a client initializer
  return SseHandshakeResult.Accepted.builder()
    .clientInitializer(sseUnicaster -> {
      // Queue this client's replay page before later broadcaster deliveries.
      // Broadcasts published before activation are not buffered for it.
      catchupMessages.stream()
        .map(catchupMessage -> SseEvent.withEvent("chat-message")
          .id(catchupMessage.id())
          .data(catchupMessage.toJson())
          .retry(Duration.ofSeconds(5))
          .build())
        .forEach(event -> sseUnicaster.unicastEvent(event));
    })
    .build();
}

This example shows where one finite replay page goes; the service must enforce the 64-event limit, and the page size must fit your configured queue capacity with room for live broadcasts. It does not by itself close the race between querying findCatchups(...) and activating the new connection, or deliver any additional replay pages. For gap-free recovery, give events stable IDs and use an application cursor or reconciliation step backed by durable history. A client may need to de-duplicate events seen in both replay and live delivery.

Initializer Lifetime

The accepted 200 response is written before the initializer runs. An initializer exception terminates the stream with PRODUCER_FAILED and its cause, unless another reason already won. On the built-in server, LifecycleObserver and MetricsCollector receive didEstablishSseConnection, willTerminateSseConnection, and didTerminateSseConnection in order even if initialization fails before the connection joins a broadcaster. The establishment and termination events keep metrics paired. This does not produce a failed-handshake or internal connection-rejection event.

Before the accepted response is written, didFailToEstablishSseConnection distinguishes CAPACITY_EXCEEDED, HANDSHAKE_TIMEOUT, and HANDSHAKE_REJECTED. The last also covers finite route/method mismatch responses on the SSE listener, including HEAD and OPTIONS, even when no event-source method ran; a matched route can therefore receive a rejection metric for these requests. Processing, response preparation, and accepted-handshake response writing failures use INTERNAL_ERROR with their cause, including a peer disconnect before accepted headers are delivered. A routine peer disconnect while writing a rejection retains HANDSHAKE_REJECTED or CAPACITY_EXCEEDED and records the write cause.

The client initializer runs once, synchronously, for bounded setup or finite catch-up. Its queued messages are released after it returns successfully and before messages from a broadcaster. For example, a greeting requires no ongoing per-client task:

@SseEventSource("/updates")
public SseHandshakeResult updates() {
  return SseHandshakeResult.Accepted.builder()
    .clientInitializer(sseUnicaster -> {
      sseUnicaster.unicastEvent(SseEvent.withEvent("hello")
        .data("connected")
        .build());
    })
    .build();
}

The initializer uses the checked SseClientInitializer interface and may throw checked exceptions. Do not retain its SseUnicaster or register it as an upstream callback after initialization. For ongoing delivery, have the application publish through an SseBroadcaster; one broadcast reaches the clients currently listening on that resource path. A successful unicast means queue acceptance, not client acknowledgment, and queued messages may be discarded if the connection terminates.

References:

Custom SSE Transports

Applications can provide their own SseServer. Its admission-fenced RequestHandler returns an HttpRequestResult to the transport's response consumer. Use getMarshaledResponse() for the offered HTTP response and getSseHandshakeResult() for the application's logical acceptance or rejection decision. The handshake optional can be empty, such as when request processing fails before producing a handshake. A 200 response alone does not establish acceptance.

For an actually accepted connection, the transport preserves the client context and invokes any client initializer once after writing the accepted response. Initialization must be bounded. Queued catch-up writes and broadcaster activation wait for successful initialization; failure or prior termination prevents activation. Establishment observation precedes termination observation even when initialization fails, following the initializer failure contract.

The accessor does not run the initializer or prove that headers were committed, initialization succeeded or a connection became active. The initializer and context are application-owned references, so callers own their retention and any logging or disclosure. HttpRequestResult.toString() omits handshake data. The custom transport remains responsible for HTTP framing, queue bounds, connection lifetime, shutdown and termination proof; see the graceful shutdown guidance.

An accepted SSE response uses status 200; validate response headers and EventSource framing before writing it. Custom transports must deliver establishment, failed-handshake and termination callbacks to their lifecycle observer and metrics collector, contain callback failures, and preserve establishment-before-termination ordering. The public result does not expose the framework's handling-failure cause when the handshake optional is absent. A custom transport can therefore classify an explicit rejection, but cannot reproduce every built-in failure cause from that result alone.

Signing Tokens

SSE handshakes in browsers are limited by design: the HTTP method is always GET, you cannot supply custom headers to a native EventSource, and cookies cannot travel cross-origin by default (a common SSE scenario).

One approach is to specify withCredentials so your cookies (which might include authentication information) can travel cross-origin. However, this is not recommended because it increases CSRF attack surface area.

const EVENT_SOURCE_URL = 'https://sse.example.com/chats/123/event-source'

// URL and "withCredentials" are the only possible customizations
let eventSource = new EventSource(EVENT_SOURCE_URL, {
  withCredentials: true,
})

CORS and Event Source Credentials

If you are comfortable with your CSRF posture and choose to initialize your EventSource using withCredentials: true and are connecting to a cross-origin SSE Event Source Method, you will need to make sure your CORS configuration writes Access-Control-Allow-Credentials=true for the appropriate origin. For example:

Set<String> allowedOrigins = Set.of("https://www.revetware.com");

// Custom "Access-Control-Allow-Credentials=true" decider
Function<String, Boolean> allowCredentialsResolver = (origin) -> {
  return true;
};

SokletConfig config = SokletConfig.withSseServer(...)
  .corsAuthorizer(CorsAuthorizer.fromWhitelistedOrigins(
    allowedOrigins, allowCredentialsResolver
  ))
  .build();

See the CORS documentation for details.

We have established the above is not an ideal approach. So, how can you securely send credentials from the browser to Soklet?

A reliable and secure solution is to have your backend vend a cryptographically-signed, time-limited token like a JWT which is included as a query parameter in the EventSource URL.

This way, even if an attacker were to intercept request logs that include the full URL, she would not be able to "replay" authentication for the Event Source Method.

Here's how your JS code running in the browser might look:

// Make a call to your backend to get a signing token...
let signingToken = await obtainSigningToken()

// ...construct a URL with it...
let eventSourceUrl =
  'https://sse.example.com/chats/123/event-source' +
  `?signingToken=${encodeURIComponent(signingToken)}`

// ...and use the constructed URL to create the EventSource.
// Notice that we omit the less-secure "withCredentials: true" config
let eventSource = new EventSource(eventSourceUrl)

Here's how your Event Source Method might look:

@SseEventSource("/chats/{chatId}/event-source")
public SseHandshakeResult chatEventSource(
  @PathParameter Long chatId,
  // Require that clients specify a signing token
  @QueryParameter String signingToken
) {
  Chat chat = myChatService.find(chatId);

  // Exceptions that bubble out will reject the handshake and go through the
  // ResponseMarshaler.forThrowable(...) path, same as non-SSE Resource Methods
  if (chat == null)
    throw new ChatNotFoundException();

  // Perform cryptographic + expiry verification of the token here.
  // You might also mark it as "cannot be reused" in your database
  myAuthorizationService.verify(signingToken);

  // Accept the handshake with no additional data
  return SseHandshakeResult.accept();
}

Addendum: Using curl

To experiment with SSE functionality, you can create a simple webpage and use the Javascript API as outlined in Client Implementation, or use curl on the command line.

First, ensure you have an Event Source Method declared...

@SseEventSource("/hello-world")
public SseHandshakeResult helloWorld() {
  // Immediately accept, no special behavior
  return SseHandshakeResult.accept();
}

...and then spin up your SSE server on 8081.

SseServer sseServer =
  SseServer.fromPort(8081);

SokletConfig config = SokletConfig.withSseServer(sseServer)
  .build();

System.out.println("Starting Soklet");
Soklet soklet = Soklet.run(config);
soklet.awaitShutdown();

Now, use curl with output buffering disabled and response headers included:

curl -N -i http://localhost:8081/hello-world

The built-in SSE server treats a client input half-close (TCP FIN) as a disconnect, even if the client can still read. Clients must keep their request side open while receiving events. Piping a completed request into some netcat implementations closes that side immediately, so use curl -N or browser EventSource for this example.

After the handshake, the server discards surplus client input only up to maximumRequestSizeInBytes. Exceeding that budget terminates the stream as CLIENT_DISCONNECTED with an input-limit cause; an established SSE connection is not an upload channel.

Your Event Source Method will accept the initial handshake and immediately respond with SSE headers:

HTTP/1.1 200 OK
Content-Type: text/event-stream; charset=UTF-8
Cache-Control: no-cache
Cache-Control: no-transform
Connection: keep-alive
Date: Sat, 18 Oct 2025 13:04:12 GMT
X-Accel-Buffering: no

The socket is kept open until you press Ctrl+C. Soklet will periodically write "heartbeat" messages which look like this:

:

If you fire off a broadcast...

ResourcePath resourcePath = ResourcePath.fromPath("/hello-world");

SseEvent event = SseEvent.withEvent("hello")
  .data("testing\nmultiple\nlines")
  .id(Instant.now().toString())
  .retry(Duration.ofSeconds(5))
  .build();

sseServer.acquireBroadcaster(resourcePath)
  .ifPresent(broadcaster -> broadcaster.broadcastEvent(event));

...you'll see its payload written to the socket:

event: hello
id: 2025-10-18T13:04:46.750110Z
retry: 5000
data: testing
data: multiple
data: lines
Previous
HTTP Server Configuration