Sub topic 13
Streaming data with Server-Sent Events
This chapter assumes you can write an annotated WebFlux controller that returns Mono and Flux. It also assumes you know the basics of operators and backpressure from earlier chapters. You will use Flux to push a continuing stream of events to a client over plain HTTP.
What Server-Sent Events are
Server-Sent Events (SSE) is a standard in which the server keeps one HTTP response open and writes events to it over time. The response has the media type text/event-stream. It is one-way: the server sends and the client listens. If the client also needs to send messages over the same connection, use WebSockets instead.
On the wire, an event is a block of text lines ending in a blank line:
id: 42
event: price
data: {"symbol":"ACME","value":10.5}
Browsers provide the EventSource API, which parses this format and reconnects automatically if the connection drops. After a reconnect it sends a Last-Event-ID header containing the last id it saw.
SSE suits dashboards, notifications, progress updates, and live feeds. It is a good fit for WebFlux because an open stream costs a subscription, not a blocked thread.
The simplest stream
Return a Flux and declare the event-stream media type. WebFlux then flushes each element to the client as it is emitted.
@GetMapping(path = "/ticks", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Long> ticks() {
return Flux.interval(Duration.ofSeconds(1));
}Without produces, WebFlux would pick another media type. For a Flux<Long> it would normally collect the elements into a JSON array. The client would then see nothing until the Flux completed, and this Flux never completes.
Three behaviors matter here:
- Each client that connects subscribes separately. Every client gets its own
Flux.interval, with its own timer. - When the client disconnects, WebFlux cancels the subscription. The upstream stops, and any
doFinallyordoOnCancelhooks run. - Each element is encoded as the
data:field. Strings are written as-is, and objects are written as JSON.
The request and the stream over time
Controlling the event fields with ServerSentEvent
To set id, event, retry, or a comment, wrap each element in ServerSentEvent<T>.
@GetMapping(path = "/prices", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<Price>> prices() {
return priceService.stream()
.map(price -> ServerSentEvent.<Price>builder()
.id(String.valueOf(price.sequence()))
.event("price")
.data(price)
.build());
}With a named event, a browser client listens using addEventListener("price", ...). Events without a name arrive on the generic onmessage handler.
Respecting slow clients
Reactor operators honor backpressure, so a slow client slows the whole pipeline. Flux.interval is a source that cannot wait. It emits on a timer, and if downstream has not requested demand it fails with an overflow error. When a client's network is slow, you must decide what to do with the events it cannot take.
| Operator | Behavior when the client is behind | Use when |
|---|---|---|
| `onBackpressureDrop()` | Discards new events | Only the freshest data matters |
| `onBackpressureLatest()` | Keeps only the newest pending event | Dashboards and gauges |
| `onBackpressureBuffer(n)` | Queues up to `n` events, then errors | Every event matters and bursts are short |
@GetMapping(path = "/ticks-safe", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Long> ticksSafe() {
return Flux.interval(Duration.ofMillis(10))
.onBackpressureLatest();
}An unbounded buffer on a long-lived stream is a memory leak waiting for a slow client. Always set a limit.
Broadcasting to many clients
Using Flux.interval creates a separate source per subscriber. Real applications usually have one event source, such as a message arriving in a service, and many connected clients. A Sinks.Many lets code push events into a Flux that all clients share.
@Service
public class NotificationService {
private final Sinks.Many<String> sink =
Sinks.many().multicast().directBestEffort();
public synchronized void publish(String message) {
sink.tryEmitNext(message);
}
public Flux<String> stream() {
return sink.asFlux();
}
}
@RestController
public class NotificationController {
private final NotificationService service;
public NotificationController(NotificationService service) {
this.service = service;
}
@GetMapping(path = "/notifications",
produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> notifications() {
return service.stream();
}
@PostMapping("/notifications")
public Mono<Void> send(@RequestBody String message) {
service.publish(message);
return Mono.empty();
}
}Several details in this code are deliberate:
directBestEffort()delivers each event to the subscribers that can accept it right now. It skips slow ones instead of buffering. ChooseonBackpressureBufferif you want buffering, but know that its defaultautoCancelterminates the sink when the last subscriber leaves. Passfalsefor the second argument ofonBackpressureBuffer(int, boolean)to turn that off.tryEmitNextmust not be called from two threads at once. A concurrent call returnsFAIL_NON_SERIALIZEDand the event is lost. Thesynchronizedkeyword serializes the calls.tryEmitNextreturns anEmitResult. This example ignores it, but production code should check for failures.
Keeping idle connections alive
Proxies and load balancers often close connections that carry no data for 30 to 60 seconds. If events are rare, merge in a periodic comment line. Clients ignore comments, but the traffic keeps the connection open.
@GetMapping(path = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> events() {
Flux<ServerSentEvent<String>> data = service.stream()
.map(msg -> ServerSentEvent.<String>builder().data(msg).build());
Flux<ServerSentEvent<String>> heartbeat = Flux.interval(Duration.ofSeconds(15))
.map(i -> ServerSentEvent.<String>builder().comment("keep-alive").build());
return Flux.merge(data, heartbeat);
}Resuming after a reconnect
EventSource resends the last id it received in the Last-Event-ID header. WebFlux does not replay anything for you. Read the header and decide what to send.
@GetMapping(path = "/history-events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> resumable(
@RequestHeader(name = "Last-Event-ID", required = false) String lastId) {
long from = lastId == null ? 0 : Long.parseLong(lastId) + 1;
return eventStore.readFrom(from)
.map(e -> ServerSentEvent.<String>builder()
.id(String.valueOf(e.sequence()))
.data(e.payload())
.build());
}Here eventStore is your own store that returns a Flux of stored events. Resuming requires that events have increasing ids and that you keep them somewhere.
Errors in a stream
Once the first event is written, the status line and headers are already sent. If the Flux then fails, the server cannot switch to a 500 status. It terminates the response, and EventSource treats this as a dropped connection and reconnects. Handle expected failures inside the pipeline, so one bad element does not end the stream.
return service.stream()
.onErrorResume(ex -> Flux.empty());For failures that are worth retrying, apply retryWhen upstream. Errors that occur before the first element can still produce a normal error response.
Consuming SSE with WebClient
A Java client can read a stream with WebClient. Ask for bodyToFlux and the stream stays open until you cancel.
WebClient client = WebClient.create("http://localhost:8080");
Flux<ServerSentEvent<String>> events = client.get()
.uri("/events")
.accept(MediaType.TEXT_EVENT_STREAM)
.retrieve()
.bodyToFlux(new ParameterizedTypeReference<ServerSentEvent<String>>() {});
events.take(5).subscribe(e -> System.out.println(e.data()));Do not apply timeout(Duration.ofSeconds(2)) to a whole stream. That timeout applies between signals, so it is useful for detecting a silent server, but only if the interval is longer than your heartbeat.
Testing a stream
An infinite stream never completes, so a test must take a limited number of elements. WebTestClient gives you the body as a Flux, and StepVerifier checks it.
class TickControllerTest {
private final WebTestClient client =
WebTestClient.bindToController(new TickController()).build();
@Test
void streamsThreeTicks() {
Flux<Long> body = client.get().uri("/ticks")
.accept(MediaType.TEXT_EVENT_STREAM)
.exchange()
.expectStatus().isOk()
.returnResult(Long.class)
.getResponseBody();
StepVerifier.create(body.take(3))
.expectNext(0L, 1L, 2L)
.verifyComplete();
}
}This test takes about three seconds in real time. For longer intervals, use StepVerifier.withVirtualTime so the test does not wait.
Common mistakes
- Forgetting
produces = TEXT_EVENT_STREAM_VALUE, so the response is buffered as JSON. - Calling a blocking method inside the stream, which stalls the event loop for every connected client.
- Using an unbounded buffer for slow clients.
- Emitting to a
Sinks.Manyfrom several threads without serializing. - Expecting an HTTP error status after the stream has started.
Exercise
A dashboard endpoint returns Flux.interval(Duration.ofMillis(5)) as text/event-stream. Some clients on slow networks receive an error and the stream ends. Why does that happen, and which operator would you add if only the newest value matters?
Show answer
Flux.interval emits on a timer and cannot wait for demand. When a slow client has not requested more elements, Reactor signals an overflow error and the stream terminates. Adding onBackpressureLatest() keeps only the newest pending element, so slow clients skip stale values and the stream continues.
Exercise
A message-broadcast service uses Sinks.many().multicast().onBackpressureBuffer(). After the last connected client leaves, new clients get no events. What is the cause and what are two ways to fix it?
Show answer
The default autoCancel behavior terminates the sink when its last subscriber cancels, so later subscribers receive nothing. Fix it by using onBackpressureBuffer(capacity, false) to disable autoCancel, or by using directBestEffort() if dropping events for slow subscribers is acceptable.