09. Whole Systems / Lesson 4 of 4
Design a Chat System
Deliver messages in milliseconds to people who come and go.
- 14 min
- Advanced
- 12 steps
- Connections—
- Messages/s—
- Delivery time—
- Request
- Response
- Write
- Health check
- Failed request
Step 1 of 12: Alice sends a message; Bob sees it at once
Read every step as text
Step 1: Alice sends a message; Bob sees it at once
A chat system sends short messages between people in real time: one-to-one and in groups. People expect the message within a blink, a tick when it arrived, to see who is online, and to read old messages later.
The hard part is delivery: Bob's phone must get the message without asking for it, even though a server cannot normally call a phone.
Requirements: fast delivery, no lost messages, correct order, groups, history, offline users.
Step 2: Napkin math: messages, connections, storage
Say 50,000,000 people a day send 40 messages each: 2,000,000,000 messages, about 23,148 a second, and 46,296 at a 2× peak. At a busy moment 20% are online: 10 million open connections. At 100,000 per server that is 100 gateways.
Storage: 2,000,000,000 × 100 bytes = 200 GB a day, 73 TB a year. Connections, not messages a second, are the unusual number here.
Messages are small. Holding millions of idle connections is the real job.
Step 3: The simplest version: ask again and again
One server and a database. Alice sends with a normal request. Bob cannot be called, so his app polls: "anything new?" every 5 seconds. Nothing is hard here, and it works for a small app.
At scale it hurts twice. 10 million people polling every 5 s is 2,000,000 requests a second, nearly all with the answer "nothing". And a message waits on average 2.5 s to be picked up: about 2,560 ms from send to display.
Polling puts the cost on the quiet times and still delivers late.
Step 4: Keep one connection open: WebSocket
A WebSocket is a connection that stays open after the first request, so the server can push to the phone at any time. No more polling: delivery is 30 ms to the server, then 30 ms to Bob, plus 2 ms to look him up: 62 ms.
Each connection costs a little memory, so a gateway server holds about 100,000. The load balancer sends each new connection to a gateway, and 10 million connections need 100 gateways. Gateways keep no chat history: they only hold connections.
An idle open connection is cheap; thousands of repeated requests are not.
Step 5: Find which gateway Bob is on
Alice is on Gateway 1 and Bob on Gateway 2. Gateway 1 must hand the message to Gateway 2. A fast sessions store (Redis) records
user → gateway: written when someone connects, deleted when they leave.Gateway 1 looks up Bob (2 ms), forwards the message to Gateway 2, which writes it to Bob's open connection. Total: 30 + 2 + 30 = 62 ms. Alternatively each gateway subscribes to a channel per user (pub/sub); the idea is the same.
The sessions map is small (one entry per online user) and hot, so keep it in memory.
Step 6: Save every message, in order, forever
The gateway also writes each message to a message store. It is write-heavy and read by chat: "the latest 50 messages of chat X". A wide-column or key-value store fits, with the key
(chat_id, message_id), so one chat's messages sit together in time order.That is 200 GB a day and 73 TB a year, too much for one machine: shard by
chat_id, so every chat lives on one shard and a history read touches only one. Saving happens beside delivery, so it does not slow it down.Shard by chat, not by message: reading a chat then needs only one shard.
Step 7: Sent, delivered, read: three small acknowledgements
Receipts are messages that go back. Sent: the server has stored it (one tick). Delivered: Bob's device received it and sent an ack (two ticks). Read: Bob opened the chat (two blue ticks).
The ack travels the same route in reverse, and the server updates the message's state. Acks are tiny, but there are three per message, so keep them cheap: batch several reads into one ack.
If the ack is lost, the server resends; the app must drop duplicates by message id.
Step 8: A group: one message, many deliveries
In a group of 10, one message is stored once under the group's chat id, then delivered to the 9 other members, each on whichever gateway they use. The gateway looks up every member's session and forwards.
If 30% of messages go to groups of 10, each message means 3.3999999999999995 deliveries on average, so deliveries are about 79,000 a second, not 23,148. Groups are capped (hundreds, not millions); a channel of millions is built like a news feed instead.
Store once, deliver many. The delivery rate, not the send rate, sizes the gateways.
Step 9: Online, offline, last seen
Each device sends a tiny heartbeat every 30 seconds. The gateway refreshes a key in the sessions store with a short expiry (say 60 s). If heartbeats stop, the key expires and the person is offline. That is 10 million ÷ 30 = 333,333 heartbeats a second.
Do not tell all friends about every change: a flapping connection would send thousands of updates. Tell only people who have that chat open, or let the app ask for status when it shows it.
Presence is the cheapest feature to build and the easiest one to make expensive.
Step 10: When Bob is not connected
If the sessions store has no entry for Bob, the message is already saved in the message store. The gateway adds a job to an offline queue, and a push service sends a notification through the phone's push system.
When Bob opens the app, it connects and asks: "give me everything after the last message I have". The undelivered messages come back from the store, and the ticks update.
The store is the source of truth; delivery over the connection and push are only ways to tell Bob sooner.
Step 11: Keep the order, and let devices catch up
Clocks on phones are unreliable, so never order by the sender's time. Give each message an id that grows inside its chat, from the chat's shard or a time-sorted id generator (see unique IDs). Everyone sorts by that id.
Each device remembers the last id it has. After a gap (airplane mode, a restart) it asks
after=103and receives 104, 105, …. The same call serves a second device logging in. Duplicates are ignored by id.Ordering is per chat, not global. A global order across all chats is expensive and not needed.
Step 12: The chat system in one picture
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.