Lesson 27 of 38Case studies
Design a Chat App
Design WhatsApp or Slack-style messaging with WebSocket gateways, ordered delivery, offline sync, receipts, and presence.
Chat feels instant and simple: type, send, two ticks. Behind it is a system holding hundreds of millions of open connections, routing each message to the right one, keeping messages in order, and catching up phones that were offline for a week. It is a top-five interview question because it tests real-time networking, ordering, and storage all at once.
Requirements
Functional
- One-to-one and group chats (groups up to 1,000 members).
- Messages arrive in real time when the recipient is online, and are delivered later when they come back.
- Delivery and read receipts (one tick, two ticks, blue ticks).
- Presence: online, or "last seen 5 minutes ago".
- Message history synced across a user's devices.
- Push notifications to offline phones.
Non-functional
- Low latency: under 200 ms sender to recipient when both are online.
- No message is ever lost once the sender sees the first tick.
- Messages in a conversation appear in the same order for everyone.
- Hundreds of millions of concurrent connections.
Out of scope: voice and video calls, stories, payments, message search.
Back-of-the-envelope numbers
| Quantity | Math | Result |
|---|---|---|
| Daily active users | 500 million | |
| Messages sent | 40 per user per day: 20B / 86,400 | about 230,000/s (peak 700,000/s) |
| Concurrent connections at peak | about 30% of DAU online | about 150 million |
| Gateways needed | at about 100,000 connections per server | about 1,500 servers |
| Message storage | 20B × 200 bytes | about 4 TB a day |
Two things stand out: a huge number of long-lived connections, and a very write-heavy message store. Both shape the design.
GET /messages every 2 seconds instead of holding a connection open?API
Clients talk over a WebSocket, sending small JSON (or protobuf) frames.
// client → server
{ "type": "send", "conv_id": "c_42", "client_msg_id": "a7f3-01", "body": "On my way" }
// server → sender (the first tick: stored durably)
{ "type": "ack", "client_msg_id": "a7f3-01", "msg_id": "m_9001", "seq": 1587 }
// server → recipient
{ "type": "message", "conv_id": "c_42", "seq": 1587, "from": "ada", "body": "On my way" }
// recipient → server (second tick, then blue ticks)
{ "type": "receipt", "conv_id": "c_42", "seq": 1587, "status": "delivered" }Plus a plain HTTP endpoint for catching up: GET /v1/conversations/c_42/messages?after_seq=1500.
Data model
Messages are written constantly and read by conversation, newest first. That access pattern fits a wide-column store such as Cassandra or ScyllaDB.
CREATE TABLE messages (
conv_id text,
bucket int, -- e.g. month number, so one partition never grows forever
seq bigint, -- per-conversation sequence number
msg_id text,
sender_id text,
body blob,
sent_at timestamp,
PRIMARY KEY ((conv_id, bucket), seq)
) WITH CLUSTERING ORDER BY (seq DESC);The partition key (conv_id, bucket) decides which node stores the rows, so one conversation's recent messages sit together on disk. The clustering key seq keeps them sorted. "Last 50 messages" is a single sequential read. Other tables: conversations (members, name), user_inbox (per user: conversations and their last read seq), and a session registry in Redis.
High-level design
Ada's phone keeps one WebSocket open to whichever gateway the load balancer gave it. When it connected, Gateway 1 recorded ada → gw1 in the session registry.
Gateways are the only stateful part: each holds open sockets. Everything behind them is stateless and scales by adding servers. When a gateway dies, its clients reconnect to another one (with random backoff so they do not all reconnect in the same second) and re-register.
Deep dive 1: sending a message, step by step
Ada's phone generates a client_msg_id so a retry after a network blip can be recognised as the same message.
Deep dive 2: ordering with sequence numbers
You might order messages by timestamp. But phones' clocks disagree, and two servers' clocks can differ by tens of milliseconds. Instead, each conversation gets its own sequence number: 1, 2, 3, assigned by one authority when the message is stored. Everyone sorts by seq, so everyone sees the same order.
Sequence numbers also make gaps visible. If a phone holds seq 1585 and receives 1587, it knows 1586 is missing and can fetch it. This client code buffers out-of-order messages and drops duplicates:
Press Run (⌘ Enter) to see what happens.What does this print?
const nextSeq = 5;
const received = [5, 7, 8];
const gaps = [];
for (let s = nextSeq; s <= 8; s++) if (!received.includes(s)) gaps.push(s);
console.log(gaps.join(","));Offline sync uses the same number. The app remembers the last seq it has for each conversation. On reconnect it asks "anything after 1587?" for every conversation with new activity, which the server knows from user_inbox.
Deep dive 3: groups, receipts, and presence
Group chats. A message is stored once in the group's conversation. Delivery fans out to each online member's gateway. With a 1,000-member cap, that is at most 1,000 small pushes. Slack-style channels with 100,000 members do not fan out to everyone: clients that have the channel open get pushed, others just see an unread badge and fetch when opened.
Read receipts. Store per member "last read seq" instead of a status per message. One number answers "has Sam read everything up to 1587?", and the write is one update, not one per message.
Presence. Each connected client sends a heartbeat every 30 seconds; the presence service sets online:{user} in Redis with a 60-second TTL. No heartbeat, the key expires, the user is offline, and "last seen" is the expiry time. Presence changes go only to contacts who currently have that chat open, never to all contacts; otherwise one person opening the app would cause hundreds of pushes.
End-to-end encryption in one paragraph: with the Signal protocol (used by WhatsApp and Signal), each device has key pairs, and senders encrypt each message with keys only the recipients' devices hold. Servers route and store ciphertext they cannot read. Consequences for the design: the server cannot search or moderate message content, groups encrypt per device (or use shared sender keys), and adding a new device needs a key exchange. Everything else in this lesson (routing, seq, receipts) works unchanged on encrypted blobs.
Bottlenecks, failures, and 10x scale
- Gateway crash. Up to 100,000 clients reconnect. Jittered backoff spreads them out; the session registry entries expire and are rewritten.
- Hot group. A huge group creates hot partitions. Bucket by time and cap group size, or treat it as a channel.
- Sequence counter. One counter per conversation is cheap because conversations are independent. Shard counters by
conv_idalongside the messages. - Store write load. 700,000 writes a second is Cassandra's sweet spot: append-only, spread across partitions, add nodes for more throughput.
- 10x: more gateways (pure horizontal scale), more Cassandra nodes, regional deployments so users connect nearby, and cross-region links for conversations spanning continents.
Match the requirement to the mechanism.
- WebSocket
- A long-lived, two-way connection over one TCP socket, letting the server push messages instantly.
- connection gateway
- A stateful server that holds client WebSockets and relays messages between them and stateless services.
- sequence number
- A per-conversation counter assigned on store, giving one agreed order and making gaps detectable.
- partition key
- In Cassandra, the part of the primary key that decides which node stores a row; rows sharing it live together.
- presence
- Online status, kept fresh by heartbeats that renew a short TTL key.
- end-to-end encryption
- Only the participants' devices hold the keys; servers relay ciphertext they cannot read.