Sub topic 14
Scaling connection servers and routing messages
This chapter assumes you know how a chat message flows between two users, as covered in the earlier chapters on the architecture and the one-to-one flow. You should also know that WebSocket connections are long-lived and stateful, and that a key-value store such as Redis can hold small records with a time-to-live (TTL).
Why one server is not enough
A single connection server holds many open WebSockets. Each connection costs a file descriptor, kernel socket buffers, and application memory for session state. A tuned server can often hold a few hundred thousand idle connections. In practice, memory per connection and the cost of heartbeats set the limit, not the CPU.
Suppose the system has 50 million concurrent users and each server comfortably holds 100,000 connections. You need at least 500 connection servers, plus headroom for failures and deploys. Once you have more than one, Alice and Bob are rarely connected to the same machine. Two problems follow:
- Placement: which server does a new connection land on?
- Routing: when Alice's server receives a message for Bob, how does it find Bob's server?
Placing connections: load balancing
Stateless HTTP APIs can be balanced with round robin because any server can handle any request. WebSockets differ in three ways:
- A connection lives for hours, so the balancer only decides once. A bad early choice cannot be corrected.
- Connection count, not request rate, is the load. Prefer least connections over round robin.
- Old servers accumulate connections while new servers stay empty, because clients rarely reconnect. After a scale-out, the new servers sit idle until clients reconnect.
A Layer 4 (TCP) balancer is cheap and passes the upgraded WebSocket through untouched. A Layer 7 (HTTP) balancer can route on headers and terminate TLS, but it must be configured with long idle timeouts, or it will cut quiet connections.
Reconnect storms
When a connection server dies, all of its clients reconnect at once. A server with 100,000 connections produces 100,000 handshakes within seconds, and each handshake involves authentication and a registry write. The same happens after a deploy or a network blip.
Defenses:
- Clients reconnect with exponential backoff and random jitter, so the retries spread out.
- Connection servers cap new handshakes per second and reject extras with a "retry later" response.
- Deploys use draining: the server stops accepting new connections, then asks clients to reconnect in small random batches.
Finding the recipient: the session registry
The common solution is a session registry: a fast shared store that maps each user to the connection server holding their connection.
- On connect, the server writes
user_id, device_id -> server_idwith a TTL. - On disconnect, the server deletes the entry.
- While the connection is alive, the server refreshes the TTL, usually on each heartbeat.
The TTL matters. If a server crashes, it cannot delete its entries. The TTL makes dead entries expire on their own, in the same way the presence heartbeats do. The cost is a short window in which the registry points to a dead server. During that window, a delivery attempt fails, and the message must fall back to the offline path described below.
Keep one entry per device, not per user. A user with a phone and a laptop may be connected to two different servers, and each device needs its own copy of the message.
Delivering across servers
Once the sender's server has looked up the target server, it needs a transport to hand over the message. There are four common options.
| Approach | How it works | Strength | Weakness |
|---|---|---|---|
| Registry lookup, then direct RPC | Sender's server calls the target server directly | Lowest latency, no extra hop | Needs a mesh of connections between servers |
| Per-server pub/sub channel | Each server subscribes to a channel named after itself. Senders publish to the target's channel | Simple, servers stay decoupled | Broker is an extra hop and a component to scale |
| Broadcast to all servers | Publish every message to every server, and each one checks for local recipients | No registry needed | Work grows with server count, which does not scale |
| Hash-based placement | Compute the server from `hash(user_id)` and force the client onto it | No registry lookup | Resizing moves users, and a hot server can't shed load |
Most designs choose the per-server channel with a registry. Message queues like Kafka can fill the same role. A partition per connection server gives you ordering and replay, at the cost of more operational weight.
The routing path
The server persists the message before routing it. Routing is only a delivery attempt, and the stored copy is what makes recovery possible if the attempt fails.
A runnable model of the routing layer
The following Python simulates the registry, the bus, and two connection servers in memory. It shows registration with TTL, delivery to multiple devices on different servers, and the fallback when a server is gone.
REGISTRY_TTL = 60
class Registry:
def __init__(self):
self.entries = {} # user_id -> {device_id: (server_id, expires_at)}
def register(self, user_id, device_id, server_id, now):
devices = self.entries.setdefault(user_id, {})
devices[device_id] = (server_id, now + REGISTRY_TTL)
def unregister(self, user_id, device_id, server_id):
devices = self.entries.get(user_id, {})
entry = devices.get(device_id)
if entry and entry[0] == server_id:
del devices[device_id]
def servers_for(self, user_id, now):
devices = self.entries.get(user_id, {})
return {sid for sid, expires in devices.values() if expires > now}
class Bus:
def __init__(self):
self.servers = {}
def subscribe(self, server):
self.servers[server.server_id] = server
def publish(self, server_id, event):
server = self.servers.get(server_id)
if server is None:
return False
server.deliver(event)
return True
class ConnectionServer:
def __init__(self, server_id, registry, bus):
self.server_id = server_id
self.registry = registry
self.sockets = {} # (user_id, device_id) -> list of received events
bus.subscribe(self)
def connect(self, user_id, device_id, now):
self.sockets[(user_id, device_id)] = []
self.registry.register(user_id, device_id, self.server_id, now)
def disconnect(self, user_id, device_id):
self.sockets.pop((user_id, device_id), None)
self.registry.unregister(user_id, device_id, self.server_id)
def deliver(self, event):
for (user_id, _), inbox in self.sockets.items():
if user_id == event["to"]:
inbox.append(event)
def route(registry, bus, event, now):
servers = registry.servers_for(event["to"], now)
delivered = sum(1 for sid in servers if bus.publish(sid, event))
return "delivered" if delivered else "offline"
registry, bus = Registry(), Bus()
s1 = ConnectionServer("s1", registry, bus)
s2 = ConnectionServer("s2", registry, bus)
s1.connect("bob", "laptop", now=0)
s2.connect("bob", "phone", now=0)
s2.connect("carol", "phone", now=0)
event = {"to": "bob", "seq": 1, "text": "hi"}
assert route(registry, bus, event, now=10) == "delivered"
assert s1.sockets[("bob", "laptop")] == [event]
assert s2.sockets[("bob", "phone")] == [event]
# Server s2 crashes. Its registry entries are stale until the TTL runs out.
del bus.servers["s2"]
assert route(registry, bus, {"to": "carol", "seq": 1}, now=10) == "offline"
# After the TTL, the stale entry is gone from the registry too.
assert registry.servers_for("carol", now=100) == set()The unregister method checks that the stored server_id matches the caller. Without this check, a slow disconnect on the old server can delete the entry a new server wrote moments earlier, after the device reconnected elsewhere.
Failure modes and edge cases
- Stale registry entry. The target server is dead or the user has moved. The publish fails or the event is dropped. The message is already stored, so treat the user as offline: send a push notification, and let the client fetch missed messages by sequence number when it reconnects.
- Race on reconnect. A device can briefly appear on two servers. Delivering to both is harmless because clients deduplicate by message ID. Idempotent handling makes this safe.
- Lost bus messages. A pub/sub channel without persistence may drop events when a subscriber restarts. That is acceptable only because clients sync from the message store using their last seen
seq. Never treat the bus as the source of truth. - Hot spots. A group with 100,000 members creates thousands of publishes per message. Batch by server: publish once per target server with the list of local recipients, rather than once per user.
- Registry as a bottleneck. Every message needs a lookup and every connection needs periodic refreshes. Shard the registry by
user_id, and avoid refreshing the TTL more often than necessary. A refresh every 30 seconds with a 60-second TTL is usually enough. - Uneven load. Servers that have been up longest hold the most connections. Rebalance by draining a fraction of connections from overloaded servers, rather than relying on new connections alone.
Scaling the other direction
Connection servers scale horizontally because they share nothing but the registry and the bus. Scale the pieces separately:
- Add connection servers when connection count or memory runs high.
- Add registry shards when lookup or refresh rate runs high.
- Add bus capacity when publish volume runs high. Group chat drives this the most.
- Scale the stateless API tier on request rate, independently of all the above.
Exercise
A connection server crashes while holding 80,000 connections. Name two things that go wrong in the first minute, and one mitigation for each.
Show answer
First, 80,000 clients try to reconnect at once, which overloads the remaining servers and the registry. Mitigate with exponential backoff plus jitter on the client and a handshake rate limit on the servers. Second, until the registry TTL expires, messages for those users are routed to the dead server and are lost in transit. Mitigate by treating a failed publish as "offline", sending a push notification, and letting the client sync from the message store by sequence number when it reconnects. A shorter TTL or a health-check process that removes the dead server's entries also narrows the window.
Exercise
Why does the registry store one entry per device instead of one per user, and why does unregister compare the server ID before deleting?
Show answer
A user can be connected from several devices on different servers, and each device needs its own copy of the message, so the registry must list every server. The server ID check prevents a stale disconnect from the old server from deleting the entry that the new server wrote after the device reconnected.