System Design · 09. Whole Systems · 14 min · Advanced

Design a Chat System

Deliver messages in milliseconds to people who come and go.

In short

23,148 messages a second and 10 million open connections: that needs 100 WebSocket gateways, a sessions store to find people, and a message store sharded by chat (73 TB a year). Delivery takes about 62 ms.

Receipts are small acks, groups store once and deliver many, presence uses expiring heartbeats, offline users get a push and then sync by last id, and order is kept per chat.

Key ideas

  • Requirements: fast delivery, no lost messages, correct order, groups, history, offline users. (step 1)
  • The sessions map is small (one entry per online user) and hot, so keep it in memory. (step 5)
  • Store once, deliver many. The delivery rate, not the send rate, sizes the gateways. (step 8)
  • Ordering is per chat, not global. A global order across all chats is expensive and not needed. (step 11)

Good to know

  • Messages are small. Holding millions of idle connections is the real job. (step 2)
  • An idle open connection is cheap; thousands of repeated requests are not. (step 4)
  • Shard by chat, not by message: reading a chat then needs only one shard. (step 6)
  • The store is the source of truth; delivery over the connection and push are only ways to tell Bob sooner. (step 10)

Watch out

  • Polling puts the cost on the quiet times and still delivers late. (step 3)
  • If the ack is lost, the server resends; the app must drop duplicates by message id. (step 7)
  • Presence is the cheapest feature to build and the easiest one to make expensive. (step 9)
AliceLoad balancerGateway 1BobMessage storeGateway 2Sessions (Redis)Offline queuePush service

Key numbers

Connections
10 million
Messages/s
23,148/s
Delivery time
62 ms

Terms

Polling
A client asking the server again and again whether anything is new.
WebSocket
A connection that stays open so the server can push messages to the client at any time.
Gateway server
A server that holds many open connections and passes messages in and out.
Sessions store
A fast map from a user to the gateway they are connected to.
Message store
Durable storage of every message, keyed by chat and message id.
Delivery receipt
A small acknowledgement showing a message was stored, delivered or read.
Group fan-out
Storing a group message once and delivering it to every member.
Heartbeat
A tiny periodic signal that shows a device is still online.
Push notification
A message sent through the phone's notification system to an offline user.
Sync after id
Asking for all messages newer than the last id a device has, to catch up.