Video in progress

Strong Middle 🏗️ System design

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:

  1. When B connects, ws-7 writes to Redis: presence:B -> ws-7 (with a TTL, refreshed by a heartbeat every 30 seconds).
  2. A sends a message. ws-3 stores it in the DB through the chat service and gets a messageId. A message that hasn't been stored isn't delivered.
  3. ws-3 finds B's server in the registry and sends to ws-7: on the node:ws-7 channel in Redis Pub/Sub, or through internal gRPC.
  4. ws-7 writes the message to B's socket, and B returns an ack.
  5. 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-7 happens 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 last messageId I saw".
  • On the load balancer, raise the idle timeout for WebSocket, otherwise connections keep dropping at 60 seconds.