Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

How would you push new notifications to a browser from a Spring Boot application using server-sent events, and what happens when you run several instances?

In Spring MVC we return an SseEmitter from a controller, keep it in a registry keyed by user, and call send() on it when a notification arrives; in WebFlux we return a Flux<ServerSentEvent<?>> with the text/event-stream media type. With several instances, each browser is connected to only one of them, so every instance subscribes to Redis pub/sub or a message broker and delivers the events for the users it holds. Event ids, timeouts and heartbeats make reconnects and proxies behave.

Why this question is asked

Notification badges, order status updates and live dashboards all need the server to talk first, without the browser asking. Server-sent events are the simplest way to do that over plain HTTP, and they work well with Spring Boot. Interviewers ask this question because the single-instance version is easy, and the interesting part is what breaks when the application runs behind a load balancer on three or ten instances. In this answer, we will recap what server-sent events are, build the endpoint in Spring MVC and WebFlux, keep track of open connections, make reconnects lossless with event ids, and then spread events across several instances.

1A Quick Recap of Server-Sent Events

Server-sent events, or SSE, are a standard way for a server to keep an HTTP response open and write small text messages into it whenever it wants. The browser opens the connection with the built-in EventSource object, and the server answers with the content type text/event-stream. Each message is a few lines of text such as id: 42, event: notification and data: followed by the payload, ended by a blank line.

SSE only goes one way, from server to browser. That is exactly what notifications need, and it is the reason SSE is simpler than WebSocket: there is no special protocol upgrade, it passes through most proxies as ordinary HTTP, and the browser reconnects by itself when the connection drops. When the browser must also stream messages back, WebSocket fits better.

2Returning an SseEmitter in Spring MVC

In Spring MVC, a controller method that returns an SseEmitter tells Spring to keep the response open after the method returns. The request thread goes back to the pool, and any other thread can later call send() on the emitter to write an event.

Java
@RestController
class NotificationController {
private final EmitterRegistry registry;
NotificationController(EmitterRegistry registry) { this.registry = registry; }
@GetMapping(path = "/notifications/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
SseEmitter stream(@AuthenticationPrincipal Jwt jwt,
@RequestHeader(value = "Last-Event-ID", required = false) String lastId) {
String userId = jwt.getSubject();
SseEmitter emitter = new SseEmitter(Duration.ofMinutes(30).toMillis()); // timeout in ms
registry.add(userId, emitter);
emitter.onCompletion(() -> registry.remove(userId, emitter));
emitter.onTimeout(() -> registry.remove(userId, emitter));
emitter.onError(e -> registry.remove(userId, emitter));
registry.replayAfter(userId, lastId, emitter); // send what the browser missed
return emitter; // response stays open
}
}
// Sending one event later, from any thread:
emitter.send(SseEmitter.event().id("42").name("notification").data(dto));
// on the wire: id:42 event:notification data:{"text":"Order shipped"}

Notice the three callbacks. An emitter that is finished, timed out or broken must leave the registry, otherwise the registry grows forever and every send to a dead emitter throws an exception. The registry itself is a ConcurrentHashMap from user id to a set of emitters, because one user can have several tabs open, and each tab is its own connection.

3The Same Endpoint in WebFlux

In Spring WebFlux, the reactive web stack, we return a stream of events instead of an object we write to. Spring writes each element of the Flux as one event.

Java
@GetMapping(path = "/notifications/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<ServerSentEvent<NotificationDto>> stream(@AuthenticationPrincipal Jwt jwt) {
Flux<ServerSentEvent<NotificationDto>> events = sink.forUser(jwt.getSubject())
.map(n -> ServerSentEvent.builder(n).id(n.id()).event("notification").build());
Flux<ServerSentEvent<NotificationDto>> pings = Flux.interval(Duration.ofSeconds(20))
.map(i -> ServerSentEvent.<NotificationDto>builder().comment("ping").build());
return Flux.merge(events, pings); // events plus a heartbeat every 20 seconds
}

The cleanup happens on its own here: when the browser goes away, WebFlux cancels the subscription, and the per-user stream stops. That is one reason WebFlux suits a service that holds many open connections, since no thread is parked per connection.

4Event Ids, Reconnects and Heartbeats

Browsers reconnect automatically when an SSE connection drops, after a short delay the server can set with a retry: line. When they reconnect, they send the id of the last event they received in the Last-Event-ID header. If we give every notification an increasing id and keep recent notifications in a store (the database table that holds notifications, or a Redis stream), the endpoint can send everything after that id before it starts sending live events. So a phone that went through a tunnel loses nothing.

Idle connections are the other trap. Load balancers and proxies close connections that carry no data for a while, often after 60 seconds. A heartbeat, a comment line sent every 15 to 30 seconds, keeps the connection alive and also reveals dead clients, because the send fails. In Spring MVC we also set an emitter timeout (or spring.mvc.async.request-timeout), so that connections are recycled now and then instead of living for days. The browser simply reconnects with its last id.

5What Happens With Several Instances

Now we run three instances behind a load balancer. Alice's browser opened its stream on instance 2, so her emitter lives in the memory of instance 2 only. The order service publishes an event saying her order shipped, and the request that triggers it may land on instance 1. Instance 1 looks in its registry, finds no emitter for Alice, and the notification is lost. With one instance this could never happen, which is why the bug often appears only in production.

The fix is to stop assuming that the instance that creates a notification also holds the connection. Each instance subscribes to a shared channel, such as a Redis pub/sub channel, a RabbitMQ fanout exchange or a Kafka topic that every instance reads with its own consumer group. Whoever creates a notification publishes it there. Every instance receives it, checks its local registry, and the one holding Alice's emitter sends it; the others ignore it.

Step throughDelivering a notification across instances
Order serviceInstance 1Redis pub/subInstance 2Alice's browser
POST /notifications for Alice
store notification id 42
publish to channel notifications
message: no emitter for Alice here
message: Alice has an emitter here
id:42 event:notification data:...

6 messages in order. Play them, or step through them one at a time.

Every instance hears every notification; only the one holding the connection sends it.

Redis pub/sub is fire and forget: an instance that is restarting misses messages. That is acceptable here because the notification is also stored, and the browser's reconnect with Last-Event-ID fills the gap. For very large numbers of users, broadcasting everything to every instance becomes wasteful, and we would route by user to the right instance instead, but for a few instances the broadcast is simple and correct.

6Follow-up questions

Why not just use sticky sessions on the load balancer?

Sticky sessions decide which instance receives the browser's requests, but the notification is usually created by a different request, often from another service or a background job, that has nothing to do with Alice's session. So stickiness does not tell the producer where the connection is. We still need a shared channel or a routing table.

How many SSE connections can one Spring MVC instance hold?

With classic Tomcat, the waiting connection does not hold a request thread, because SseEmitter uses asynchronous request processing, but each connection still costs a socket and some memory. A few thousand per instance is normal; tens of thousands need tuning of connection limits such as server.tomcat.max-connections, or a move to WebFlux or virtual threads. Under HTTP/1.1 browsers also allow only about six connections per host, so many tabs can block each other; HTTP/2 removes that limit.

Should notifications be sent from inside the database transaction?

No. Publish after the commit, for example from a @TransactionalEventListener or an outbox table, so that a browser never sees a notification for a change that was later rolled back.

7Conclusion

In this answer, we saw that a Spring MVC controller returns an SseEmitter and a WebFlux controller returns a Flux of ServerSentEvent with the text/event-stream type. We kept a per-user registry and removed emitters on completion, timeout and error, gave every event an id so a reconnecting browser can resume from Last-Event-ID, and added heartbeats and timeouts for proxies. With several instances, the connection lives on one of them, so every instance listens on Redis pub/sub or a broker and delivers to the users it holds.

What to say in the interviewAbout 80 seconds aloud

Open with

I would expose a GET endpoint that produces text/event-stream. In Spring MVC it returns an SseEmitter, which I store in a registry keyed by user id, and I remove it in the onCompletion, onTimeout and onError callbacks so dead connections do not pile up.

Then, if they want more

In WebFlux I would return a Flux of ServerSentEvent instead, and cancellation does the cleanup for me. Every notification gets an increasing id and is stored, so when the browser reconnects, which EventSource does automatically, it sends Last-Event-ID and I replay what it missed.

I also send a comment heartbeat every twenty seconds or so, because proxies tend to cut idle connections after about a minute, and I set a timeout so connections recycle. The real issue with several instances is that a user's connection sits in the memory of one instance, while the notification is usually created somewhere else.

So I publish every notification to Redis pub/sub or a broker topic that all instances subscribe to. Each instance checks its local registry and sends the event if it holds that user's emitter. Pub/sub can drop messages during a restart, but because notifications are stored and the browser resumes from its last id, nothing is lost for the user. I would also publish only after the transaction commits.

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 official documentation for the version you use. 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 "How would you push new notifications to a browser from a Spring Boot application using...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/c061d19190/