Design WhatsApp
Understanding the Problem
💬 What is WhatsApp? WhatsApp is a mobile messaging app. You open a chat with a contact or a group, type a message, and it shows up on their phone within a second if they're online, or the next time they are if not. Small ticks next to each message tell you whether it reached the server, reached their phone, and was read. It runs on phones first, so it has to work on bad networks and with apps the OS keeps killing to save battery.
"Design Facebook Messenger" is the same problem. The main difference is where history lives: WhatsApp keeps messages on the device and deletes them from the server once delivered, while Messenger keeps a full server-side history that every device syncs from. We'll design the delivery core so it works either way and call out where the choice matters. Slack and Discord are a different problem (channels, workspaces, search across years of history); see Design Slack.
Functional Requirements
Agree on scope early; chat apps grow features fast (stories, calls, payments).
Core Requirements
- Users should be able to send a text message to another user, delivered in real time if they're online and when they come online if not.
- Users should be able to create groups (up to about 1,000 members) and send messages to them.
- Senders should see delivery state for each message: sent to the server, delivered to the device, and read.
- Users should be able to send media (photos, videos, voice notes).
Below the line (out of scope)
- Voice and video calls.
- Status/stories, payments, channels for broadcasting.
- Contact discovery and spam detection.
Non-Functional Requirements
Ask about scale. We'll design for 2 billion users, 500 million connected at peak, and 100 billion messages a day.
Core Requirements
- Messages should arrive within about 500 ms when both users are online.
- Messages must never be lost once the sender sees "sent," and each must be shown exactly once, in order within a chat.
- The system should handle hundreds of millions of concurrent connections.
- It should work on poor mobile networks: reconnects, timeouts and app restarts are normal, not exceptions.
- Messages should be end-to-end encrypted; the server routes content it can't read.
Below the line (out of scope)
- Global ordering across chats.
- Keeping messages forever on the server (we keep undelivered ones for up to 30 days).
Some quick math. 100B messages/day ÷ 86,400 ≈ 1.2M messages per second average, maybe 3M/s at peak. Most are 1-1 or small groups, so with an average fan-out of about 2 recipients that's on the order of 3-6M deliveries per second. At ~200 bytes per message on the wire (encrypted text plus metadata), storage is about 100B × 200 B = 20 TB per day if we stored everything; since we delete after delivery, the live store holds only undelivered messages, which is much smaller.
The number that drives the design is connections. A well-tuned server can hold on the order of hundreds of thousands to a million mostly idle TCP connections. 500M ÷ ~500k ≈ 1,000 chat servers, and every message needs to find which of those 1,000 the recipient is on.
Chat is a routing problem more than a storage problem. Spend your design time on "how does a message find the recipient's connection," and on what happens when the connection isn't there.
The Set Up
Planning the Approach
We'll start with 1-1 messages between online users, then add offline delivery, groups, receipts and media. Deep dives cover routing across many servers, not losing or duplicating messages, large groups, the mobile client, and encryption.
Defining the Core Entities
- User: an account, identified by phone number, with one or more devices.
- Chat: a conversation, either 1-1 (two participants) or a group (a list of members and admins).
- Message: belongs to a chat, has a client-generated ID, sender, timestamp, a per-chat sequence number assigned by the server, and an encrypted body (or a pointer to media).
- Inbox entry: a message waiting to be delivered to one specific device.
- Receipt: a small message that says "device D received (or read) message M."
API or System Interface
The client keeps a WebSocket (or a custom binary protocol over TCP/TLS) open to a chat server. Everything is a frame on that connection, both ways:
client -> server
send { clientMsgId, chatId, body, mediaRef? }
ack { messageIds: [...] } // I received these
read { chatId, upToSeq } // I read up to here
sync { cursor } // give me what I missed
server -> client
sent { clientMsgId, messageId, seq, ts } // stored on server (one tick)
message { messageId, chatId, seq, sender, body }
receipt { messageId, deviceId, state: "delivered" | "read" }
Plus a few plain HTTPS endpoints for things that don't need the socket:
POST /groups { name, members } -> { chatId }
POST /groups/{id}/members { add: [...], remove: [...] }
POST /media -> { uploadUrl, mediaId } // presigned upload
High-Level Design
1) Users should be able to send 1-1 messages, online or offline
Both users online, one server. Alice and Bob are connected to the same chat server. Alice's client sends a send frame. The server stores the message, replies sent to Alice, and writes a message frame to Bob's connection. That's the whole thing, and it falls apart as soon as there's more than one server.
Many servers. Alice is on server 17 and Bob on server 402. Server 17 needs to know where Bob is. We add a session registry: when a device connects, its chat server writes deviceId → serverId to a sharded in-memory store (Redis), with a TTL refreshed by heartbeats. To deliver, server 17 looks up Bob's devices and forwards the message to server 402, which writes it to Bob's socket.
Bob is offline. No entry in the registry. We can't just drop the message. Before anything else, server 17 writes it to the message store and to Bob's inbox (one entry per recipient device). When Bob comes online, his client sends sync, and the server streams everything in his inbox. As each message is acknowledged by Bob's device, its inbox entry is deleted. We also send a push notification through APNs or FCM so Bob's phone knows to wake up and connect. (The push contains no message content, just a wake-up, since content is end-to-end encrypted.)
The order of operations matters: persist first, then deliver. The sent tick tells Alice the message is durable, so we only send it after the write.
For storage, the inbox is write-heavy, append-and-delete, and keyed by device. A wide-column store like Cassandra (or DynamoDB) fits: partition key deviceId, clustering by sequence, with a 30-day TTL so undelivered messages for abandoned devices expire on their own.
2) Users should be able to send messages to groups
A group message goes to every member. We store group membership in a Group Service (a table keyed by chatId with the member list, cached heavily, because it's read on every message and changes rarely).
When Alice sends to a group of 50:
- Her chat server stores the message once in the message store, with the next sequence number for the chat.
- A fan-out step looks up the 50 members, and for each member device writes an inbox entry (pointing to the message) and, if the device is online, forwards it to that device's chat server.
This is fan-out on write: delivery cost is paid when the message is sent, proportional to group size. For groups capped around 1,000 members it's the right choice, because every member needs the message on their phone anyway; there's no "read it later from a shared timeline." We do the fan-out asynchronously through a queue (Kafka, partitioned by chat ID), so Alice gets her sent tick as soon as the message is stored, not after 1,000 deliveries.
3) Senders should see sent, delivered and read state
The three ticks map to three events:
- Sent (one tick): the server has durably stored the message. The server returns
sentto the sender after the write. - Delivered (two ticks): the recipient's device received it. The device sends
ackfor the message IDs it got; the server deletes those inbox entries and sends areceipt { delivered }to the sender. - Read (two blue ticks): the recipient opened the chat. The device sends
read { chatId, upToSeq }, which covers every message in the chat up to that sequence, and the server forwards areadreceipt to the sender.
Receipts are just messages going the other way. They take the same path: look up the sender's devices in the registry, forward if online, otherwise put them in the sender's inbox. That means they inherit all the reliability work we do for messages, for free.
In groups, receipts multiply. A message read by 200 members generates 200 read receipts back to the sender. We batch them (one receipt frame carrying many (device, message) pairs) and for large groups only send aggregates ("read by 180 of 200"), with details fetched on demand when the sender opens the message info screen.
read { upToSeq } is cumulative: one frame acknowledges a whole chat's worth of messages, so reading 40 messages at once costs one receipt, not 40.
4) Users should be able to send media
Media doesn't go over the chat connection. A 20 MB video would block every other frame on the socket and tie up chat servers that are built to shuffle small messages.
- The client encrypts the file with a fresh random key and asks the Media Service for an upload URL.
- It uploads the encrypted blob directly to object storage (S3) using a presigned URL.
- It sends a normal chat message containing the
mediaId, the decryption key, a hash and a small thumbnail. - Recipients download the blob from a CDN in front of the object store and decrypt it locally.
The server stores only ciphertext. Because the key travels inside the end-to-end encrypted message, the media is as private as the text. Media blobs are deleted after a retention window once delivered; forwarding a popular image can reuse the same blob if the client re-sends the same key and hash.
Potential Deep Dives
1) How do we route messages between a thousand chat servers?
The registry tells us which server a device is on. The question is how messages get from server to server.
Bad Solution: Every Server Connects to Every Server
Approach
Each chat server keeps a direct connection to every other server and forwards messages straight to the right one.
Challenges
1,000 servers means about 500,000 connections in the mesh, and every deploy or failure reshuffles them. It works at a few dozen servers and becomes an operational burden beyond that.
Good Solution: Pub/Sub Channel per User
Approach
Each chat server subscribes, in Redis Pub/Sub, to a channel for every device connected to it. To deliver to Bob, publish to device:{bobDeviceId}; whichever server holds Bob's connection receives it. No registry lookup needed.
Challenges
Redis Pub/Sub is fire-and-forget: if the subscriber is momentarily disconnected, the message is gone (that's fine here, since the inbox has a durable copy, but it means we always need the inbox). Hundreds of millions of channels across a Redis cluster is a lot of subscription state, and a cluster-mode Pub/Sub broadcasts across nodes unless you use sharded Pub/Sub. It's a reasonable answer that interviewers accept.
Great Solution: Session Registry Plus Direct Routing Through a Message Router Tier
Approach
Keep the registry (deviceId → serverId, sharded Redis, TTL refreshed by heartbeats). Chat servers don't forward to each other directly; they hand messages to a stateless router tier that looks up the recipient's server and pushes to it over a small number of long-lived connections (each router talks to all chat servers, but there are far fewer routers than chat servers, and chat servers only talk to routers). The durable copy is already in the inbox, so a failed forward is only a latency hit: the recipient gets it on the next sync.
To keep lookups cheap, routers cache registry entries briefly and invalidate on a "wrong server" response.
Challenges
The registry must be correct when devices move. A phone switching from Wi-Fi to cellular reconnects, possibly to a different server, while the old server hasn't noticed the dead socket yet. We store a connection epoch with each registry entry; the newer connection overwrites it, and the old server, on its next heartbeat or write failure, removes its entry only if the epoch still matches. Messages forwarded to the old server during the gap fail and are caught by the inbox.
Make the inbox the source of truth and the live connection an optimization. Then every routing failure (server crash, stale registry, dropped Pub/Sub message) is handled the same way: the client syncs and gets what it missed. Interviewers like hearing that a design has one recovery path, not ten.
2) How do we make sure messages are never lost, duplicated or out of order?
Mobile networks drop packets, connections die mid-frame, and clients retry. Each of the three guarantees needs its own mechanism.
Not lost. Every hop is acknowledged, and nothing is deleted until the next hop confirms:
- The sender's client keeps the message in a local outbox until it gets
sent. If the connection drops, it resends on reconnect. - The server sends
sentonly after the message is in the message store and the inboxes. - Inbox entries are deleted only when the recipient device sends
ack.
Not duplicated. Retries mean the server may get the same send twice, and a device may get the same message twice. The client generates a unique clientMsgId (a UUID) per message. The server stores messages with a uniqueness check on (senderDeviceId, clientMsgId); a duplicate send returns the original sent response instead of storing a second copy. On the receiving side, the client keeps the IDs it has displayed and ignores repeats.
In order. Clocks on phones are wrong, and two messages sent a millisecond apart can travel different paths. We order by a per-chat sequence number assigned by the server at write time. For a 1-1 or group chat, one partition (keyed by chat ID) owns sequence assignment, so it's a simple increment. Clients display messages by sequence, and if a device sees seq 41 and then 43, it knows 42 is missing and asks for it on its next sync.
Message store (Cassandra), partitioned by chat:
PRIMARY KEY ((chat_id), seq)
columns: message_id, sender, client_msg_id, sent_at, body_ciphertext, media_ref
Inbox, partitioned by device:
PRIMARY KEY ((device_id), chat_id, seq) -- with TTL of 30 days
What the sender sees while their own message is pending also matters. The client shows it immediately with a clock icon (optimistic UI), sorted at the end of the chat, and slots it into its final position when sent returns with a sequence number.
3) How do we handle large groups and very active groups?
With fan-out on write, a message to a 1,000-member group writes up to 1,000 × (devices per member) inbox entries and up to that many forwards. At our scale most groups are small, but large ones are common enough to plan for.
- Batch per server. Group the recipients by chat server and send one frame per server listing all its recipients, instead of one per recipient.
- Async fan-out workers consume from a queue partitioned by chat ID, so a burst in one huge group doesn't slow other chats, and order is kept within a group.
- Store once, reference many. Inbox entries point to the message in the message store rather than copying the body (in an end-to-end encrypted design, though, the sender encrypts per device or uses a shared group key; see deep dive 5).
- Membership cache. The member list for active groups lives in memory on fan-out workers, invalidated by membership changes.
If the interviewer pushes toward groups of 100,000 or more, that's a broadcast channel, not a chat: switch to fan-out on read, where members pull from the channel's timeline when they open it and only online, active viewers get live pushes. That's the Slack/Discord design and is why WhatsApp-style groups are capped.
4) What does the mobile client need to do?
Interviewers who ask about "mobile chat client concerns" want to hear that the phone isn't a dumb terminal. Much of the reliability lives there.
- Local database. The client stores chats and messages in SQLite on the device. The UI reads from the local DB, never from the network. That makes the app open instantly, work offline, and makes the server's job just "sync the deltas." For WhatsApp-style designs it's also the only long-term copy of history.
- Outbox. Messages typed offline go into a local outbox table with their
clientMsgIdand are sent in order when the connection returns. Because sends are idempotent, retrying aggressively is safe. - Sync cursor. The client remembers the last sequence it has per chat (or an inbox cursor). On reconnect it sends
sync, gets everything after it, and acks. It never asks for "all messages." - Connection management. Reconnect with exponential backoff plus jitter, so a server restart doesn't cause a million phones to reconnect in the same second. Detect dead connections with an application-level ping; TCP alone can take minutes to notice.
- Background limits and push. iOS and Android suspend apps in the background, so the socket dies. Push notifications through APNs/FCM are how the server wakes the app; the app then connects and syncs. High-priority pushes are for messages; everything else can wait for the next time the user opens the app.
- Battery and data. Heartbeats are as infrequent as NAT timeouts allow (every few minutes). Media is downloaded on Wi-Fi only by default, thumbnails first.
- Multiple devices. A user with a phone, a laptop and a tablet has three devices, each with its own inbox and its own keys. The sender's client sends to all of the recipient's devices and to the sender's own other devices, so everything stays in sync.
5) How does end-to-end encryption change the design?
With end-to-end encryption, only the devices in a conversation have the keys. The server is a router for ciphertext. The standard approach is the Signal protocol:
- Each device generates an identity key pair and uploads its public keys (plus a batch of one-time "prekeys") to a key server.
- To message a device for the first time, the sender fetches the recipient's public keys and runs a key agreement to establish a session, even if the recipient is offline.
- Each message advances a "double ratchet," so every message has a fresh key and a leaked key can't decrypt past messages.
For groups, encrypting each message once per member device is expensive. With sender keys, each member generates a group sending key and distributes it once to every other member over the pairwise encrypted sessions. After that, a group message is encrypted once and fanned out as the same ciphertext to everyone. Membership changes require rotating sender keys.
What this means for the rest of the design:
- The server can't read, index or search messages. Search happens on the device.
- Push notifications can't include content; the app decrypts after waking.
- Multi-device means encrypting to each device separately (or per-device sessions for each sender key).
- Server-side history (the Messenger approach) has to store ciphertext only, with key backups handled separately, usually protected by a user secret.
Don't go deep on cryptography unless the interviewer wants to. It's enough to say: keys live on devices, the server distributes public keys and routes ciphertext, and the design must not depend on reading message contents.
Final Design
The full flow:
- Each device holds a persistent connection to a chat server behind a load balancer. The chat server registers
deviceId → serverIdwith an epoch in the session registry. - Alice's client writes the message to its local outbox and sends it with a
clientMsgId. The chat server deduplicates, assigns the chat's next sequence number, stores the message and writes inbox entries for each recipient device, then returnssent. - For groups, a fan-out worker reads the member list and writes inbox entries per device. For each online recipient, the router looks up the device's chat server and forwards the message.
- Bob's device acks; the server deletes the inbox entry and sends a delivered receipt to Alice. When Bob reads, a cumulative read receipt follows the same path.
- Offline devices get a push notification and sync from their cursor when they reconnect. Media goes directly to object storage, with only a pointer and key in the message.
What is Expected at Each Level?
Mid-level
You should get to persistent connections to chat servers, a registry to find which server a user is on, and an inbox for offline users with push notifications to wake them. With prompting, you should explain how delivered and read receipts work and store messages in a database suited to the write volume.
Senior
You should derive that connections, not storage, drive the server count, and make the inbox the source of truth with live delivery as an optimization. Expect to cover idempotent sends with client-generated IDs, per-chat sequence numbers for ordering, fan-out on write for groups with the reason it fits, and media upload outside the chat path. You should talk about what the mobile client does: local DB, outbox, sync cursor.
Staff+
You should handle the subtle parts: stale registry entries when devices switch networks, reconnect storms, cumulative and aggregated receipts in groups, multi-device delivery, and where fan-out on write stops working. Expect to explain how end-to-end encryption constrains the server (no content in pushes, no server-side search, sender keys for groups) and the trade-off between device-held history and server-side history.