Try it before you read it
You will remember far more of this walkthrough if you attempt the problem first. Run it as a timed 45-minute practice, then come back and compare stage by stage. Each section below opens with what the interviewer wants from that stage and how long to spend on it.
Requirements
~5 minIn the interview: Clarify functional requirements (what the system must do) and non-functional ones (scale, latency, availability, consistency). State what is out of scope.
Functional
- One-to-one chat: send text (and small media references) to another user.
- Group chat: up to a few hundred members per group.
- Delivery receipts: sent (server has it), delivered (recipient device has it), read.
- Offline support: a recipient who is offline receives every message when they reconnect, in order.
- Message history: a device can fetch older messages for a conversation.
- Presence: online / last seen; typing indicators are nice-to-have.
Non-functional
- Low latency: a message between two online users arrives in under ~200 ms end to end.
- Ordering: within a conversation every participant sees the same order.
- Durability: once the server acknowledges a message it is never lost.
- Highly available: a connection server dying must not drop messages, only connections.
- Scale: hundreds of millions of daily active users, tens of billions of messages per day.
Out of scope
- Voice/video calls, stories, media transcoding, spam detection, end-to-end encryption key exchange (we discuss its impact in the deep dive).
Back-of-envelope estimates
~5 minIn the interview: Estimate QPS (read and write), storage over 5 years, bandwidth and cache size. Show the arithmetic.
Assumptions
- 500M DAU, each sends 40 messages/day → 20B messages/day.
- Average message ~100 bytes of text plus ~100 bytes of metadata (ids, timestamps, status) ≈ 200 B.
- Each user keeps one persistent connection most of the day; ~50% of DAU online at peak.
Traffic
- Writes: 20B / 86,400 s ≈ 230K messages/s average; peak 3× ≈ 700K/s. The store has to absorb this as appends, which is why the message store is chosen for sequential writes.
- Each message produces at least one delivery push plus two receipt updates, so the fan-out write rate is 3–4× the ingest rate: around 2–3M small operations per second at peak across the routing layer.
- Group messages multiply: a message to a 100-person group is 1 store write but 100 pushes, so group traffic is bounded by pushes, not storage.
Connections
- 250M concurrent WebSocket connections at peak, each one a long-lived socket that must live on some server.
- A tuned connection server holds ~200K–500K idle connections (limited by memory per socket, roughly 10–20 KB, and file descriptors). 250M / 250K ≈ 1,000 connection servers, plus headroom, so the fleet must be cheap and interchangeable.
Storage
- 20B × 200 B = 4 TB/day of messages. Over 5 years ≈ 7 PB, which is only feasible with a horizontally sharded wide-column store and a retention policy (e.g. drop server copies 30 days after delivery to all devices).
- Media is stored in object storage, referenced by URL; it dominates bytes but not the message path.
Memory for registry and presence
- Connection registry: 250M entries × ~50 B (user_id → server_id, timestamp) ≈ 12.5 GB. Fits a Redis cluster easily.
- Presence heartbeats every 30 s from 250M users ≈ 8M writes/s to presence, far too many to write one by one. Batch and coalesce them on the connection server, or drop to "last seen" granularity of minutes.
Bandwidth
- 700K msg/s × 200 B ≈ 140 MB/s ingest at peak. Small compared with media, so network capacity is not the constraint; connection count is.
API design
~5 minIn the interview: Define the core endpoints, their inputs, outputs and error cases.
Connection
- WebSocket wss://chat.example.com/ws with an auth token on connect. The server returns a session id and resume cursor.
- Client sends a heartbeat (ping) every 30 s; the server closes idle sockets after 2 missed beats.
Over the socket (JSON or protobuf frames)
- send_message { client_msg_id, conversation_id, body, media_ref? } → server replies ack { client_msg_id, message_id, seq, server_ts }. client_msg_id makes retries idempotent.
- message (server → client) { message_id, conversation_id, seq, sender_id, body, server_ts }.
- receipt { message_id, conversation_id, status: delivered | read } in both directions.
- typing { conversation_id, is_typing } best effort, never persisted.
REST for everything that is not real time
- GET /v1/conversations?cursor= → list of conversations with last message and unread count.
- GET /v1/conversations/{id}/messages?before_seq=&limit=50 → history page, newest first.
- POST /v1/groups { name, member_ids[] } and POST /v1/groups/{id}/members.
- POST /v1/media/upload-url → pre-signed URL; the message carries the resulting media_ref.
- GET /v1/sync?since_cursor= → every message and receipt the device missed, used on reconnect.
Errors
- 401 bad token, 403 not a conversation member, 413 message too large, 429 sending too fast, 409 duplicate client_msg_id (returns the original ack).
Data model
~5 minIn the interview: Define the main entities, keys, indexes, and pick a storage technology with a reason.
Entity: message
- conversation_id (partition key), seq (clustering key, ascending)
- message_id (globally unique, Snowflake-style), sender_id, body, media_ref, server_ts
- Reads are always "messages for conversation X after/before seq N", which maps to a single partition range scan.
Entity: conversation
- conversation_id (PK), type (direct | group), created_at, last_seq
- conversation_member: (conversation_id, user_id) → joined_at, role, last_read_seq, muted
Entity: user_inbox (per-user pending deliveries)
- user_id (partition key), message_id, conversation_id, seq, enqueued_at
- Rows are removed once the device acks delivery. This is what offline sync reads.
Entity: receipt
- (message_id, user_id) → delivered_at, read_at. For groups, aggregate "delivered to all" lazily.
Storage choice
- Messages: a wide-column store (Cassandra, ScyllaDB, HBase) keyed by conversation_id with seq as the clustering column. Append-heavy, time-ordered reads, horizontal scale, cheap tiered storage for old partitions.
- Conversation metadata and membership: relational or a document store; small and relational-shaped.
- Connection registry and presence: Redis (user_id → connection_server_id, last_seen), with TTLs so dead servers age out.
- Hot conversations: the last ~50 messages per active conversation in a Redis list to serve history and reconnects without touching the wide-column store.
Blue: services · Green: durable stores · Yellow: caches · Purple: queues · Red: third parties · Dashed arrows: asynchronous.
Messages are partitioned by conversation and clustered by seq so history and gap fills are single-partition range scans. The inbox is partitioned by user so a reconnect is one scan. Receipts are separate because they churn far more than messages.
High-level design
~10 minIn the interview: Draw the main components and the request flow for reads and writes. Keep it simple first.
Components
- Connection servers: terminate WebSockets, hold millions of sockets, and do nothing clever. They are stateless apart from the sockets themselves, so losing one loses only the connections on it, which clients re-establish elsewhere.
- Connection registry (Redis): maps user_id → the id of the connection server currently holding that user's socket. Written on connect, deleted on disconnect, with a TTL as a safety net so a crashed server's entries disappear on their own.
- Chat service: validates the message, assigns a per-conversation sequence number, persists the message, and routes it to the recipient's connection server.
- Message store: a wide-column store keyed by conversation, where each conversation's messages are one ordered partition.
- Inbox / delivery queue: per-user list of messages that have not yet been acknowledged by that user's device, which is what an offline recipient drains on reconnect.
- Presence service: last seen and online status, fed by heartbeats batched by the connection servers.
- Media: object storage behind a CDN, uploaded directly by the client via pre-signed URLs so message traffic never carries bytes.
Send path (both users online)
1. Alice's client sends a send_message frame over her WebSocket to connection server A, carrying a client_msg_id she generated so a retry can be recognised.
2. A forwards the frame to the chat service. The chat service assigns seq = last_seq + 1 for the conversation, writes the message row (conversation_id, seq, body, sender, timestamp) to the store, and only then acks Alice with the assigned seq. Her client shows a single tick ("sent") because the server now has a durable copy.
3. The chat service looks up Bob in the registry, finds connection server C, and pushes the message to C over an internal RPC or a pub/sub channel that C subscribes to.
4. C writes the frame to Bob's socket. Bob's client stores it locally and sends a delivered receipt; the receipt travels back through the chat service to Alice's connection server, and her client shows a double tick ("delivered").
5. When Bob opens the chat his client sends a read receipt, which follows the same route and updates Alice's view to "read".
Send path (Bob offline)
- Step 3 finds no registry entry for Bob. The chat service appends the message to Bob's inbox and, if enabled, asks the push notification system to wake his phone with a notification that carries no body. When Bob reconnects, his client calls sync with the last cursor it acknowledged, and the server returns every inbox row above it in seq order; the client acks them in batches and the server deletes the acked rows.
Why a separate chat service rather than connection servers talking to each other directly?
- Sequence assignment and persistence need to happen exactly once per message, in one place that owns the conversation's counter. Keeping that in the chat service means connection servers stay dumb and interchangeable, which is what lets you run a thousand of them cheaply.
Messages must reach an online user in under ~200 ms, so both clients keep WebSockets open to connection servers behind the L4 load balancer. Connection server A forwards Alice’s message to the chat service, which pushes it through connection server C to Bob’s socket.
Say: I keep connection servers dumb; the chat service owns all message logic.
Faded boxes arrive in a later step; outlined boxes are new in this one.
Draw the socket layer first, then the chat service that owns sequencing and persistence, then the stores. Say that connection servers are deliberately dumb so thousands of them can be added and replaced without touching message logic.
Deep dives
~10 minIn the interview: Pick the 2–3 hardest parts (bottlenecks, hot paths, failure modes) and go deep.
1. Connection servers and the registry
- Each server holds up to a few hundred thousand sockets. Clients connect through a layer-4 load balancer, which balances TCP connections rather than HTTP requests; once a socket is open it stays on that server for its lifetime, so there is no need for sticky HTTP sessions.
- On connect, the server writes SET user:{id} → server_id into the registry with a TTL of ~60 s and refreshes it on every heartbeat. On a clean disconnect it runs DEL. If a server dies without cleaning up, its entries expire within a minute, clients reconnect to other servers and write fresh entries, and any message routed during the gap is still safe because it was written to the recipient's inbox before the push was attempted.
- Routing a message from the chat service to a specific server works either by direct RPC to that server's address, or by publishing to a pub/sub topic per server (a Redis channel or a Kafka partition per server) that the server subscribes to. Pub/sub is simpler to reason about when servers are added and removed, because the chat service never needs an address list.
- A user with multiple devices has one registry entry per device. The chat service delivers to every device, and each device acks separately, so one phone being offline does not block delivery to the laptop.
2. Ordering with per-conversation sequence numbers
- Client timestamps cannot be used for ordering because clocks drift and offline clients queue messages for hours. Instead the server assigns a monotonically increasing seq per conversation, meaning every message gets the next integer after the previous one.
- Implementation: route all writes for a conversation to one chat service shard (chosen by consistent hashing on conversation_id) so a single process owns the counter. It keeps last_seq in memory and persists it alongside each message. Alternatively use an atomic INCR on a Redis key per conversation; if Redis is lost, the shard re-reads max(seq) from the store before accepting new messages so it never reuses a number.
- Clients keep last_seq per conversation. If a message arrives with seq > last_seq + 1, the client knows a message is missing and fetches the gap from history before rendering. This also makes in-order display trivial: do not render seq N+2 until N+1 has arrived.
- Trade-off: a single writer per conversation limits that conversation's throughput to one shard. That is fine in practice, because no single conversation needs more than a few thousand messages per second.
3. Receipts
- Sent: the chat service acks after the store write succeeds, which tells the sender the message is durable. The client shows one tick.
- Delivered: the recipient device acks over its socket after it has persisted the message locally, and the chat service forwards that ack to the sender. For groups, store per-member delivery and show "delivered" once all members have it, or simply show the count.
- Read: emitted when the conversation is open on screen. Coalesce reads into one receipt saying "read up to seq N" rather than one receipt per message, which cuts receipt traffic by an order of magnitude when someone opens a busy chat.
- Receipts are themselves tiny messages that take the same routing path back to the sender, but they are not sequenced or persisted with the same durability. Losing one is recoverable because the next sync resends the latest delivered and read positions for each conversation.
4. Offline delivery and sync on reconnect
- For every message whose recipient has no live connection, append a row to user_inbox. Even for online recipients, write to the inbox first and delete the row only after the device acks. This makes the live push best-effort and the inbox the source of truth, so a socket closing between push and ack cannot lose a message.
- On reconnect the client sends its cursor (its last acknowledged message_id, or per-conversation last_seq). The server returns the inbox contents above the cursor in order, the client acks in batches of a few hundred, and the server clears the acked rows.
- Mobile push: the inbox write also triggers a notification through APNs/FCM carrying no message body (or an encrypted one). Its only job is to make the user open the app so the socket reconnects and drains the inbox.
- Retention: the inbox for a user who never returns is capped (e.g. 30 days or 10K messages). Beyond the cap the oldest rows are dropped and the client fetches anything older from conversation history on demand.
5. Group chat fan-out
- A group message is stored once under the group's conversation_id, then fanned out: one inbox write and one push per member. For a 256-member group that is 256 small writes, which is acceptable.
- Cap group size (WhatsApp historically 256, now 1,024). Above a few thousand members the per-message fan-out becomes the dominant cost, so switch to pull: members fetch the conversation when they open it instead of receiving per-message pushes, which is how a broadcast channel works.
- Membership changes must be sequenced like messages: "Alice added Bob at seq 1,042" is itself an entry in the conversation, so every client agrees on which messages Bob is allowed to see.
6. Presence and typing
- Presence is heartbeat driven. Every 30 s each of the ~1,000 connection servers batches all of its users into one presence update rather than one write per user, which turns 8M writes/s into 1,000 / 30 s ≈ 33 writes/s, each carrying ~250K heartbeats. A user is shown online if their last heartbeat is under 60 s old, otherwise "last seen at" that time.
- Only publish presence changes to users who are currently looking at you: those with a contact list open or the conversation open. These subscriptions live on the connection server and expire when the screen closes. This turns an N² broadcast (everyone's status to everyone) into a modest fan-out to a few watchers.
- Typing indicators are fire-and-forget frames sent only to online members of the conversation, never persisted, and rate limited to one per 3 s so a fast typist does not generate a frame per keystroke.
7. End-to-end encryption impact
- With E2EE (the Signal protocol) the server stores ciphertext and cannot search, moderate, or render link previews, because it never holds the keys. Group keys are distributed per device, so adding a member means re-keying the group for everyone.
- Message routing, sequencing, receipts and the inbox are unchanged; only the body becomes opaque to the server. Multi-device requires the sender to encrypt once per recipient device, which multiplies the fan-out by the number of devices and is why linked devices are capped.
Number the steps as you draw them: ack to the sender only after the store write, then look up the recipient and push. The delivered receipt takes the same route in reverse. Mention that the inbox write happens before the push, so a dropped push is harmless.
When the registry has no entry for Bob, nothing is pushed; the inbox row and a silent mobile push are the whole story. On reconnect the client sends its cursor and drains the inbox in seq order, acking in batches, then fills any remaining gaps from history.
One store write, then one inbox write and push per member. Point at the member cap: below ~1K members push works; above it, switch to pull where members fetch the conversation on open, like a channel.
Heartbeats are batched per connection server; presence changes are published only to users who are currently subscribed because they have the conversation or contact list open. Typing is a transient frame that never touches storage.
Key decisions
The choices this design turns on. For each, know the options, what you give up with each, and the condition that would make you pick differently: that condition is usually the interviewer’s next question.
How do clients receive messages in real time?
How are messages ordered within a conversation?
Message store?
Wrap-up
~5 minIn the interview: Summarise the key decisions, what you gave up, and what you would do with more time.
Summary of decisions
- WebSockets on dumb connection servers, with a Redis registry mapping user → server, so the fleet scales to thousands of interchangeable boxes.
- A chat service assigns per-conversation sequence numbers and persists before acking, which is what gives every participant the same order and a durable "sent".
- Wide-column message store keyed by (conversation_id, seq) so history is one partition range scan; a per-user inbox for offline delivery.
- Inbox-first delivery makes the live push best effort and the inbox the source of truth, so a dropped socket can only delay a message, never lose it.
- Receipts coalesced into "read up to seq N" and presence published only to subscribers, because both would otherwise cost more traffic than the messages themselves.
What was given up
- A single sequencing shard per conversation caps per-conversation throughput, which is fine because no conversation needs thousands of messages per second.
- Server-side search and rich previews if E2EE is adopted, since the server never sees plaintext.
- Exact "delivered to all" in large groups; we show counts and compute the full state lazily rather than waiting on every member.
With more time
- Media pipeline (thumbnails, transcoding), message search with client-side indexes, spam and abuse detection, multi-region active-active with conversation-home regions, and a proper key distribution service for E2EE.
What good looks like
What an interviewer expects you to cover at each level. Pick your target level and tick what your last attempt covered; the gaps are what to practise next.
Interviewer follow-ups
Questions that come after the main design. Answer each out loud in under two minutes, naming the part of the design that changes.
- How would you add end-to-end encryption and what do you lose server-side?
- How does presence (online/typing) scale?
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Network Load Balancer | L4 load balancer | Cloud Load Balancing (passthrough network) | Azure Load Balancer | HAProxy, Envoy, IPVS |
| Amazon EC2 | Connection server A, Connection server C, Connection server, Connection servers | Compute Engine | Azure Virtual Machines | DigitalOcean Droplets, any VM or bare metal |
| Amazon EC2 Auto Scaling | Chat service, Presence service, Chat service shard, Sync service, Fan-out workers | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon ElastiCache | Connection registry, Registry, Presence store, Subscriptions | Memorystore | Azure Managed Redis | Redis, Valkey, Memcached |
| Amazon Keyspaces | Message store, User inbox, Bob inbox, Member inboxes ×256 | Bigtable | Managed Instance for Apache Cassandra | Apache Cassandra, ScyllaDB |
| Amazon Aurora | Membership | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |