How do you scale WebSocket connections across many servers?
Topic: microservices, Real-Time Communication. Level: Hard.
Answer
WebSockets are **stateful**: a connection lives on one server, so a message from user A (on server 1) to user B (on server 2) needs cross-server routing. Solutions: a **pub/sub backplane** (Redis Pub/Sub, Kafka, NATS) so any server can broadcast to connections held elsewhere; **sticky sessions** at the load balancer so a client stays on its server; store connection→server mappings for targeted delivery; and scale horizontally with connection limits per node. Add heartbeats (ping/pong) to detect dead connections and clean up.
```js
// Backplane: publish to Redis; every app server subscribes and pushes to its local sockets
redisPub.publish('room:general', JSON.stringify(msg)) // from server 1
redisSub.subscribe('room:general')
redisSub.on('message', (_ch, payload) => {
const msg = JSON.parse(payload)
for (const ws of localSocketsInRoom('general')) ws.send(payload) // on every server
})
// LB uses sticky sessions so a client's frames land on the server holding its socket.
```