SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a Chat App
  • Design a News Feed
  • Design a Notification System
  • Design a Web Crawler
  • Design Search Autocomplete
  • Design File Storage (Dropbox)
  • Design Video Streaming (YouTube/Netflix)
  • Design a Distributed Cache
  • Design a Leaderboard
  • Design a Job Scheduler
  • Design a Social Media Platform (Facebook)
System Design/Case Studies/Medium
Interview case study

Design a Chat App

One-to-one and group messaging that feels instant: connections, delivery, ordering and offline users.

⏱ 34 min readMedium case studyIntermediate24 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a chat application like WhatsApp or Messenger.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Choosing the connection modelChat needs the server to push. A strong candidate says WebSocket (or similar), and then deals with the cost: millions of open, stateful connections.
Reliable deliveryMessages must not be lost or shown twice. This is persist-before-ack, client ids, retries and receipts, in the right order.
Ordering and identityYou must say what order means in a chat (per conversation, not global) and how a phone catches up after being offline.
Fan-out thinkingA group of 5 and a channel of 100,000 need different designs. Interviewers want to see you do the cost maths.
Stateful systems at scaleGateways remember who is connected. Presence, reconnect storms and routing a message to the right gateway are the real difficulty.

TL;DRThe whole design in 60 seconds

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.

  • Scale: 500M daily users and 40 messages each is 20 billion messages a day, about 230,000 a second on average and about 700,000 at peak. Around 100M phones are connected at once, so roughly 800 gateways.
  • Routing: a registry (Redis) maps user to gateway. The chat service looks up each recipient and pushes the message to that gateway. If there is no entry, the user is offline: keep the message and send a push notification.
  • Reliability: every message has a client-made id. The phone retries until acked, the server checks the id, so a retry is safe. On reconnect the phone says “my last seq is 118” and gets everything after it.
  • Ordering: a sequence number per conversation. Global order is not needed.
  • Storage: a wide-column store keyed by (conversation, seq), partitioned by conversation. Media goes to object storage and a CDN.
  • Groups: small groups fan out on write to each member. Huge channels store the message once and members pull it.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
4
5
8
15
6
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify41:1 and groups, media, history, multi-device, presence. Say what you will skip (end-to-end encryption, calls).
2. Estimate4Messages per second, concurrent connections, gateway count, storage per year, media.
3. API and data5WebSocket frames, a few REST calls, the message and conversation tables.
4. High-level design8Gateways, registry, chat service, message store, push, media path. One send, one offline case.
5. Deep dives15Delivery and acks, ordering and ids, group fan-out, presence and connections.
6. Scale and failures6Gateway crash, reconnect storm, hot conversations, multi-region, abuse.
7. Wrap up3Recap, trade-offs, what you would add next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write down five questions that would change the design. Hint: think about group size, what happens to a phone that is offline, whether the phone has several devices, and whether the server may read messages.

Questions to ask, and why

AskWhy you ask itTypical answerHow 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.

Write the scope on the board

Functional (must do)
  • •Send and receive text and media, one-to-one and in groups
  • •Delivery states: sent, delivered, read
  • •Offline users get messages when they return, and a push notification
  • •Message history per conversation, with paging
  • •Online and last-seen status for contacts
  • •Several devices per user stay in sync
Non-functional (how well)
  • •Low latency: under 500 ms from send to display when both are online
  • •Reliable: an acked message is never lost, and the user never sees it twice
  • •Highly available: 99.99%
  • •Ordered within a conversation
  • •Scales to 500M daily users and 100M connected at once
  • •Durable: messages kept with replication
Out of scope (say it)
  • •End-to-end encryption (mention it at the end)
  • •Voice and video calls
  • •Full-text search of messages
  • •Large broadcast channels (name the pull model later)
  • •Stories, payments and bots
🎤
Say it out loud
“Let me confirm the scope. One-to-one chat and groups up to 500 people, text plus images and short video, with sent, delivered and read receipts. Offline users get the message when they come back, plus a push notification. Up to four devices per user, online status for contacts, and full history. I will skip end-to-end encryption, calls, search and huge broadcast channels, and mention them at the end. The scale is 500M daily users with 40 messages each. We want under 500 ms delivery, 99.99% availability, and never losing an acked message. Does that match?”

Step 2Estimate the scaleabout 4 min

🤔
Pause. Try it yourself first
On paper: how many messages a second is 500M users times 40 a day? How many phones are connected at once, and how many gateways hold them? How big is a year of messages?

Assumptions (say them first)

AssumptionValue
Daily active users500 million
Messages sent per user per day40
Average message record (text, ids, metadata)200 bytes
Peak versus average traffic3 times
Recipients per message (1:1 and small groups)3 on average
Share of daily users connected at one moment20%
Connections one gateway can hold125,000
Messages that carry media10%, about 200 KB each
Presence changes per user per day10

The arithmetic, line by line

WhatMathsResult
Messages per day500M users × 4020 billion
Messages per second (average)20 billion ÷ 86,400 (about 10^5)about 230,000 per second
Messages per second (peak)230,000 × 3about 700,000 per second
Deliveries per second at peak700,000 × 3 recipientsabout 2.1 million per second
Outbound bandwidth at peak2.1M × 200 bytesabout 420 MB/s, 3.4 Gbit/s
Text storage per day20 billion × 200 bytes4 TB per day
Text storage per year (3 copies)4 TB × 365 × 3about 4.4 PB
Connected phones at once500M × 20%100 million
Gateways needed100M ÷ 125,000800 gateways
Heartbeats per second100M connections ÷ 30 s3.3 million per second (about 4,200 per gateway)
Registry size100M entries × 100 bytesabout 10 GB, fits in memory
Media per day20 billion × 10% × 200 KB400 TB per day, 100 times the text
Presence updates to deliver, naive500M × 10 ÷ 86,400 = 58,000 per second; × 200 contacts11.6 million per second
Presence, only to people watching (5%)11.6M × 5%about 580,000 per second
What the numbers tell us about the design
  • •100 million open connections is the central fact. The connection tier is its own, stateful system, and it must be designed first.
  • •Text is small (4 TB a day), media is huge (400 TB a day). Keep them on different paths, and never put media in the message store.
  • •One message becomes about three deliveries, so fan-out and the routing lookup run millions of times a second. The registry must be in memory.
  • •Naive presence would be 11.6 million updates a second, more than the messages themselves. Send it only to people who are looking.
  • •Heartbeats alone are 3.3 million a second. Keep them tiny, and handle them in the gateway without touching a database.
🎤
Say it out loud
“500M users at 40 messages a day is 20 billion messages, about 230,000 a second, and about 700,000 at peak. With roughly three recipients each, that is around 2 million deliveries a second. If a fifth of users are connected, that is 100 million WebSockets. At 125,000 per gateway, about 800 gateways. Text is 4 TB a day, but media is about 100 times that, so media gets its own path through object storage. These are assumptions. The design consequences are that connections are the hard part, the routing table lives in memory, and presence must not be sent to everyone.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the frames that go over the WebSocket for send, ack and receive. What id does the phone attach to a new message? What does it send when it reconnects?

Endpoints

MethodPathRequestResponseNotes
POSTws: 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.
GETws: 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.
POSTws: sync{ last_seq per conversation }all messages after those seqsSent on every reconnect. This is how a phone catches up after being offline.
GET/v1/conversations/{id}/messages?before_seq=&limit=50none200 { 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.

Data model

TableKeyHolds
messagespartition: conv_id, sort: seqmsg_id, client_id, sender_id, body or media_ref, sent_at, deleted flag
conversations_by_userpartition: user_id, sort: last_msg_timeconv_id, last_seq, unread_count, muted. This is the inbox list.
memberspartition: conv_id, sort: user_idrole, joined_at. A second copy keyed by user_id lists a user's groups.
receiptspartition: conv_id, sort: user_idlast_delivered_seq and last_read_seq per member (one row per member, not per message)
devicespartition: user_id, sort: device_idpush endpoint, platform, last_seq_seen
The registry (in memory, not a database)
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)
📝Which store, and why
Messages are append-mostly, read by (conversation, recent first), and huge in number. That is a wide-column store (Cassandra style) or a key-value store partitioned by conversation, with the sequence number as the sort key. One partition holds one conversation, so history is a single range read. Do not use a relational database for messages at this size. User and group data is small and can stay in a normal database. The registry is a Redis-style in-memory store, because it is read millions of times a second.
🎤
Say it out loud
“Most traffic is WebSocket frames: send, deliver, ack and sync. A send carries a client id that the phone makes, so a retry is safe, and the ack comes back only after the message is saved, with the conversation sequence number. On reconnect the phone sends the last sequence it saw and gets everything after it. History is a REST call paged by sequence. Media uploads go straight to object storage through a pre-signed URL. Messages live in a wide-column store, partitioned by conversation and sorted by sequence.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw a phone, the connection tier, and where a message is saved. Then draw what happens when the recipient has no connection. Where does the registry sit?
Chat app: high-level design
📱Phone AWebSocket
→↓send
🚪Gatewayholds connections
→↓frame
💬Chat servicesave, then route
→↓deliver
🚪Gateway (B)found in registry
→↓push frame
📱Phone B
Hot state (memory)
🧭Session registryuser to gateway
🟢Presence serviceheartbeats, last seen
Durable state
🗄️Message storeby conversation, seq
👥User and group DBmembers, devices
Offline and media
🔔Push serviceAPNs / FCM
🖼️Object storage + CDNphotos and video
Gateways hold connections. The chat service saves, then routes through the registry. Offline users get a push.
ComponentWhat it does
GatewayTerminates 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 registryMaps each user device to the gateway holding its connection. In memory, with a short TTL that heartbeats renew.
Chat serviceStateless. Assigns the sequence number, saves the message, acks the sender, looks up recipients and hands the message to their gateways.
Message storeWide-column store partitioned by conversation. Replicated three times. The source of truth.
Presence serviceTracks who is online from heartbeats, and tells only the people watching.
Push serviceSends notifications through Apple and Google when the recipient has no live connection.
Media pathUpload to object storage with a pre-signed URL, serve through a CDN. The message holds only a reference.
Group serviceStores membership, answers “who is in this group”, and drives fan-out.
Write path (follow one request)
  1. Phone A makes the message with a client id and sends it over its WebSocket to its gateway.
  2. The gateway forwards the frame to the chat service, which checks the sender is a member and applies a rate limit.
  3. The chat service looks up the client id. If it has been seen, it returns the earlier ack and stops.
  4. It assigns the next sequence number for the conversation and writes the message to the store (replicated).
  5. Only after the write succeeds does it ack Phone A (one tick: sent).
  6. It finds each recipient's devices in the registry and sends the message to those gateways.
  7. For a recipient with no entry in the registry, it keeps the message pending and asks the push service to notify the device.
Read path (follow one request)
  1. A gateway pushes the message frame to Phone B over the open WebSocket.
  2. Phone B stores it, shows it, and sends a delivered ack with the conversation id and seq.
  3. The chat service records last_delivered_seq for B, and tells A's gateway so A shows two ticks.
  4. If B was offline: B opens the app, connects, and sends sync with its last seq for each conversation.
  5. The chat service reads the missing range from the store and streams it to B. Then B sends its delivered ack.
  6. History scrolling uses the REST call, paged by sequence number, straight from the store.
🎤
Say it out loud
“Here is the picture. Phones hold a WebSocket to a gateway. A send goes to the chat service, which saves the message, assigns a sequence number in the conversation, and acks the sender only after the save. Then it looks up each recipient in an in-memory registry that maps users to gateways, and pushes the message there. If there is no entry, the message waits in the store and a push notification goes out. When a phone reconnects it sends its last sequence number and gets what it missed. Media goes straight to object storage and the message carries a reference.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

Delivering a message without losing or duplicating it

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.

OptionHow it worksGoodBad
Fire and forgetThe 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 savingThe 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 + dedupThe 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.
Pick
Save before ack, retry from the phone with a client id, and dedup on that id

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”.

MomentWhat happenedWhy the user is safe
Crash before the saveNothing stored, no ackThe phone times out and retries. It is a normal first save.
Crash after the save, before the ackStored, but the phone has no ackThe retry finds the client id and returns the same seq. No second copy.
Ack lost on the way backStored and passed on, phone unsureSame: the retry is recognised and answered from the record.
Crash after save, before passing it onStored, recipient not toldThe recipient syncs with its last seq on its next heartbeat or reconnect.
Recipient offlineStored, push sentDelivered on reconnect through sync. The push is only a nudge.
💡Where the id check lives
Make the check part of the write: a conditional insert on (conversation, client id), or a unique index. A separate “read, then write” check has a race when two retries arrive together.
🎤
Say it out loud
“I would save before acking. The sender gets one tick only after the message is in the replicated store. If the ack is lost, the phone retries with the same client id, and the server finds the id and returns the same sequence number, so the retry is safe. For the recipient, the server pushes and waits for a delivered ack. Anything not acked is fetched through sync when the phone reconnects. So the result is at-least-once on the wire and effectively-once for the user.”
5.2

Ordering messages and catching up after being offline

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.

OptionHow it worksGoodBad
Sender's timestampOrder 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 timestampThe 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 conversationThe 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.
Pick
A sequence number per conversation, assigned when the message is saved

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.

Catching up after being offline
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 }
📝What if two people send at the same moment?
Both messages reach the partition owner. It takes them in the order they arrive and gives them 119 and 120. Everyone sees 119, then 120. Which one was “really first” does not matter, because the order is the same for everyone. Say that out loud.
🎤
Say it out loud
“Order only matters inside a conversation, so I give each conversation a sequence number, assigned by the partition that stores it, as part of the write. Everyone sees the same order. The phone remembers its last sequence for each conversation, and on reconnect it asks for everything after it. A gap in the numbers tells it exactly what is missing. I would still keep a globally unique message id for replies and deletes, but ordering comes from the counter, not from clocks.”
5.3

Group chat fan-out

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.

OptionHow it worksGoodBad
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 sizeSmall 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.
Pick
Store the message once in the conversation, then fan out the delivery (not the data) for small groups, and use a ping-and-pull for large ones

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 sizeMessage copies storedDeliveries per messageApproach
2 (one to one)11 to 2Direct push to each device
501up to 50Loop over members, push through gateways
5001up to 500Same, spread over many chat workers, batch by gateway
100,000 (channel)1tens of thousands onlinePing and pull, with receipts turned off or sampled
🎤
Say it out loud
“I would store each message once under its conversation, whatever the group size, and fan out only the delivery. For a group of 500 the chat service looks up the members, groups them by gateway so each gateway gets the message once, and pushes. Read receipts are two numbers per member, not a copy of the message. For huge channels I would not loop at all: I would send a small ping saying there is a new sequence number, and let clients pull. That is out of scope for now, but I would say it so you know I have seen the limit.”
5.4

Presence and connections at scale

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.

OptionHow it worksGoodBad
Update a database on every changeWrite 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 TTLEach 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 contactsTell 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 lookingA 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.
Pick
Heartbeats into an in-memory registry with a TTL, and presence fan-out only to people who are looking

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.

EventWhat the system does
Phone loses signal for 5 secondsReconnects quietly. The grace delay means no one is told it was offline.
Phone is switched offHeartbeats stop. The TTL expires after about a minute. Last seen is recorded. Messages now go to the push path.
Gateway crashesIts registry entries expire. Phones reconnect to other gateways, with jitter, and sync.
Deploy of a tenth of the fleetDrain gateways slowly: tell clients to reconnect, a few percent at a time.
Phone has two devicesThe registry holds a set of connections. A message goes to each live device.
⚠️The registry must not become a single point of failure
Shard the registry by user id, and replicate each shard. If the registry loses an entry, the worst case is an unneeded push and a sync on reconnect. A lost registry entry must degrade delivery, never lose a message.
🎤
Say it out loud
“A phone sends a tiny heartbeat every 30 seconds, and the gateway renews its registry entry with a 60-second TTL. So the registry is both the routing table and the presence record, and a dead phone expires by itself. I would show presence only to people who are looking, because telling every contact would be around 11 million updates a second. The real risk is a reconnect storm after a gateway crash or deploy, so clients reconnect with exponential backoff and jitter, and we drain gateways slowly. If the registry loses an entry, we fall back to the store and sync, so a message is never lost.”
VisualizerOne message, one fault: save, ack, retry and dedupPick whether the recipient is online, then a fault (a lost reply or a crash). Turn the phone's retry and the server's client-id check on or off, and step through to see the message get lost, duplicated, or delivered exactly once.
Recipient
What goes wrong?
Phone retries with the same id
Server checks the client id
Copies in the store
2
Recipient sees
2
copies
Sender sees
✓✓ delivered
Push sent
no
not needed
Duplicated. The recipient sees the same message twice. The retry created a second copy because the server could not tell it was a repeat. Checking the client id fixes this. Checking the seq cannot, because each copy got its own seq.
Phone A (sender)
⏱ sending
outbox: m1 (a1)
Chat server
running
saves first, replies after
Message store
empty
Phone B (online)
screen: nothing yet
Step 1 of 7
1. The sender taps send
Phone A makes message m1 with its own id, a1, keeps it in an outbox on the phone, and sends it over its WebSocket. It shows a clock, because nothing is confirmed yet.

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.

Step 6Scale, bottlenecks and failuresabout 6 min

🤔
Pause. Try it yourself first
If one gateway dies, what do its users see? If one group gets a thousand messages a minute, what is hot? If a whole region is lost, where do phones go?

What breaks first, and the fix

BottleneckFix
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 outageQueue pushes, collapse repeats (“12 new messages”), and respect the provider's rate limits.
Presence stormsSubscribe-only presence, batching, and a grace delay before announcing offline.

What if a part fails?

FailureHow the design copes
A gateway crashesIts 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-sendIf 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 failsThree replicas. Writes need a quorum (two of three), so one failure is invisible. Repair brings the node back in line.
The registry loses dataTreat 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 downMessages still arrive when the app is opened. Queue and retry pushes with backoff.
A region is lostPhones 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.
What to monitor
  • •Send-to-deliver latency, p50 and p99, for online recipients
  • •Connected devices per gateway, connection churn, and reconnect rate
  • •Ack timeouts and client retry rate (a rising retry rate means something is failing)
  • •Message store write latency and error rate, per partition
  • •Registry hit rate, TTL expiry rate and heartbeat lag
  • •Push queue depth and provider error rate
Security and abuse
  • •Authenticate the WebSocket at connect time with a short-lived credential, and check conversation membership on every send and sync.
  • •Rate limit sends per user and per device, and limit group creation and invites, to slow spam. See Rate Limiting.
  • •Validate and size-limit every frame. Scan uploaded media for malware, and strip metadata such as location.
  • •Encrypt traffic with TLS and data at rest. End-to-end encryption is the next step (see the wrap-up).
  • •Let users block and report, and keep an audit trail for abuse handling.

Step 7Wrap upabout 3 min

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.

Trade-offs you made

DecisionWhat we gainWhat it costs
Persist before ackAn acked message is never lost.A little added latency for the sender, and a write on the hot path.
Per-conversation sequence numbersA clear order and exact catch-up.One writer per conversation, and no order across conversations.
Store a group message once, fan out deliveryStorage and writes do not grow with group size.Delivery loops and per-member receipt state.
Heartbeat presence with a TTLCheap, and dead phones expire by themselves.Online and last seen are a little late.
Wide-column store partitioned by conversationHistory is one range read, and it scales out.No joins, and cross-conversation queries need another system.
Stateful gatewaysTrue push with low latency.Reconnect storms, drains for deploys and a routing registry to run.
If we had more time, we would…
  • •End-to-end encryption: the server stores and forwards ciphertext. Key exchange moves to the clients, and search and server-side spam checks stop working.
  • •Large broadcast channels with ping-and-pull delivery and sampled receipts.
  • •Multi-region active-active, with a home region for each conversation.
  • •Message search, with a separate index built from the message stream.
  • •Voice and video calls, which use a separate real-time media path.
🎤
Say it out loud
“To recap: WebSocket gateways hold the connections, and a stateless chat service saves each message first, with a per-conversation sequence number, then acks the sender. A registry in memory finds the recipient's gateway, and if there is none, we send a push and the phone catches up with sync. A client id makes retries safe. Groups store the message once and fan out delivery, and presence comes from heartbeats and is shown only to people who are looking. With more time I would add end-to-end encryption, large channels, and multi-region.”

Q&ACross-questions (24)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Connections and scale

Interviewers want to see that you know the connection tier is the hard, stateful part.

Delivery, ordering and storage

The correctness questions. Be exact about what is saved when, and what the ids are for.

Groups, presence and features

Where the cost maths shows up. Say the numbers, and say which path changes with size.

Curveballs

These test whether you can extend or defend the design.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Add voice and video callsUse 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 searchBuild 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 encryptionServer stores ciphertext only. A message is encrypted once per recipient device. Search, spam scanning and server-side backups change.
Support 10 times more usersAbout 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 networksSmaller frames, compression, longer timeouts, an outbox on the phone, and aggressive batching of acks and presence.
The company wants analytics on usageEmit events (sent, delivered, read) to a stream, off the hot path, and process them in batch. Never read the message store for analytics.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts 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.
EstimationNo 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.
OrderingSorts 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.
CommunicationLists components with no reason.Follows the steps and explains choices.States trade-offs, gives numbers for decisions, and handles curveballs calmly.

AvoidCommon mistakes on this question

MistakeDo this instead
Polling instead of a persistent connectionSay WebSocket early, then handle the cost: stateful gateways, a registry, backoff.
Acking before the message is savedPersist first, then ack. State the rule out loud.
Ignoring retries and duplicatesGive every message a client id, and make the server check it as part of the write.
Ordering by wall-clock timeUse a sequence number per conversation, and explain gaps and catch-up.
Copying each group message into every inboxStore once, fan out delivery, and name ping-and-pull for very large groups.
Telling all contacts about every presence changeDo the maths (about 11.6M updates a second) and send presence only to those looking.
Putting media in the message storePre-signed upload to object storage, CDN for download, and a reference in the message.
No plan for reconnect stormsExponential backoff with jitter on clients, gradual draining, and load shedding on the server.

Revise60-second revision sheet

  • ✔Scale: 500M users × 40 = 20B messages a day, about 230,000 a second, 700,000 at peak. 100M connections, about 800 gateways.
  • ✔Connection: a WebSocket per phone to a thin, stateful gateway. Logic lives in a stateless chat service.
  • ✔Reliability: save to the replicated store, then ack. The phone retries with a client id and the server dedups.
  • ✔Routing: an in-memory registry maps user to gateway (about 10 GB). No entry means offline: store and push.
  • ✔Order: a sequence number per conversation. The phone syncs with its last seq on reconnect.
  • ✔Groups: store the message once, fan out the delivery. Huge channels use ping and pull.
  • ✔Presence: heartbeats every 30 s, a 60 s TTL, and updates only to people who are looking.
  • ✔Storage: a wide-column store keyed by (conversation, seq). Media in object storage and a CDN.
  • ✔Failures: backoff plus jitter to prevent reconnect storms, and drain gateways slowly on deploy.
  • ✔One line: “Save, then ack, give every message an id, number it per conversation, and let the phone ask for what it missed.”

Read these topics next

WebSockets→

The connection that lets the server push a message.

Message Ordering→

Why a per-conversation order is enough.

Delivery Semantics→

At-least-once delivery plus dedup gives effectively once.

Idempotent Consumer and Inbox Pattern→

How the server recognises a retried message.

Push Notifications→

How offline users are reached.

Heartbeats→

How presence and dead connections are detected.

Sharding→

Partitioning messages by conversation.

Design a Unique ID Generator→

Where the message ids come from.

← Previous
Design a Scalable Parking System (Smart Parking)
Next →
Design a News Feed