Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Show how to push progress updates to a browser with server-sent events in Spring MVC and in WebFlux.

In Spring MVC we return an SseEmitter from a text/event-stream endpoint, keep it in a registry, and call emitter.send(SseEmitter.event().id(..).name("progress").data(..)) whenever progress changes, then complete() at the end; onTimeout, onCompletion and onError remove it from the registry. In WebFlux we return a Flux<ServerSentEvent<T>> with produces = text/event-stream. In both cases the browser's EventSource reconnects automatically and sends the last id in a Last-Event-ID header, so the server can resume.

Why this question is asked

Long-running operations, such as an import that takes two minutes or a report being generated, need a way to tell the user how far they are. Polling every second works but wastes requests and still feels laggy. Server-sent events, SSE, give us a simple push channel over plain HTTP, and Spring supports them in both of its web stacks. Interviewers ask for this because the happy path is short but the details, timeouts, cleanup and reconnection, are where real implementations break. In this answer, we will recap the SSE protocol, write the Spring MVC version, the browser side, the WebFlux version, and then handle reconnection with Last-Event-ID.

1A Quick Recap of Server-Sent Events

SSE is a one-way stream from server to browser over an ordinary HTTP response. The client sends a GET, the server answers with Content-Type: text/event-stream and never finishes the response; instead it writes small text blocks, one per event, whenever it has something to say. Each event is a few lines such as id:, event: and data:, ended by a blank line. The browser's built-in EventSource object parses these blocks and fires a JavaScript event for each one.

Because it is plain HTTP, SSE works through most proxies and load balancers, benefits from HTTP/2, and needs no special protocol upgrade. The trade-off is direction: the server pushes, and if the client wants to say something it sends a normal HTTP request.

Java
HTTP/1.1 200 OK
Content-Type: text/event-stream
id:7
event:progress
data:{"percent":42}
id:8
event:progress
data:{"percent":43}

Each block is one event. The id is what the browser remembers for reconnection, the event name lets the client listen for specific kinds, and data carries the payload, usually JSON.

2The Spring MVC Version With SseEmitter

In Spring MVC, the controller returns an SseEmitter. Spring starts async processing, writes the response headers, and keeps the connection open. Whoever holds the emitter can send events later, from any thread, which is why we store it in a registry keyed by the job id.

Java
@RestController
class ProgressController {
private final Map<String, Set<SseEmitter>> registry = new ConcurrentHashMap<>();
@GetMapping(path = "/jobs/{id}/progress", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
SseEmitter progress(@PathVariable String id) {
SseEmitter emitter = new SseEmitter(Duration.ofMinutes(30).toMillis()); // async timeout
registry.computeIfAbsent(id, k -> ConcurrentHashMap.newKeySet()).add(emitter);
emitter.onCompletion(() -> remove(id, emitter)); // normal end or client gone
emitter.onTimeout(() -> { remove(id, emitter); emitter.complete(); });
emitter.onError(e -> remove(id, emitter));
return emitter; // response stays open
}
void publish(String id, long seq, Progress p) { // called by the job
for (SseEmitter e : registry.getOrDefault(id, Set.of())) {
try {
e.send(SseEmitter.event().id(Long.toString(seq)).name("progress").data(p));
} catch (IOException ex) {
e.completeWithError(ex); // browser closed the tab
}
}
}
void finish(String id) {
registry.getOrDefault(id, Set.of()).forEach(SseEmitter::complete); // ends the stream
}
}

The callbacks matter more than they look. Without them, every closed browser tab leaves an emitter in the map forever, and the service slowly leaks memory and wastes time sending to dead connections. Notice also the timeout in the constructor. An SseEmitter created without one uses the MVC async default, which falls back to the servlet container's default (30 seconds in Tomcat), so a stream that should last minutes would be cut off early.

data(p) is serialised with the same message converters as a response body, so a record becomes JSON. complete() ends the HTTP response cleanly, and the browser sees the stream end.

3The Browser Side

On the client, EventSource does the work. We listen for our named event and close the source when the job is done, otherwise the browser would reconnect.

Java
const source = new EventSource('/jobs/81f2/progress');
source.addEventListener('progress', e => {
const p = JSON.parse(e.data); // {percent: 42}
bar.style.width = p.percent + '%';
if (p.percent === 100) source.close(); // stop automatic reconnects
});
source.onerror = () => console.log('connection lost, browser will retry');

That is the whole client. There is no library, no handshake and no reconnection code, because EventSource has it built in.

4The WebFlux Version With Flux<ServerSentEvent<T>>

In WebFlux, a stream of events is simply a Flux. We map each progress value to a ServerSentEvent, which lets us set the id and event name, and declare text/event-stream.

Java
@GetMapping(path = "/jobs/{id}/progress", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<ServerSentEvent<Progress>> progress(@PathVariable String id) {
Flux<ServerSentEvent<Progress>> events = jobs.progress(id) // Flux<Progress> from a Sinks.Many
.map(p -> ServerSentEvent.<Progress>builder()
.id(Long.toString(p.seq()))
.event("progress")
.data(p)
.build());
Flux<ServerSentEvent<Progress>> heartbeat = Flux.interval(Duration.ofSeconds(15))
.map(i -> ServerSentEvent.<Progress>builder().comment("keepalive").build());
return Flux.merge(events, heartbeat)
.takeUntilOther(jobs.finished(id)); // complete when the job ends
}
Spring MVC and WebFlux side by side
ConcernSpring MVCWebFlux
Return typeSseEmitterFlux<ServerSentEvent<T>>
Sending an eventemitter.send(event().id().name().data())emit a value into the Flux
End of streamemitter.complete()Flux completes
Client disconnectonCompletion / onError callbackssubscription cancelled
Timeoutconstructor or MVC async defaultnone by default; add take or timeout

There is no registry to clean up by hand. When the browser disconnects, WebFlux cancels the subscription, and the Flux stops; any doFinally on it runs the cleanup. The heartbeat is a comment line (it starts with a colon on the wire), which the browser ignores but which keeps proxies from closing an idle connection.

5Reconnecting and Resuming With Last-Event-ID

Connections drop: a laptop sleeps, a mobile network switches, a deploy restarts an instance. EventSource then reconnects by itself after a short delay, which the server can set with a retry: field (reconnectTime in Spring's builder). On that new request, the browser adds a Last-Event-ID header with the id of the last event it received.

The server can use it to resume instead of starting over. In MVC we read the header and send what was missed before switching to live events.

Java
@GetMapping(path = "/jobs/{id}/progress", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
SseEmitter progress(@PathVariable String id,
@RequestHeader(value = "Last-Event-ID", required = false) Long lastId) {
SseEmitter emitter = register(id);
if (lastId != null) {
for (ProgressEvent e : history.after(id, lastId)) { // events 9, 10, 11 were missed
emitter.send(SseEmitter.event().id(Long.toString(e.seq())).name("progress").data(e.progress()));
}
}
return emitter;
}

For progress bars, resuming is often trivial: we just send the current percentage, because only the latest value matters. For notifications, where every event counts, we keep a short history per stream and replay everything after lastId. This only works if ids increase in a known order, which is why we use a sequence number rather than a random id.

6Follow-up questions

How many SSE connections can a browser keep open?

Under HTTP/1.1, browsers limit connections per host to about six, and every open EventSource uses one, so several tabs can exhaust the limit and block other requests to the same host. Under HTTP/2, many streams share one connection and the limit effectively disappears, which is one reason to serve SSE over HTTP/2.

Why do events arrive in one batch at the end instead of one by one?

Something between the server and the browser is buffering the response: a reverse proxy, a compression filter or the server's own buffer. With nginx, sending X-Accel-Buffering: no or turning proxy buffering off for the stream fixes it. Spring flushes after each send, so the server side is usually not the cause.

Can SseEmitter be used from a background thread?

Yes, that is its purpose. send() is safe to call from another thread, but calls for one emitter should not overlap; if several threads publish to the same emitter, we serialise them, for example with a single-threaded executor per stream or a synchronized block.

7Conclusion

In this answer, we pushed progress updates with server-sent events. In Spring MVC, the endpoint returns an SseEmitter with an explicit timeout, keeps it in a registry, sends named events with ids and calls complete() at the end, while onTimeout, onCompletion and onError remove it from the registry. In WebFlux, it returns Flux<ServerSentEvent<T>> with text/event-stream, and disconnects cancel the Flux. The browser's EventSource reconnects automatically with a Last-Event-ID header, which lets the server resume from where the client left off.

What to say in the interviewAbout 80 seconds aloud

Open with

Server-sent events are a one-way stream over normal HTTP: the server responds with text/event-stream and keeps writing small blocks with an id, an event name and data. In Spring MVC I return an SseEmitter from a GET mapping that produces text/event-stream.

Then, if they want more

I create it with an explicit timeout, because otherwise the MVC async default, which falls back to Tomcat's 30 seconds, ends it early. I store the emitter in a concurrent registry keyed by the job id, and the job calls emitter.send with SseEmitter.event().id(sequence).name("progress").data(progress), and complete() at the end.

I always register onCompletion, onTimeout and onError to remove the emitter, otherwise closed tabs leak. In WebFlux it is simpler: the method returns a Flux of ServerSentEvent built with id, event and data, and when the client disconnects the subscription is cancelled. I would merge in a comment heartbeat every 15 seconds so proxies do not close idle connections.

On the client, EventSource listens for the progress event. If the connection drops, the browser reconnects automatically and sends the last id it saw in the Last-Event-ID header, so I use increasing sequence ids and replay what was missed, or just the current value for a progress bar.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Show how to push progress updates to a browser with server-sent events in Spring MVC and...": https://scrivio-interview-library.netlify.app/spring-boot/web-other/735feca253/