One-to-one and group messaging that feels instant: connections, delivery, ordering and offline users.
“Design a chat application like WhatsApp or Messenger.”
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Choosing the connection model | Chat needs the server to push. A strong candidate says WebSocket (or similar), and then deals with the cost: millions of open, stateful connections. |
| Reliable delivery | Messages must not be lost or shown twice. This is persist-before-ack, client ids, retries and receipts, in the right order. |
| Ordering and identity | You must say what order means in a chat (per conversation, not global) and how a phone catches up after being offline. |
| Fan-out thinking | A group of 5 and a channel of 100,000 need different designs. Interviewers want to see you do the cost maths. |
| Stateful systems at scale | Gateways remember who is connected. Presence, reconnect storms and routing a message to the right gateway are the real difficulty. |
Phones keep one long-lived WebSocket to a gateway. The gateway is stateful but simple: it holds connections and forwards frames. A chat service does the real work. It saves the message first, then replies “sent”, then delivers it.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | 1:1 and groups, media, history, multi-device, presence. Say what you will skip (end-to-end encryption, calls). |
| 2. Estimate | 4 | Messages per second, concurrent connections, gateway count, storage per year, media. |
| 3. API and data | 5 | WebSocket frames, a few REST calls, the message and conversation tables. |
| 4. High-level design | 8 | Gateways, registry, chat service, message store, push, media path. One send, one offline case. |
| 5. Deep dives | 15 | Delivery and acks, ordering and ids, group fan-out, presence and connections. |
| 6. Scale and failures | 6 | Gateway crash, reconnect storm, hot conversations, multi-region, abuse. |
| 7. Wrap up | 3 | Recap, trade-offs, what you would add next. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| One-to-one only, or groups too? How big can a group be? | Group size decides fan-out. 8 people is a loop. 100,000 people is a different system. | Both. Groups up to 500 members. Large broadcast channels are out of scope for now. | Fan-out on write for groups up to 500. Name the channel case as a later extension. |
| What do we send: text only, or images and video too? | Media is far bigger than text and needs its own upload path. | Text plus images and short video. | Upload media to object storage with a pre-signed URL. Messages carry only a pointer. |
| Do we show sent, delivered and read? | Receipts are more messages. In a big group they cost a lot. | Yes for 1:1. Group read receipts are optional. | Ack levels in the protocol, and a per-message receipt record. |
| What if the other person is offline? Must the message wait? | Decides whether we need durable storage and a push path. | Yes. Keep it until delivered, and send a push notification. | Store before ack, a pending-message path, and a mobile push service. |
| Is it one device per user, or phone plus laptop? | Several devices means several connections and several delivery targets per user. | Up to 4 devices per user, all in sync. | Registry maps user to a set of device connections. Sync is by sequence number per device. |
| Do we show online status and last seen? | Presence is a large, noisy stream of updates. | Yes, for contacts only. A few seconds of delay is fine. | A presence service with heartbeats, and fan-out only to people who are watching. |
| How long do we keep history, and must it be searchable? | Retention drives storage. Search needs another system. | Keep all messages. History scrolls back. Full-text search is out of scope. | Time-ordered storage per conversation and a paging API. No search index. |
| Does the server read messages (plain) or only carry them (end-to-end encrypted)? | End-to-end encryption removes server-side search, spam checks and easy backups. | Out of scope for the first version. Mention it at the end. | Design as if the server can read. Say what changes if it cannot. |
| What scale: daily users, messages per user, how many online at once? | Every capacity number comes from here. | 500M daily users, 40 messages a day each, about 20% connected at the same time. | Hundreds of gateways, and a partitioned message store. |
| How fast must a message arrive, and how available must we be? | Sets the latency budget and the failure handling. | Under 500 ms end to end when both are online. 99.99% available. Never lose an acked message. | Persist before ack, replicate the store, and keep the hot path short. |
| Assumption | Value |
|---|---|
| Daily active users | 500 million |
| Messages sent per user per day | 40 |
| Average message record (text, ids, metadata) | 200 bytes |
| Peak versus average traffic | 3 times |
| Recipients per message (1:1 and small groups) | 3 on average |
| Share of daily users connected at one moment | 20% |
| Connections one gateway can hold | 125,000 |
| Messages that carry media | 10%, about 200 KB each |
| Presence changes per user per day | 10 |
| What | Maths | Result |
|---|---|---|
| Messages per day | 500M users × 40 | 20 billion |
| Messages per second (average) | 20 billion ÷ 86,400 (about 10^5) | about 230,000 per second |
| Messages per second (peak) | 230,000 × 3 | about 700,000 per second |
| Deliveries per second at peak | 700,000 × 3 recipients | about 2.1 million per second |
| Outbound bandwidth at peak | 2.1M × 200 bytes | about 420 MB/s, 3.4 Gbit/s |
| Text storage per day | 20 billion × 200 bytes | 4 TB per day |
| Text storage per year (3 copies) | 4 TB × 365 × 3 | about 4.4 PB |
| Connected phones at once | 500M × 20% | 100 million |
| Gateways needed | 100M ÷ 125,000 | 800 gateways |
| Heartbeats per second | 100M connections ÷ 30 s | 3.3 million per second (about 4,200 per gateway) |
| Registry size | 100M entries × 100 bytes | about 10 GB, fits in memory |
| Media per day | 20 billion × 10% × 200 KB | 400 TB per day, 100 times the text |
| Presence updates to deliver, naive | 500M × 10 ÷ 86,400 = 58,000 per second; × 200 contacts | 11.6 million per second |
| Presence, only to people watching (5%) | 11.6M × 5% | about 580,000 per second |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| POST | ws: send | { client_id, conv_id, body or media_ref } | ack { client_id, msg_id, seq, status: sent } | client_id is made by the phone and makes a retry safe. The ack is sent only after the message is saved. |
| GET | ws: deliver (server to phone) | none | { conv_id, seq, msg_id, sender, body, sent_at } | Pushed by the server. The phone replies with a delivered ack carrying conv_id and seq. |
| POST | ws: sync | { last_seq per conversation } | all messages after those seqs | Sent on every reconnect. This is how a phone catches up after being offline. |
| GET | /v1/conversations/{id}/messages?before_seq=&limit=50 | none | 200 { messages[], next_before } | History paging by sequence number, not by page offset. |
| POST | /v1/media/upload-url | { type, size } | 200 { upload_url, media_ref } | Pre-signed URL: the phone uploads straight to object storage, then sends media_ref in a message. |
| POST | /v1/groups | { name, member_ids[] } | 201 { conv_id } | Idempotency key on create. Adding and removing members are PUT and DELETE on /members. |
| Table | Key | Holds |
|---|---|---|
| messages | partition: conv_id, sort: seq | msg_id, client_id, sender_id, body or media_ref, sent_at, deleted flag |
| conversations_by_user | partition: user_id, sort: last_msg_time | conv_id, last_seq, unread_count, muted. This is the inbox list. |
| members | partition: conv_id, sort: user_id | role, joined_at. A second copy keyed by user_id lists a user's groups. |
| receipts | partition: conv_id, sort: user_id | last_delivered_seq and last_read_seq per member (one row per member, not per message) |
| devices | partition: user_id, sort: device_id | push endpoint, platform, last_seq_seen |
user:42:devices -> { d1: gateway-17, d2: gateway-503 }
(entry has a short TTL, renewed by heartbeats;
a missing entry means: offline, store and push)| Component | What it does |
|---|---|
| Gateway | Terminates the WebSocket, authenticates, and passes frames on. It keeps no business logic, so it can be restarted and scaled. About 125,000 connections each. |
| Session registry | Maps each user device to the gateway holding its connection. In memory, with a short TTL that heartbeats renew. |
| Chat service | Stateless. Assigns the sequence number, saves the message, acks the sender, looks up recipients and hands the message to their gateways. |
| Message store | Wide-column store partitioned by conversation. Replicated three times. The source of truth. |
| Presence service | Tracks who is online from heartbeats, and tells only the people watching. |
| Push service | Sends notifications through Apple and Google when the recipient has no live connection. |
| Media path | Upload to object storage with a pre-signed URL, serve through a CDN. The message holds only a reference. |
| Group service | Stores membership, answers “who is in this group”, and drives fan-out. |
The problem: Phones drop off networks, servers crash, and replies get lost. The user must see each message exactly once, and the sender must never be told “sent” for a message that was lost.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Fire and forget | The phone sends. The server passes it on. No reply, no retry. | Simplest and fastest. | Any dropped packet or crash loses the message, and the sender never knows. |
| Ack before saving | The server replies “sent” as soon as it gets the frame, then saves and delivers. | The lowest delay for the sender. | A crash after the ack loses a message that the sender was told was safe. |
| Save, then ack, with retries (at least once) | Save to the replicated store first, then ack. The phone resends the same frame until it gets an ack. | No loss of an acked message. Simple to reason about. | Retries create duplicates unless the server can recognise them. |
| At least once + a client id + dedup | The phone puts a unique id on each message. The server remembers ids it has stored and returns the old ack for a repeat. | Effectively once. Retries are safe. This is the standard answer. | The server needs a fast id lookup, kept for as long as a retry could arrive. |
The rule is persist before ack. The sender sees one tick only when the message is in the replicated store, so a later crash cannot lose it. If the ack is lost, the phone does not know whether the save happened, so it retries. The retry carries the same client id, and the server returns the existing sequence number instead of writing again. That turns at-least-once delivery into an effectively-once result. See Delivery Semantics and Idempotent Consumer and Inbox Pattern.
The recipient side has the same shape. The server pushes, and the phone replies with a delivered ack. If no ack comes, the message stays pending, and the phone fetches it with sync when it reconnects. The sync is also the safety net for a crash between “saved” and “passed on”.
| Moment | What happened | Why the user is safe |
|---|---|---|
| Crash before the save | Nothing stored, no ack | The phone times out and retries. It is a normal first save. |
| Crash after the save, before the ack | Stored, but the phone has no ack | The retry finds the client id and returns the same seq. No second copy. |
| Ack lost on the way back | Stored and passed on, phone unsure | Same: the retry is recognised and answered from the record. |
| Crash after save, before passing it on | Stored, recipient not told | The recipient syncs with its last seq on its next heartbeat or reconnect. |
| Recipient offline | Stored, push sent | Delivered on reconnect through sync. The push is only a nudge. |
The problem: Two people type at once, messages take different routes, and a phone may be offline for days. Everyone in a conversation must see the same order, and a phone must find out exactly what it missed.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Sender's timestamp | Order by the time the phone says it sent the message. | No server work. | Phone clocks are wrong, and can be changed on purpose. Order differs between viewers. |
| Server timestamp | The server stamps the time when it receives the message. | One clock source per server. | Several servers have clocks that differ by milliseconds, so two messages can swap. Ties happen. |
| A global ID (Snowflake style) | Each message gets a roughly time-ordered 64-bit id from an id generator. | Unique and sortable. No coordination on the hot path. | Only roughly ordered across machines. Gaps give no way to know whether something is missing. |
| A sequence number per conversation | The conversation has a counter. Each saved message takes the next number: 1, 2, 3. | A clear order that everyone agrees on. Gaps are visible, so “what did I miss” is a simple range. | Needs a single place to assign the number (the partition owner), so one conversation is limited to one writer at a time. |
Chat needs order inside a conversation, not across the whole world. A per-conversation counter gives exactly that, and it is cheap, because each conversation lives in one partition of the store, and the partition owner can hand out the next number as part of the write. A conversation of even 1,000 messages a minute is only about 17 writes a second, far below one partition's limit. See Message Ordering and Lamport Timestamps for why a counter beats clocks.
The counter also solves catch-up. The phone remembers the highest sequence it has for each conversation. On reconnect it sends “conversation 7, last seq 118”. The server answers with 119 onwards. A hole in the numbers on the phone means a message is missing, and the phone asks for exactly that range. A separate globally unique message id (Snowflake style) still exists, for references such as replies and deletes. See Design a Unique ID Generator.
phone -> sync { conv 7: last_seq 118, conv 9: last_seq 40 }
server -> conv 7: messages 119..131 (13 messages)
conv 9: nothing new
phone: stores them, shows them in seq order,
sends delivered { conv 7, up to 131 }The problem: One message to a group must reach every member. A group of 5 is easy, but a group of 100,000 would turn each message into 100,000 writes and deliveries.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Fan-out on write (copy to each member's inbox) | On send, write the message into every member's own inbox and push to each. | Reading is a single lookup. Delivery state is per person and simple. | One message costs one write per member. Large groups are expensive. |
| Fan-out on read (store once) | Store the message once under the conversation. Members read the conversation when they open it. | One write per message, no matter how large the group. | Each member must find out there is something new, so a lightweight notification is still needed. Per-user state needs another table. |
| Hybrid by group size | Small groups: fan out on write. Large groups: store once and send a small “new message in conversation X” ping. | Cheap for the common case and bounded for the extreme case. | Two code paths to run and to test. |
Do the maths. In a 500-member group, one message is 500 deliveries. At 700,000 messages a second, if a tenth were group messages of that size, that would be 35 million deliveries a second. Copying the data 500 times is the waste, so store the message once, keyed by conversation. Fan out only the delivery: the chat service looks up the members, finds their gateways in the registry, and sends the frame. Per-member state is only two numbers (last delivered, last read), not a copy of each message.
For a very large group or channel, even the delivery loop is too much. Send one small “conversation 7 has seq 4,001” signal to those online, and let each client pull the message. This is the same push-versus-pull choice as in a news feed. Name it, say it is out of scope for the first version, and move on.
| Group size | Message copies stored | Deliveries per message | Approach |
|---|---|---|---|
| 2 (one to one) | 1 | 1 to 2 | Direct push to each device |
| 50 | 1 | up to 50 | Loop over members, push through gateways |
| 500 | 1 | up to 500 | Same, spread over many chat workers, batch by gateway |
| 100,000 (channel) | 1 | tens of thousands online | Ping and pull, with receipts turned off or sampled |
The problem: 100 million phones are connected. We must know who is online, route to the right gateway, survive a gateway dying, and not melt when millions reconnect at once.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Update a database on every change | Write online/offline to a database as it happens. | Simple. | Millions of writes a second for something that is only displayed. The database becomes the bottleneck. |
| Heartbeats into an in-memory store with a TTL | Each device pings every 30 seconds. The registry key lives for 60 seconds and is renewed. | Fast, cheap, and a dead phone expires by itself. | “Offline” is noticed after up to a minute. Last seen is approximate. |
| Push every change to all contacts | Tell all of a user's contacts whenever the user goes online or offline. | Contacts are always current. | About 11.6 million updates a second in the estimate. Wasteful, since most contacts are not looking. |
| Subscribe only while looking | A client subscribes to the presence of the people on its screen. Updates go only to subscribers, in small batches. | About 5% of the naive load. Natural. | More protocol work. A new screen needs a fresh read of presence. |
The registry entry is the presence. A phone sends a small heartbeat every 30 seconds. The gateway renews the key with a 60-second TTL. No heartbeat for two intervals, and the entry expires, so the user is offline and the registry also stops routing to a dead connection. One structure does both jobs. See Heartbeats.
For display, the client subscribes to the people it is showing and receives their changes, with a short delay (a few seconds of batching is fine). Do not announce a flapping connection: wait a few seconds before telling anyone someone is offline, to hide brief signal drops.
The dangerous case is a reconnect storm. If one gateway with 125,000 connections dies, all of them reconnect at once, and a deploy that restarts a tenth of the fleet means 10 million phones. Clients must reconnect with exponential backoff and random jitter. Spread over 30 seconds, one gateway's 125,000 phones become about 4,200 connections a second. The load balancer should also be able to shed load on new connections.
| Event | What the system does |
|---|---|
| Phone loses signal for 5 seconds | Reconnects quietly. The grace delay means no one is told it was offline. |
| Phone is switched off | Heartbeats stop. The TTL expires after about a minute. Last seen is recorded. Messages now go to the push path. |
| Gateway crashes | Its registry entries expire. Phones reconnect to other gateways, with jitter, and sync. |
| Deploy of a tenth of the fleet | Drain gateways slowly: tell clients to reconnect, a few percent at a time. |
| Phone has two devices | The registry holds a set of connections. A message goes to each live device. |
A simplified model of one message with fixed rules (no random numbers). Real systems add timeouts per hop, a durable outbox on the server, and many more messages in flight. The idea stays the same: save before you reply, give every message an id from the sender, and let the receiver ask for what it missed.
| Bottleneck | Fix |
|---|---|
| Open connections (100M, 800 gateways) | Scale gateways out, keep them stateless apart from the socket, tune OS limits and memory per connection (about 10 KB each), and balance new connections by least loaded. |
| Registry reads and writes (millions per second) | Shard by user id, keep it in memory, replicate each shard, and batch heartbeat renewals instead of one write each. |
| A hot conversation (one partition takes all the writes) | One partition handles thousands of writes a second, so normal groups are fine. For channels, split by time bucket, or use the ping-and-pull model. |
| Message store size (4.4 PB a year with replicas) | Partition by conversation, move old data to cheaper storage, compress, and keep hot recent messages on fast disks. |
| Media (about 100 times the text) | Direct upload to object storage, CDN for download, thumbnails made by a background worker, and size and type limits. |
| Push notification volume after an outage | Queue pushes, collapse repeats (“12 new messages”), and respect the provider's rate limits. |
| Presence storms | Subscribe-only presence, batching, and a grace delay before announcing offline. |
| Failure | How the design copes |
|---|---|
| A gateway crashes | Its connections drop. Phones reconnect to other gateways with backoff and jitter and send sync. Registry entries expire by TTL. No messages are lost, because they were saved before the ack. |
| The chat service crashes mid-send | If before the save: the phone retries. If after: the retry finds the client id and returns the same seq. The recipient syncs for anything not delivered. |
| A message store node fails | Three replicas. Writes need a quorum (two of three), so one failure is invisible. Repair brings the node back in line. |
| The registry loses data | Treat everyone as offline until their next heartbeat. Messages wait in the store, pushes go out, and phones sync. Slower, never lossy. |
| The push provider (APNs or FCM) is down | Messages still arrive when the app is opened. Queue and retry pushes with backoff. |
| A region is lost | Phones reconnect to another region. Messages are replicated across regions asynchronously, so the last moments may be missing until the region returns. Say this limit out loud. |
Phones keep a WebSocket to one of about 800 gateways. The chat service saves each message first (with a per-conversation sequence number), then acks, then routes it using an in-memory registry that maps users to gateways. Offline users get a push notification and catch up through sync with their last sequence number. A client id makes retries safe. Groups store the message once and fan out the delivery. Presence comes from heartbeats and goes only to people who are looking.
| Decision | What we gain | What it costs |
|---|---|---|
| Persist before ack | An acked message is never lost. | A little added latency for the sender, and a write on the hot path. |
| Per-conversation sequence numbers | A clear order and exact catch-up. | One writer per conversation, and no order across conversations. |
| Store a group message once, fan out delivery | Storage and writes do not grow with group size. | Delivery loops and per-member receipt state. |
| Heartbeat presence with a TTL | Cheap, and dead phones expire by themselves. | Online and last seen are a little late. |
| Wide-column store partitioned by conversation | History is one range read, and it scales out. | No joins, and cross-conversation queries need another system. |
| Stateful gateways | True push with low latency. | Reconnect storms, drains for deploys and a routing registry to run. |
Interviewers want to see that you know the connection tier is the hard, stateful part.
The correctness questions. Be exact about what is saved when, and what the ids are for.
Where the cost maths shows up. Say the numbers, and say which path changes with size.
These test whether you can extend or defend the design.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| Add voice and video calls | Use the chat path only for signalling (who calls whom, session setup). Media goes over a separate real-time path (WebRTC) with relay servers when a direct link is not possible. |
| Add message search | Build a search index from the message stream, per user or per conversation. This is impossible on the server if messages are end-to-end encrypted, so it moves to the device. |
| Messages must expire (disappearing messages) | Store an expiry time. Clients delete at expiry, and the server drops the record with a TTL. Make sure backups and caches honour it. |
| Add end-to-end encryption | Server stores ciphertext only. A message is encrypted once per recipient device. Search, spam scanning and server-side backups change. |
| Support 10 times more users | About 8,000 gateways and a sharded registry. Partition the message store further. Automate gateway draining and reconnect throttling. The design is the same. |
| Groups become huge (channels) | Ping-and-pull delivery, sampled or no receipts, a CDN-like cache for the recent range, and time-bucketed partitions. |
| Users are on slow, unreliable networks | Smaller frames, compression, longer timeouts, an outbox on the phone, and aggressive batching of acks and presence. |
| The company wants analytics on usage | Emit events (sent, delivered, read) to a stream, off the hot path, and process them in batch. Never read the message store for analytics. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts drawing boxes. Never asks about groups, offline users or devices. | Asks about groups, media, receipts, offline and scale, and states what is out of scope. | Uses each answer to justify a design choice, and names end-to-end encryption as a later extension. |
| Estimation | No numbers, or only messages per second. | Messages per second, connections, storage per year. | Gets to 100M connections and 800 gateways, separates media from text, and sees that presence would be bigger than the messages. |
| Delivery correctness | “Send it to the other user.” No acks, no offline path. | Persists, acks, pushes, and syncs on reconnect. | Persist before ack, client ids and dedup, receipts as sequence numbers, and a safety net through sync. |
| Ordering | Sorts by timestamp. | Uses a sequence number per conversation. | Explains why global order is unnecessary, how gaps drive catch-up, and what happens with simultaneous sends. |
| Scale and failure | “Add more servers.” | Gateway tier, registry and sharded store, with replicas. | Reconnect storms with jitter, draining, a degraded registry that never loses messages, and multi-region limits. |
| Communication | Lists components with no reason. | Follows the steps and explains choices. | States trade-offs, gives numbers for decisions, and handles curveballs calmly. |
| Mistake | Do this instead |
|---|---|
| Polling instead of a persistent connection | Say WebSocket early, then handle the cost: stateful gateways, a registry, backoff. |
| Acking before the message is saved | Persist first, then ack. State the rule out loud. |
| Ignoring retries and duplicates | Give every message a client id, and make the server check it as part of the write. |
| Ordering by wall-clock time | Use a sequence number per conversation, and explain gaps and catch-up. |
| Copying each group message into every inbox | Store once, fan out delivery, and name ping-and-pull for very large groups. |
| Telling all contacts about every presence change | Do the maths (about 11.6M updates a second) and send presence only to those looking. |
| Putting media in the message store | Pre-signed upload to object storage, CDN for download, and a reference in the message. |
| No plan for reconnect storms | Exponential backoff with jitter on clients, gradual draining, and load shedding on the server. |
The connection that lets the server push a message.
Why a per-conversation order is enough.
At-least-once delivery plus dedup gives effectively once.
How the server recognises a retried message.
How offline users are reached.
How presence and dead connections are detected.
Partitioning messages by conversation.
Where the message ids come from.