Push to the browser in real time
Chat, presence and live updates need server-to-client pushes, not polling.
Say it like this
Chat needs sub-second server push, so I hold one WebSocket per client on stateless connection servers and keep a registry of which server holds each user, so any service can route a message to the right socket.
Basic solution
Keep a persistent WebSocket per client on connection servers; route messages to the server that holds the user’s socket.
Routing a message between connection servers
Alice is on server A, Bob on server C. The chat service persists first, looks Bob up in the registry, then pushes to server C, which writes the frame to his socket.
How it works
- The client opens an ordinary HTTP connection and sends an Upgrade: websocket header; the load balancer (an L4 balancer, or a sticky L7 one) forwards it to a connection server, which switches the connection into a persistent two-way socket.
- The connection server authenticates the token sent with the upgrade, keeps the socket open, and writes user → server into a shared registry (Redis) with a TTL, so other services can find which server holds this user.
- The client sends frames (small messages) over the socket; the server forwards each one to the chat service over an internal RPC or a queue, so the connection server never runs business logic.
- To deliver to user B, the chat service looks B up in the registry to find B's server, then sends the message to that server, by direct RPC or by publishing to a Pub/Sub channel that server subscribes to. That server writes the frame to B's socket.
- Heartbeats every ~30 s keep the socket alive through proxies that close idle connections and refresh the registry entry; a missed heartbeat makes the server close the socket and delete the entry.
- On reconnect the client sends the sequence number of the last message it saw, and the server replays anything newer, so a dropped socket loses nothing.
Why connection servers are separate
- They hold the only state in the system that cannot be moved, the open sockets, and nothing else, so they scale by connection count and can be replaced or redeployed without touching message logic.
Worked example
Chat app, 50M DAU
- Concurrent connections at peak ≈ 20% of DAU = 10M sockets, each held open by one server.
- One connection server with 16 GB can hold ~250K idle sockets (about 20–50 KB each with kernel and application buffers), so ~40 servers for 10M, say 60 with headroom and zone spread.
- Heartbeats: 10M / 30 s ≈ 330K small frames per second across the fleet, ~5.5K/s per server. Cheap on the socket side, but the registry refresh must be batched: one Redis pipeline per server per interval instead of 5.5K individual SETs, or Redis becomes the bottleneck.
- Message rate: 50M × 40 messages/day = 23K/s average, ~70K/s peak. Each is one registry lookup and one frame write, well within budget.
- Registry: 10M entries × ~60 B = 600 MB in Redis, replicated so a registry failure does not strand every user.
Variants and when each wins
WebSocket
- One persistent socket per client over which either side can send at any time, with a few bytes of overhead per message. It wins for chat and collaborative apps; it needs sticky routing and a registry because the socket lives on one server.
- A single long-lived HTTP response that the server keeps appending events to, with automatic reconnection built into browsers. It wins for feeds and notifications where the client only listens; sends still go over normal HTTP requests.
- The client sends a request that the server holds open until there is data or a timeout, then the client immediately sends the next one. It works through every proxy and wins as the fallback, at the cost of one request per message and constant reconnects.
MQTT or gRPC streams
- MQTT is a lightweight publish-subscribe protocol whose broker does the fan-out, which wins for constrained mobile or IoT clients; gRPC bidirectional streams win for service-to-service pushes inside the data centre.
Use WebSocket for two-way, low-latency traffic; SSE when the client only listens; long polling as the fallback for restricted networks.
Failure modes
Server loss drops all its sockets
- 250K clients reconnect at once and the reconnect storm hits the balancer and the registry together. It happens because a deploy or crash closed every socket on one server at the same instant. Fix it by draining connections gradually before shutdown, having clients reconnect with jittered backoff so they spread out, and replaying from a cursor so no message is lost.
Stale registry entries
- Messages are routed to a server that no longer holds the user, and vanish. It happens because the server died without deleting its registry entries. Fix it with a TTL on every entry that heartbeats refresh, and have the receiving server reply "not here" so the sender falls back to the offline delivery path.
Proxies killing idle sockets
- Connections drop every 60 s for some users. It happens because a load balancer or a corporate proxy on the path closes any connection that has been idle for its timeout. Fix it with heartbeats sent more often than the shortest timeout on the path, and configure your own balancer for long-lived connections.
Uneven connection distribution
- One server sits at its socket limit while others are half empty. It happens because the balancer used round-robin rather than least-connections, or because a reconnect storm after one server restarted landed on whichever server was next. Fix it with least-connections balancing at L4, and have a server refuse new connections when it nears its limit.
Message lost between servers
- A message is acknowledged to the sender but never arrives. It happens because it was written to a socket that closed in the middle of the write. Fix it by writing to the durable inbox before pushing, so the push is only an optimisation, and let the client's cursor-based sync fill any gap.
Interviewer follow-ups
Answer out loud before you open each one.
How does server A know that user B is connected to server C?
A shared registry, usually Redis, maps user id to connection server id with a TTL refreshed by heartbeats. A looks up B and either calls C directly or publishes to a channel C subscribes to. If the entry is missing, B is offline and the message takes the inbox-and-push path instead.
How many connections can one server hold, and what limits it?
Memory per socket is the usual limit: kernel buffers plus the application object, 20–50 KB each, so a 16 GB box holds a few hundred thousand idle sockets. File descriptor limits and the number of active (not idle) sockets, which cost CPU for frame handling, are the next constraints.
What does the client do when the socket drops?
Reconnect with exponential backoff and jitter so a server loss does not become a stampede, then send its last-seen sequence number per conversation. The server replays from the inbox or history, so the socket only needs to be at-least-once; ordering and gaps are handled by sequence numbers.
Can you avoid the registry entirely?
Yes, by having every connection server subscribe to a Pub/Sub channel per user it holds, and publishing messages to the user channel. The broker then does the routing. It is simpler but puts every message through the broker and makes per-user channels at 10M users a scaling concern of its own.
Connections
- In study paths
- Real-time delivery
- Pairs with
- Find which server holds a user · Deliver to users who are offline · Track online status cheaply · Order events within a stream
- Pulls against
- Keep servers stateless · Spread traffic across servers
- Used in
- Chat App (WhatsApp / Messenger) · Ride Matching (Uber / Lyft)
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 | Conn server A, Conn server C | Compute Engine | Azure Virtual Machines | DigitalOcean Droplets, any VM or bare metal |
| Amazon EC2 Auto Scaling | Chat service | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon ElastiCache | Registry (Redis) | Memorystore | Azure Managed Redis | Redis, Valkey, Memcached |
| Amazon Keyspaces | Message store | Bigtable | Managed Instance for Apache Cassandra | Apache Cassandra, ScyllaDB |