System design · Queues, write scaling, delivery lag
How to design a chat system like WhatsApp
A chat system looks simple. The hard part is holding tens of millions of open connections, keeping every conversation in order, delivering to people who are offline, and surviving the moment everyone sends "Happy New Year" in the same second.
Updated · 5 min read
A teaching design of a system like WhatsApp, not WhatsApp's real architecture.
The short version
- Stateful gateways hold one WebSocket per online device. A routing store says which gateway each user is on.
- Acknowledge the sender once the message is on a durable queue partitioned by conversation. Workers write it to storage at a rate the store can sustain.
- Order within a conversation only: one queue partition per conversation and time-ordered message IDs.
- A client_msg_id makes resends safe, so users never see a message twice.
- Small groups fan out on write. Huge channels store each message once and fan out on read.
Clarifying questions to ask first
- One-to-one only, or groups too? (Assume both, with groups of around 200 members.)
- How many users, and how active? (Assume 100 million daily users sending about 40 messages each.)
- What ordering and delivery guarantees? (Assume order within a conversation only, and no message lost or shown twice.)
- Must history sync across devices? (Assume yes: every device sees the full history, and offline devices catch up on reconnect.)
- Text only, or media too? (Assume text; presence, typing indicators and media attachments are optional extras.)
Numbers that shape the design
| Quantity | Assumption | Result |
|---|---|---|
| Messages | 100M daily users × 40 messages each | 4B a day ≈ 46,000/s average, ≈ 140,000/s at a 3× peak |
| History reads | about 1.5 reads per message sent | ≈ 70,000/s average |
| Storage | ≈ 200 bytes per message, text only | ≈ 800 GB a day ≈ 290 TB a year, before replicas |
| Open connections | 30% of daily users online at peak | ≈ 30M concurrent connections |
Writes are a large share of the load, so caching alone won't save you. Storage grows by hundreds of terabytes a year, so partition the message store from day one. Tens of millions of long-lived connections need their own tier.
API
A WebSocket carries real-time traffic both ways. History goes over plain HTTP, which is cacheable and easy to page.
WebSocket /ws
→ { "type": "send", "client_msg_id": "c-91f2", "conversation_id": "conv_42", "body": "hi" }
← { "type": "ack", "client_msg_id": "c-91f2", "message_id": "1840238472101", "status": "sent" }
← { "type": "message", "conversation_id": "conv_42", "message_id": "1840238472101", "from": "u_7", "body": "hi" }
→ { "type": "receipt", "message_id": "1840238472101", "status": "read" }
GET /api/conversations/{id}/messages?before={message_id}&limit=50
→ 200 OK { "messages": [ ... ] }If the connection drops before the ack, the client resends with the same client_msg_id and the server drops the duplicate.
Data model
The main query is "latest messages in this conversation", so partition by conversation and sort by a time-ordered message ID. Cassandra, DynamoDB or PostgreSQL sharded by conversation all fit.
messages
conversation_id bigint partition key
message_id bigint sort key (time-ordered, e.g. Snowflake)
sender_id bigint
body text
created_at timestamp
conversation_members
conversation_id bigint
user_id bigint
last_read_id bigint for read receipts and unread countsReceipts are a per-member last_read_id, never updates to the message row. Otherwise a group message read by 200 people is 200 writes to one hot row.
High-level design
- Gateways hold the WebSockets. A routing store, often Redis, records which gateway each online user is on.
- The chat service validates, assigns a message ID, puts the message on a queue partitioned by conversation, then acks. The sender waits only for this.
- Workers write to the message store and deliver through each recipient's gateway, or send a push notification if they're offline.
- History reads use a separate path with a cache, because recent messages are read far more than old ones.
Surviving the spike
Write every message to the database before acking and the database fails the moment traffic spikes. Writes can't be cached, and read replicas add no write capacity, so at midnight on New Year's Eve sends simply fail.
With a durable queue in front, a spike becomes a backlog: delivery is a few seconds late instead of failing. The new risk is lag. Size workers so the backlog clears soon after the peak, and shard the store so their writes fit.
Ordering, receipts and offline devices
- Clocks disagree, so never order by timestamp. One queue partition per conversation means one worker handles it in sequence, and time-ordered IDs make storage and clients sort the same way.
- Sent means queued. Delivered means a device received it. Read means the recipient opened the conversation.
- An offline device reconnects and asks for everything after its last known message ID in each conversation. A push notification is a hint; the app still syncs from the server.
Groups and presence
A message to 200 members is 200 deliveries. Small groups fan out on write. Very large channels store the message once and members pull it when they open the channel, so one message doesn't become millions of deliveries.
Presence is the chattiest feature: every connect, disconnect and heartbeat is an update. Store it with a short expiry refreshed by heartbeats, and publish changes only to contacts who have the app open.
Common traps
- Showing a queued message as read. Ack, delivery and read describe different events; track them separately.
- Using push notifications as history. A push only wakes the phone and may be delayed; fetch durable messages on reconnect.
- Broadcasting every presence heartbeat to every contact. Presence can outnumber messages.
- Treating the cache as storage. It only speeds up recent history; page older messages from partitioned storage.
Follow-up questions interviewers ask
- "A gateway crashes." Its users reconnect to another gateway, which updates the routing store, and each device syncs from its last known message ID.
- "A user is on several devices." Record every connection in the routing store and deliver to each. An offline device catches up from history.
- "How do you show unread counts?" Count messages after the member's last_read_id. Marking read never touches the message row.
Frequently asked questions
Why use WebSockets for chat instead of polling?
+
Chat needs the server to push messages the moment they arrive. Polling either wastes requests or adds delay. A WebSocket keeps one connection open both ways, so delivery is immediate and idle users cost almost nothing.
How do you store billions of messages?
+
Partition by conversation ID and sort by message ID inside each partition. Cache recent history and move old messages to cheaper storage over time.
How does the server know where to deliver a message?
+
Each gateway registers its connected users in a shared routing store. A worker looks up the recipient's gateway and hands the message over, or sends a push notification if the user isn't connected.
How do you keep chat messages in order?
+
Order is only needed within a conversation. Route every message of a conversation to the same queue partition so one consumer processes them in sequence, and give each message a time-ordered ID.