Sub topic 13
Streaming data with Server-Sent Events
This chapter assumes you know how to write a WebFlux annotated controller that returns Flux and Mono. It also assumes you understand that nothing runs until a subscriber arrives. If backpressure is unfamiliar, review that chapter first.
What Server-Sent Events are
Server-Sent Events (SSE) is a standard way for a server to push a stream of text messages to a client over one long-lived HTTP response. The client opens a normal GET request. The server keeps the connection open and writes events as they happen. The media type is text/event-stream.
SSE is one-way, from server to client. If the client must also send messages over the same connection, use WebSocket instead. SSE works over plain HTTP, so proxies and load balancers handle it easily. Browsers reconnect automatically through the EventSource API.
A Flux fits SSE well. Each element the Flux emits becomes one event on the wire, and the response stays open until the Flux completes, errors, or the client disconnects.
A first streaming endpoint
Return a Flux and declare text/event-stream as the media type:
@GetMapping(path = "/ticks", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Long> ticks() {
return Flux.interval(Duration.ofSeconds(1));
}Flux.interval emits a Long counter (0, 1, 2, ...) once per second. It never completes on its own, so the stream runs until the client closes the connection. Without the produces attribute, WebFlux would collect the elements into one JSON array and wait for completion, which would never happen here.
On the wire, each element is one event:
data:0
data:1
data:2You can test it with curl -N http://localhost:8080/ticks. The -N flag turns off output buffering so you see each event as it arrives.
What happens when the client leaves
When the client disconnects, WebFlux cancels the subscription. The cancel signal travels upstream through the operators to the source. This is how a producer learns it should stop work.
<br>
Controlling the event format
Returning a bare value gives you only a data: field. To set the event name, id, or retry interval, return a ServerSentEvent<T>:
@GetMapping(path = "/prices", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> prices() {
return Flux.interval(Duration.ofSeconds(1))
.map(seq -> ServerSentEvent.<String>builder()
.id(String.valueOf(seq))
.event("price-update")
.data("price-" + seq)
.build());
}The id lets a reconnecting browser send a Last-Event-ID header, so your server can resume from where the client stopped. The server does that part. WebFlux does not track the position for you.
Common mistakes
- Forgetting the media type. Without
text/event-stream, aFlux<T>is serialized as a JSON array, and the client sees nothing until theFluxcompletes. - Blocking inside the stream. A blocking call in a
mapstalls an event-loop thread. Every connected client shares those few threads. - Ignoring idle timeouts. Proxies often close connections that stay silent. Emit a periodic heartbeat event if your data is sparse.
- Unbounded sources. A fast producer feeding a slow client builds up memory. Use operators such as
onBackpressureDroporsampleto limit the rate.
Exercise
A controller method returns a Flux<Long> from Flux.interval(Duration.ofSeconds(1)) but has no produces attribute. A client sends a request with an Accept header of application/json. What does the client receive, and why?
Show answer
The client receives no data, and the request keeps waiting. With a JSON media type, WebFlux collects the elements into one JSON array and writes it only when the Flux completes. Flux.interval never completes, so nothing is sent. Adding produces = MediaType.TEXTEVENTSTREAM_VALUE (and having the client accept text/event-stream) makes each element go out as its own event.
Exercise
How would you make the /prices endpoint send a heartbeat comment every 15 seconds when no price changes, and what does the client's disconnect do to the heartbeat?
Show answer
Merge the price Flux with a second Flux built from Flux.interval(Duration.ofSeconds(15)) that maps each tick to ServerSentEvent.<String>builder().comment("heartbeat").build(). Both sources are part of the same merged pipeline. When the client disconnects, WebFlux cancels the merged subscription, and the cancel reaches both sources, so the heartbeat stops too.