Video in progress
In a chat application, users are connected to different servers over WebSocket. How does A's message reach the server B is connected to?
You need a registry that stores who is connected to which server (for example, Redis) and a message channel between servers (Redis Pub/Sub, Kafka or direct gRPC). The message is first written to the DB, then routed to B's server.
📖 Answer
A WebSocket connection is pinned to one server. If A is on ws-3 and B is on ws-7, ws-3 can't write to B directly.
The typical flow:
- When B connects,
ws-7writes to Redis:presence:B -> ws-7(with a TTL, refreshed by a heartbeat every 30 seconds). - A sends a message.
ws-3stores it in the DB through the chat service and gets amessageId. A message that hasn't been stored isn't delivered. ws-3finds B's server in the registry and sends tows-7: on thenode:ws-7channel in Redis Pub/Sub, or through internal gRPC.ws-7writes the message to B's socket, and B returns anack.- If B isn't online — to the push notification service.
There's a simpler variant: every server receives all messages from one Pub/Sub channel and checks "is this user on me?". It works with 5–10 servers, but every server reads the whole traffic — it won't scale further.
What not to forget:
- B may be connected from several devices — the registry stores a set.
- Pub/Sub is "fire and forget": if
ws-7happens to be restarting at that moment, the message is lost. So the source of truth is the DB, and when B reconnects it asks "give me everything after the lastmessageIdI saw". - On the load balancer, raise the idle timeout for WebSocket, otherwise connections keep dropping at 60 seconds.
Sign up to mark studied questions and save your progress.