Video in progress

Strong Middle 🏗️ System design

Design a chat application where users message each other: connections, message delivery and offline users.

Clients connect to gateway servers over WebSocket, and Redis stores which user is on which server. A message is first written to the DB and gets an ID, then sent to the recipient's server; if they're offline a push notification goes out, and when the client reconnects it asks for the history starting from the last ID it saw.

📖 Answer

Requirements: 1:1 and small groups, message order, "delivered/read" marks, nothing lost after being offline.

Connections. One server can hold tens of thousands of WebSocket connections, but millions of users need many servers. Ali may be connected to server 3 and Vali to server 7. So a user → server map is kept in Redis (with a TTL and heartbeat).

The send flow:

  1. Ali sends the message with a clientMsgId (to eliminate duplicates).
  2. The server writes it to the messages table and assigns a seq that grows within the chat.
  3. Ali gets back "accepted" (with the seq).
  4. Through an event broker (Kafka, partitioned by chat_id — order is preserved) it is delivered to the server Vali is connected to, which writes it to the WebSocket.
  5. If Vali isn't online — the push notification service.

Offline and disconnects. A message sent over WebSocket may not have arrived. So the client remembers the last seq it received for each chat and, on reconnect, requests GET /chats/{id}/messages?after=1840. The source of truth is the DB; the WebSocket is only an accelerating channel.

Storage. Messages are written heavily and read in time order by chat_id. Cassandra with an (chat_id, seq) key, or PostgreSQL sharded by chat_id, fits.

Large groups. In a channel with 50,000 members, sending every message to each member separately is expensive; there, clients pull it themselves, or it is sent only to online members.

In an interview, say clearly where the ordering guarantee comes from: not global, but within a chat.