Find which server holds a user
Server A has a message for Bob, but Bob’s socket is on server C.
Say it like this
Sockets are stateful, so I keep a registry of user to connection server in Redis with a TTL refreshed by heartbeats, and any server can route a message by one lookup.
Basic solution
On connect, write user → server into a shared registry with a TTL; look it up to route, or publish to a per-server channel.
Routing a message through the registry
Each connection server writes its users into Redis with a TTL. The chat service does one lookup per message and forwards to the right server, or to the inbox and push when nothing is found.
How it works
- Bob's app opens a WebSocket. The load balancer picks connection server C, and C checks Bob's token and accepts the socket.
- C writes the mapping bob -> C into the registry, a Redis key whose value is the server name, with a TTL of about 60 seconds (SET bob C EX 60). On every heartbeat from Bob's socket, C resets that TTL, so the entry stays alive exactly as long as the socket does.
- Alice sends Bob a message through her own connection server A. A hands it to the chat service, which writes the message to the message store first, then asks the registry for bob and gets back C.
- The chat service forwards the message frame to C, either over a persistent internal connection to C or by publishing to a Pub/Sub channel named after C. C receives the frame and writes it to Bob's socket.
- If the registry returns nothing for bob, Bob is offline. The message stays in his inbox row in the database, and a push notification is sent through APNs or FCM so his phone can wake the app.
- When Bob disconnects cleanly, C deletes the entry. If C crashes and never deletes it, the entry expires on its own when the TTL runs out, because nobody is refreshing it any more.
Why a TTL rather than explicit delete only
- Servers crash without cleaning up. With a TTL, a dead entry can misroute messages for at most one heartbeat interval before it disappears; without one it would misroute until someone noticed.
Worked example
Routing in the chat app
- 10M online users across 40 connection servers, each holding 250K sockets.
- Registry: one entry per user, about 60 bytes with key and value, so 600 MB in Redis. One primary plus a replica holds it comfortably.
- Writes: a heartbeat every 30 seconds refreshes the TTL, so 10M / 30 = 333K writes per second. Pipelined from each server (its 250K keys refreshed in batches of 1,000) that is about 330 pipeline round trips per second across the fleet, well within one Redis node, but shard the registry by user id across 4 nodes to leave headroom.
- Reads: 500K messages per second, one lookup each, so 500K GETs per second; with 4 shards that is 125K per node.
- Alternative without a registry: broadcast every message to all 40 servers and let each check its local table. That is 500K x 40 = 20M frames per second of internal traffic to deliver 500K messages. The registry removes 97 percent of it.
Variants and when each wins
Central registry (Redis, user -> server)
- One key per connected user holding the server name, read once per message and refreshed by heartbeats. It wins because it is exact and simple; the cost is that the registry sits on the delivery path, so it needs a replica and a fallback.
Per-server Pub/Sub channels with a registry
- The same lookup, but the chat service delivers by publishing to a channel named after the target server instead of holding a direct connection to it. It wins when there are many connection servers, because no component has to maintain a connection to every other one.
Consistent hashing of users to servers
- No registry at all: the server for a user is computed by hashing the user id onto the set of servers, and the load balancer routes new sockets the same way. It wins when connections are evenly spread and the server set rarely changes; a server change moves users and forces reconnects.
Broadcast to all servers
- Every message is sent to every connection server and each one checks its own local table. It wins only for a handful of servers or very low message rates, because internal traffic grows with the number of servers.
Recommendation: Redis registry with TTL plus per-server channels; mention the consistent hashing option as the stateless alternative.
Failure modes
Stale entry after a server crash
- Messages for Bob vanish for up to a minute even though his phone shows him online. It happens because server C died, nobody deleted bob -> C, and the chat service keeps forwarding to a server that no longer exists. Set the TTL to two heartbeat intervals so the entry expires quickly, and when a forward to C fails, delete the entry immediately and treat Bob as offline for that message.
Two entries for one user
- Bob gets messages on his phone but not on his laptop. It happens because the registry stores one value per user, so the second device's registration overwrote the first and only one socket is ever found. Key the registry by user and device, or store a set of connections per user and forward to all of them.
Registry shard down
- All delivery stops for a quarter of users at once. It happens because the registry is on the critical path of every message and one of its four shards is unreachable. Run each shard with a replica and automatic failover, and when a lookup times out, fall back to writing the inbox row and sending a push, so the message arrives late instead of not at all.
Heartbeat write storm
- Redis CPU sits at 100 percent doing nothing but TTL refreshes. It happens because every one of millions of sockets refreshes its own key with its own command. Batch the refreshes per connection server using pipelining, and lengthen the heartbeat interval for connections that are idle.
Lookup races with a reconnect
- A message is forwarded to the old server while Bob is in the middle of reconnecting to a new one, and the old server has no socket for him. It happens because the chat service read the registry entry a moment before it changed. Have the old server return a not-connected error, let the sender retry the lookup once, and rely on the inbox row to guarantee the message is not lost in between.
Interviewer follow-ups
Answer out loud before you open each one.
How does server A actually get the bytes to server C?
Either a mesh of persistent internal connections between the chat service and every connection server, or a Pub/Sub channel per server that the chat service publishes to. Channels are simpler to operate because nobody maintains a connection to everyone; the mesh has slightly lower latency.
What TTL would you set, and what happens if it is too long or too short?
About two heartbeat intervals, so 60 seconds for a 30 second heartbeat. Too long and a crashed server keeps swallowing messages for its users; too short and a single missed heartbeat marks an online user offline and triggers unnecessary push notifications.
Could you avoid the registry entirely?
Yes, by hashing users to servers consistently and having the load balancer route by user id, so the server is computable. The cost is that connections are no longer balanced by load, a ring change disconnects users, and the balancer needs the user id before authentication.
How does the registry handle a user with three devices?
Store a set of connections per user, each with its own server and TTL, and deliver to every member. Receipts then come from each device, and the message is marked delivered when any device acks and read when any device reads.
Connections
- In study paths
- Real-time delivery
- Built on
- Hash table · Consistent hash ring
- Pairs with
- Push to the browser in real time · Track online status cheaply · Deliver to users who are offline · Fan one event out to many consumers · Expire data automatically
- Pulls against
- Keep servers stateless
- Used in
- Chat App (WhatsApp / Messenger)
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 | Connection server A, Connection 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 |