Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

A dashboard needs live order updates from a JAX-RS service. Compare server-sent events using Sse and SseEventSink, long polling with AsyncResponse, and WebSockets, and describe how you would scale the chosen option to 50,000 open connections.

For a dashboard that only receives updates, I would choose server-sent events: a @GET method producing MediaType.SERVER_SENT_EVENTS with an injected SseEventSink and Sse, one-way over plain HTTP, with automatic browser reconnects using Last-Event-ID and SseBroadcaster for fan-out. Long polling with AsyncResponse works without holding a thread but pays for a reconnect after every event, and WebSockets add bidirectional messaging we do not need along with different proxy, auth and tooling requirements. To reach 50,000 connections, I would use non-blocking I/O or virtual threads, set proxy idle timeouts and send heartbeats, put a message bus behind the nodes so any node can deliver any event, and protect against slow consumers with bounded buffers and a disconnect policy.

Why this question is asked

Live updates sound like a front-end feature, but most of the difficulty is on the server: tens of thousands of connections that stay open for hours, proxies that silently close idle ones, and events that must reach users connected to a different node. Interviewers ask this design question because choosing between SSE, long polling and WebSockets is easy to get wrong for fashion reasons, and scaling any of them requires understanding connections rather than requests. In this answer, we will compare the three options, write the SSE endpoint in JAX-RS, see how reconnects work, and then design the system for 50,000 open connections, including the slow consumer problem.

1Comparing the Three Options

Server-sent events, SSE, is a standard for a server to push a stream of text events over one long HTTP response. The browser's EventSource API reads it and reconnects automatically. Long polling means the client sends a request that the server holds open until there is news or a timeout, answers it, and the client immediately sends the next request. WebSockets upgrade an HTTP connection into a full-duplex channel where both sides can send messages at any time.

SSE, long polling and WebSockets
ConcernSSELong pollingWebSockets
Directionserver to clientserver to clientboth ways
Protocolplain HTTP responserepeated HTTP requestsHTTP upgrade, then frames
Reconnectbuilt in, with Last-Event-IDevery event costs a new requestwrite it yourself
Proxies and authnormal HTTP rulesnormal HTTP rulesupgrade support, separate auth handling
JAX-RS APISse, SseEventSink, SseBroadcasterAsyncResponseJakarta WebSocket, separate API
Best forlive feeds, dashboardsold clients, rare eventschat, collaborative editing, games

The deciding question is direction. The dashboard receives order updates; it does not need to send messages over the same channel, and its rare actions can be normal REST calls. That makes SSE the simplest fit. It also works through ordinary HTTP infrastructure, uses normal headers and cookies for authentication, and gets reconnect logic for free.

2Writing the SSE Endpoint

In JAX-RS 2.1 and later, an SSE resource method injects an SseEventSink, the open connection to one client, and Sse, a factory for events and broadcasters. The method returns immediately; the sink stays open.

Java
@Path("/orders/stream")
@ApplicationScoped
public class OrderStream {
@Context Sse sse;
private volatile SseBroadcaster broadcaster;
@PostConstruct
void init() {
broadcaster = sse.newBroadcaster();
broadcaster.onClose(sink -> metrics.disconnected());
broadcaster.onError((sink, t) -> metrics.failed());
}
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public void subscribe(@Context SseEventSink sink,
@HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER) String lastId) {
if (lastId != null) {
for (OrderEvent e : recent.since(lastId)) sink.send(event(e)); // replay what was missed
}
broadcaster.register(sink); // returns at once, sink stays open
}
void onOrderChanged(OrderEvent e) { // called by the message bus listener
broadcaster.broadcast(event(e));
}
private OutboundSseEvent event(OrderEvent e) {
return sse.newEventBuilder().id(e.sequence()).name("order")
.mediaType(MediaType.APPLICATION_JSON_TYPE).data(OrderEvent.class, e).build();
}
}
// On the wire:
// id: 18342
// event: order
// data: {"orderId":42,"status":"SHIPPED"}

Notice the id on every event. When the connection drops, the browser reconnects after a short delay and sends Last-Event-ID: 18342, so the server can replay what was missed from a small recent-events buffer. Injecting Sse into a field of an application-scoped resource is how the specification examples do it; in some setups we inject it into the method instead, so check your implementation.

3Long Polling With AsyncResponse

For comparison, long polling suspends the request without holding a thread, using AsyncResponse.

Java
@GET @Path("/orders/poll")
public void poll(@QueryParam("after") long after, @Suspended AsyncResponse response) {
response.setTimeout(25, TimeUnit.SECONDS);
response.setTimeoutHandler(r -> r.resume(Response.noContent().build())); // 204: nothing new, ask again
waiting.add(after, response); // resumed later when an event arrives
}

This works everywhere, but each event costs a full request and response, headers, authentication and routing, and between polls the client is not listening, so the server must buffer events per client. At high event rates, that overhead is far larger than SSE.

4Scaling to 50,000 Open Connections

The first constraint is connections, not CPU. With a thread-per-connection model, 50,000 connections would need 50,000 platform threads, which is not workable. SSE with SseBroadcaster does not hold a thread per client in Jersey or RESTEasy when the container supports async I/O, and on Java 21 or later virtual threads make the blocking model cheap too. Each connection still costs memory for socket buffers and objects, perhaps 20 to 50 KB, so 50,000 connections need 1 to 2.5 GB across the fleet, which we spread over, say, 5 nodes of 10,000 each. File descriptor limits on each host must be raised above that number.

The second constraint is the infrastructure in between. Load balancers and proxies close connections that look idle, often after 60 seconds. We send a heartbeat comment every 20 to 30 seconds and set idle timeouts above that interval, disable response buffering on the proxy for this path (otherwise events arrive in bursts), and accept that any connection can drop at any time, which is fine because the client reconnects with Last-Event-ID. Over HTTP/1.1, browsers limit connections per host to about 6, so a user with several tabs can exhaust them; HTTP/2 removes that limit by multiplexing.

The third constraint is fan-out across nodes. An order changes on whichever node handled the write, but the users who care are connected to all 5 nodes. So events go through a message bus, for example a Kafka topic or Redis pub/sub, and every node subscribes and broadcasts to its own local connections.

Step throughSSE delivery at 50,000 connections
  1. Browsers with EventSourcereconnect with Last-Event-ID
  2. Load balanceridle timeout above the heartbeat, no buffering, HTTP/2
  3. 5 JAX-RS nodes, about 10,000 sinks eachSseBroadcaster, async I/O or virtual threads
  4. Message busevery node subscribes to order events
  5. Order servicepublishes an event for every change

5 layers, from the top down. Step through them one at a time.

5Handling Slow Consumers

Some clients read slowly: a laptop on a train, a frozen tab. If the server queues events for them without limit, one slow client can use megabytes, and a thousand of them can exhaust the heap. So each connection gets a bounded buffer, for example 100 events. When it fills, we apply a policy: drop the oldest events and send a resync event telling the dashboard to reload its state, or disconnect the client and let it reconnect with Last-Event-ID. For a dashboard that shows current order status, dropping intermediate updates is often fine, because only the latest state matters, so we can even collapse queued events per order. The send() method returns a CompletionStage, so we can see failures per sink and close sinks that keep failing.

6Follow-up questions

When would you choose WebSockets instead?

When the client must send a steady stream of messages back on the same channel with low latency, such as chat, collaborative editing or games. For a dashboard that receives updates and occasionally calls an API, SSE is simpler and fits HTTP infrastructure better.

How do you authenticate an SSE connection?

The browser's EventSource sends cookies but cannot set an Authorization header, so with a session cookie it works naturally. With bearer tokens we use a fetch-based SSE client that can set headers, or a short-lived ticket in the URL obtained through a normal authenticated call. Because the connection lives for hours, we also re-check authorization periodically, or close connections when the token expires so the client reconnects with a fresh one.

Does SSE work with HTTP/2?

Yes, and it works better: many streams share one connection, so the per-host connection limit disappears. The server still sends one long response per subscription.

7Conclusion

In this answer, we compared SSE, long polling with AsyncResponse, and WebSockets, and chose SSE for a one-way dashboard feed because it is plain HTTP with built-in reconnects through Last-Event-ID and broadcast support in JAX-RS. We wrote the endpoint with SseEventSink, Sse and SseBroadcaster, then scaled it to 50,000 connections with async I/O or virtual threads, raised connection limits, heartbeats under the proxy idle timeout, no proxy buffering, a message bus for cross-node fan-out, and bounded per-client buffers with a drop or disconnect policy for slow consumers.

What to say in the interviewAbout 80 seconds aloud

Open with

The dashboard only receives updates, so I would pick server-sent events. In JAX-RS that is a GET method producing MediaType.SERVER_SENT_EVENTS that injects an SseEventSink and Sse, registers the sink with an SseBroadcaster and returns immediately.

Then, if they want more

Events carry an id, and when the connection drops the browser's EventSource reconnects and sends Last-Event-ID, so I replay recent events from a small buffer. Long polling with AsyncResponse also avoids holding a thread, but every event costs a new request and the client misses events between polls.

WebSockets are bidirectional, which we do not need, and they bring different proxy, auth and tooling requirements.

For 50,000 connections the limit is connections, not CPU: I would use async I/O or virtual threads, spread them over several nodes with raised file descriptor limits, send heartbeats every 20 or 30 seconds, set the load balancer idle timeout above that, turn off proxy buffering for the stream, and prefer HTTP/2.

Because an order changes on one node but users are connected to all of them, every node subscribes to a message bus like Kafka or Redis and broadcasts locally. Finally, slow consumers get bounded buffers, and when one fills I either drop old updates and send a resync event, or disconnect them so they reconnect.

About this answer

Last updated
12 November 2026
Versions it names
Java 21
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.
Official documentation
Jakarta EE specifications
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 "A dashboard needs live order updates from a JAX-RS service. Compare server-sent events...": https://scrivio-interview-library.netlify.app/java/jax-rs/02fced5302/