Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Your real-time feed must support 5 million concurrent WebSocket connections. How would you design the connection layer and message routing?

I would put the connections on a dedicated fleet of gateway nodes that only hold sockets, built on a non-blocking server such as Netty or with virtual threads, and keep business logic in separate services. A registry of which node holds each user's connection, or pub/sub topics per group of users, routes each message to the right node. Clients reconnect with a resume token and fetch what they missed, and load balancers must support long-lived connections and let nodes drain slowly during deploys.

Why this question is asked

Five million concurrent connections changes the problem. With ordinary request and response traffic, a connection lives for milliseconds and any instance can serve any request. A WebSocket lives for hours, it pins a user to one machine, and every deploy or crash disconnects a large number of people at once. Interviewers at this level want to see that we can size the fleet, route a message to the one node that can deliver it, and keep reconnect storms from taking the system down. In this answer, we will size the connection layer, separate it from business services, design message routing, handle reconnects without losing data, and look at load balancers and deploys.

1A Quick Recap: What a Connection Costs

A WebSocket is a long-lived, two-way connection that starts as an HTTP request and is then upgraded. Most of these connections are idle most of the time; a feed user might receive one message a minute. So the cost is not CPU, it is memory and file descriptors per open socket, plus the work of heartbeats.

On a non-blocking server such as Netty, which Spring WebFlux and Reactor Netty use, an idle connection costs roughly a few kilobytes to a few tens of kilobytes: buffers, the session object and the subscription state. With 20 KB per connection, 250,000 connections take about 5 GB of heap and native memory, which fits comfortably on a 16 GB node. For 5 million connections, that is 20 nodes, and we plan for at least 30 so that losing a zone or deploying a third of the fleet still leaves room. These are planning numbers; the real figure comes from a load test with our own message sizes.

2Dedicated Gateway Nodes

The first decision is to keep connections out of the business services. A gateway node does only three things: authenticate the connection when it opens, keep it alive with heartbeats, and write messages to it. Feed ranking, permissions and storage live in normal stateless services that scale and deploy independently.

The reason is that the two kinds of service have opposite needs. Business services change several times a day and should be restarted freely. Every restart of a connection holder disconnects up to 250,000 people. Keeping the gateway small and stable means it is deployed rarely, and a bug in feed logic cannot crash the sockets.

Step throughThe connection layer
  1. Clients5 million apps and browsers with one WebSocket each
  2. Load balancersL4 or WebSocket-aware L7, long idle timeouts
  3. Gateway nodesabout 30 Netty nodes, sockets and heartbeats only
  4. Routingconnection registry in Redis, or pub/sub topics per user group
  5. Business servicesfeed, notifications, permissions; stateless
  6. Event logKafka topics with the messages to deliver

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

3Non-Blocking Servers or Virtual Threads

Holding 250,000 connections with one platform thread each would need 250,000 threads with their own stacks, which no JVM handles well. A non-blocking server multiplexes all sockets over a few event-loop threads, usually one per CPU core, so idle connections cost no thread at all. Spring WebFlux on Reactor Netty, or plain Netty, is the proven choice for this layer.

Virtual threads, final since Java 21, give another option: one cheap virtual thread per connection with simple blocking code, because a blocked virtual thread does not hold an operating-system thread. It reads more simply, but we must check for pinning and per-connection memory. For a dedicated gateway whose job is exactly multiplexing, I would still start with Netty and measure.

Java
// The gateway's handler on Spring WebFlux: no thread per connection
public Mono<Void> handle(WebSocketSession session) {
String userId = auth.userId(session.getHandshakeInfo()); // checked at upgrade
Flux<WebSocketMessage> out = deliveries.forUser(userId) // messages routed to this node
.mergeWith(Flux.interval(Duration.ofSeconds(25)).map(i -> PING))
.map(json -> session.textMessage(json));
registry.register(userId, nodeId); // userId -> this node, with a TTL
return session.send(out)
.doFinally(s -> registry.unregister(userId, nodeId)); // on close or error
}

Notice that the operating system must also allow it: raising the file-descriptor limit well above 250,000, tuning TCP buffer sizes, and giving the load balancer enough source ports or IP addresses, since one source IP talking to one backend port has only about 64,000 ports.

4Routing a Message to the Right Node

A business service wants to deliver a message to user 123, and only one of 30 gateways holds that socket. There are two common designs.

The first is a connection registry. When a user connects, the gateway writes user 123 -> gateway 17 into Redis with a TTL of a minute or two, refreshed by heartbeats. A delivery service looks up the node and sends the message directly to it, for example to a per-node Kafka partition or over gRPC. This is precise, and each message travels to one node only. Its cost is keeping the registry fresh: a node that crashes leaves entries behind until the TTL expires, and messages sent to it in that window are dropped, which the resume logic below must cover.

The second is pub/sub by group. Users are hashed into, say, 1,024 groups, every gateway subscribes to the groups of the users it currently holds, and producers publish to the user's group topic. There is no lookup, at the cost of some nodes receiving messages for users they do not hold. Broadcasts go to one topic that every gateway reads and fans out locally.

5Reconnects Without Losing Messages

Connections will drop constantly at this scale: phones change networks, nodes restart, and a single failed node disconnects 250,000 people at once. Every message gets a sequence number per user, and the client stores the last one it saw. On reconnect it sends that number as a resume token, and the gateway asks the feed service for everything newer before it starts streaming live messages. So the live socket is an optimisation, and the store is the source of truth.

The dangerous part is the herd. If 250,000 clients reconnect in the same second, they hammer authentication and the resume query together. Clients must reconnect with exponential backoff and random jitter, and the resume path must be cheap, ideally a range read on a per-user list in Redis.

Step throughReconnecting with a resume token
ClientLoad balancerGateway 9Feed serviceRegistry
upgrade, token, last seq 1041 (after jittered backoff)
route to a healthy node
user 123 -> gateway 9, TTL 90 s
items for user 123 after 1041
1042, 1043
send 1042, 1043, then live messages

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

The store is the source of truth; the socket only makes delivery fast.

6Load Balancers and Deploys

Load balancers built for short requests often close connections after 60 seconds of idleness or spread new connections badly. We need one that supports long-lived WebSocket connections, an idle timeout above our heartbeat interval, and balancing based on current connection counts rather than requests, since a node that just started has zero connections and should receive more.

Deploys need the most care. We never restart a gateway abruptly. Instead the node is drained: it is removed from the load balancer for new connections, then it closes its existing connections gradually, for example 5 percent a minute, sending each client a close message telling it to reconnect. Over 20 minutes the clients move to other nodes without a spike. A full fleet rollout therefore takes hours, which is another reason to keep gateway code small and to deploy it rarely.

7Follow-up questions

Why not let every business service hold its own WebSocket connections?

Then each service would need sticky routing, would disconnect users on every deploy, and would duplicate authentication and heartbeat logic. A single gateway layer gives one connection per device instead of one per feature, and lets business services stay stateless.

What happens to messages sent to a node that just crashed?

They are lost from the live path, because the socket is gone. The registry entry expires within its TTL, the clients reconnect elsewhere and use their resume token to fetch every item after their last sequence number, so the user still receives them, only a few seconds later.

8Conclusion

In this answer, we sized a fleet of about 30 gateway nodes at 250,000 connections each, kept them separate from business services, and used Netty or carefully measured virtual threads so that idle connections cost no threads. We routed messages through a connection registry or group pub/sub topics, made reconnects lossless with per-user sequence numbers and resume tokens, protected the system from reconnect storms with jittered backoff, and used long-lived-connection load balancers with slow draining during deploys.

What to say in the interviewAbout 90 seconds aloud

Open with

First I would size it. An idle connection on Netty costs on the order of tens of kilobytes, so a node can hold a few hundred thousand; at 250,000 per node, 5 million is 20 nodes, and I would run about 30 for headroom.

Then, if they want more

I would make those nodes a dedicated gateway layer that only authenticates, keeps heartbeats and writes messages, so business services stay stateless and can deploy freely without disconnecting people. The gateway runs on a non-blocking server like Reactor Netty; virtual threads are an option, but I would measure memory and pinning first.

For routing, each gateway records user to node in Redis with a TTL refreshed by heartbeats, and delivery services send to that node. Alternatively users are hashed into groups and gateways subscribe to the groups they hold. Broadcasts go to a topic every gateway reads.

Every message has a per-user sequence number, and on reconnect the client sends its last one as a resume token, so the store is the source of truth and the socket is only a fast path. Clients reconnect with jittered exponential backoff to avoid storms.

Finally, load balancers must allow long idle times and balance by connection count, and during deploys I drain each node gradually over several minutes rather than restarting it.

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 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 "Your real-time feed must support 5 million concurrent WebSocket connections. How would...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/150764ef4c/