GOAT EngineerPreparing your learning space…

System Design · Interview breakdown · Free article

Design a Chat System (WhatsApp, Messenger)

Send each message once, find the one server holding the recipient’s phone, keep every chat in one order, catch up a phone that was off, and carry groups of any size. Built one step at a time, with experiments you can run.

A chat system lets people send short messages to one person or a group and see them arrive within a second, on every device they own. Each phone holds one open connection to a connection server. A message is numbered in its chat and stored in one database transaction, with an ID from the phone so a retry is never stored twice. Delivery workers find each recipient device in a directory and hand the message to the server holding it. Every message also takes the next number in each member’s inbox, and each device catches up from its own cursor, so a phone that was off misses nothing.

Difficulty: Medium. Reported in interviews at Meta, Anthropic, Databricks, Airbnb, Uber. Also asked as Design WhatsApp, Design Facebook Messenger, Design Slack, Design a real-time chat application.

Practise one part of it on a canvas that tests your design: Deliver Chat Messages to Whoever Is Online.

How do you design a chat system like WhatsApp?

A chat system lets people send short messages to one person or to a group, and see them appear on the other person’s screen within a second. WhatsApp, Messenger, Telegram and Signal are chat systems. So are Slack and Discord, which are built around bigger groups. The hard part is everything around that second. A message must reach a phone that is switched off, turn up on every device a person owns, and sit in the same order for everyone.

  1. Sent: “ok” · one tick. The train enters a tunnel and the reply is lost. The retry must not send it twice.
  2. Stored: Message #41 of the chat. Two people send at once. Everyone must see the same order.
  3. Found: Priya: server 40 of 100. Her phone is connected to one of 100 servers. The message must find it.
  4. Caught up: Phone off for 6 hours. Her laptop read everything. Her phone must still get every message, with no gaps.
  5. Read: Two ticks, then blue. Each tick must mean what it says, in a group of 1,000 too.
One message, start to finish. The system does this about 120,000 times a second at the evening peak.

Picture Nila on a train, in a group chat called “Saturday trip” with Priya and Ben. Priya asks where to meet. Nila types “ok”, the train enters a tunnel, and a clock icon sits beside her message. Priya is at home with her phone switched off and her laptop open. Ben is on a slow connection in a café. Three people share one conversation across five devices, and each device sits on a different network.

Interviewers like this problem because the first drawing takes five minutes. A phone opens a WebSocket to a chat server, the server saves the message and passes it on. The rest of the round is about how that drawing fails. It can show a message twice or in the wrong order. It can send a message to the wrong server, or never show it at all.

Here is the design in brief. Every phone holds one open connection to a connection server. A message goes up that connection to the chat service, which gives it the next number in its chat and stores it, in one database transaction, before it replies. A delivery worker then finds which connection server holds each recipient’s device, and hands the message to it. Every message also takes the next number in each member’s inbox, and each device keeps a cursor into that inbox. A phone that was off asks for everything after its cursor when it comes back.

The rest of this page is about the moments that design has to survive.

The first is a tunnel. Nila’s “ok” reaches the server and is stored. The server’s reply leaves a moment after the train loses signal, and never arrives. When the train comes out, her phone sends the message again. A careless server stores it a second time, and Priya sees “ok” twice.

The second is a phone left off. Priya’s phone is off for six hours while her laptop reads every message. The system records one thing: Priya has seen up to the latest message. The phone reconnects, asks for anything newer, and gets nothing. Six messages never appear on it.

What is the interviewer testing?

Most candidates draw the happy path in the first ten minutes. A phone opens a WebSocket to a chat server. The server writes the message to a database and pushes it to the recipient. That drawing is right, and a mid-level answer often stops there.

The interviewer then breaks it one piece at a time. The reply to the sender is lost. The recipient is connected to a different server, one of a hundred. Two people send in the same second. A phone is off for six hours. A group has 100,000 members. Every user wants to see who is online. A senior answer makes the send safe to retry, routes through a directory, orders each chat and catches up from a cursor. A staff answer also sizes the connection fleet, plans for a whole server’s phones reconnecting at once, changes how big groups are stored, and works out what online status costs.

Spend most of the deep-dive time on delivery: finding the recipient’s server, catching up after being offline, then groups. How to run a round has the time plan for a 45 to 60 minute round and a 15-minute screen.

What should you ask before drawing anything?

Four questions change the design. Ask them in the first two minutes. If the interviewer leaves one open, say your assumption out loud.

One-to-one only, or groups too? How big?
A chat between two people is the easy case. A group of 1,000 changes how a message is copied, and a channel of 100,000 changes it again. Assume one-to-one chats and groups of up to 1,000 members, with very large channels as a follow-up.
Does the server keep history, or only hold messages until they are delivered?
Some apps delete a message from the server once every device has it. Others keep every message, so a new laptop can scroll back years. Assume history is kept, because signing in on a new device must show old chats.
Can one person use several devices at once?
A phone and a laptop open at the same time means each message goes to several devices, and each can be offline at a different moment. Assume yes: a phone plus a few other devices.
Is it end-to-end encrypted?
If only the devices can read messages, the server cannot search them, preview them or scan them for abuse. Assume the server can read them for now, and treat encryption as a follow-up that changes several answers.

Functional requirements

On the board: Functional requirements
1. Send to a person or a group (up to 1,000)
2. Deliver in real time to online devices
3. Catch up after offline, on every device
4. Sent, delivered and read ticks
5. Online status and typing, best effort
out: calls, encryption, huge channels

Say it, don’t write it: Sending is easy. The hard part is every device ending up with the same messages, in the same order.

The users are people talking to people they know. They notice three things: a message that does not arrive, a message that arrives twice, and a message that arrives above the one it answers.

  1. Send a text message to one person, or to a group of up to 1,000 members.
  2. Deliver it within a second to every device of every recipient that is online.
  3. Give a device that was offline every message it missed, on every device the person owns, and keep history for scrolling back.
  4. Show whether a message was sent, delivered and read.
  5. Show who is online and who is typing, on a best-effort basis.

Out of scope

  • Voice and video calls
  • End-to-end encryption, beyond a section near the end
  • Channels with 100,000 members, beyond a section on how they differ
  • Search over message history
  • Photos and files, beyond a short section

Non-functional requirements

On the board: Non-functional requirements
• 100M users × 50 a day = 5B messages/day
• ≈ 58k/s average, 120k/s at the peak
• Online delivery in under 500 ms
• An acknowledged message is never lost
• One order per chat, the same on every device
• 40M devices online ÷ 400k = 100 servers

Say it, don’t write it: The number that sizes the servers is not messages a second. It is how many phones hold a connection open at once.

  • About 5 billion messages a day: about 58,000 a second on average and 120,000 at the evening peak.
  • A message to an online recipient appears within 500 milliseconds.
  • Once the sender sees one tick, the message is never lost.
  • Every chat has one order, and it is the same on every device.
  • A retry never shows a message twice.
  • About 40 million devices hold a connection open at the evening peak.

Two numbers are worth working out now, because they size the two busiest parts of the system. The first is messages. 100 million daily users sending 50 messages each is 5 billion messages a day. A day has 86,400 seconds, so that is about 58,000 a second on average. Evenings are busier, so plan for about twice that: 120,000 a second.

The second is connections. Say 40 million devices hold a connection open at the evening peak. Plan for 400,000 open connections on each connection server. 40 million ÷ 400,000 = 100 connection servers. That is a cautious figure: WhatsApp reported pushing one server past 2 million connections in 2012 (WhatsApp). The routing deep dive explains why a smaller number per server is the safer plan.

The other numbers appear in the deep dive that needs them. They are illustrative interview targets, not measurements of any particular app.

Core entities

On the board: Core entities
Message(chat, seq, client id, sender, body)
Chat(id, last seq, members)
Member(chat, user, read up to seq)
Inbox(user, n → chat, seq)
Device(user, id, cursor n)
Connection: device → server (soft)

Say it, don’t write it: Two numbers matter: seq is the chat’s order, and n is each person’s inbox order.

Follow Nila’s “ok” through the records. Before sending, her phone gives the message an ID of its own, c1. The chat service raises the chat’s last seq from 40 to 41 and stores the message as seq 41 of “Saturday trip”, with c1 beside it.

Then each member gets an inbox entry. Priya’s inbox takes its next number, #101, and points it at seq 41 of “Saturday trip”. Ben’s inbox gives the same message his own next number, #3,288. Priya’s phone and laptop each keep a cursor into her inbox. The cursor is the last number that device has stored with no gaps before it.

Two different orders are at work, and the design needs both. The chat’s seq answers “what order do these messages go in?” It is the same for everyone in the chat. The inbox number answers “what has this device not seen yet?” It is different for each person. A phone in 30 chats keeps one cursor, not 30.

The connection row is the other thing worth noticing. It records which connection server holds each device. It changes every time a phone reconnects, it can be lost without losing a message, and it is rebuilt when the phone comes back. Nothing else in the list may be lost.

API

On the board: API
WS /connect(token, device, cursor)
→ send {chat, client_id, body} → {seq}
← event {n, chat, seq, message}
→ ack {n} · read {chat, up_to_seq}
GET /inbox?after=n&limit=100
GET /chats/:id/messages?before=seq

Say it, don’t write it: Live traffic rides one socket. Catching up and scrolling back are plain requests that are safe to retry.

The phone opens one WebSocket when the app starts and keeps it open. Everything live travels over it, in both directions. Catching up and scrolling back are ordinary HTTP requests.

CallReturnsWhy it looks like this
send {chat, client_id, body}The message’s seq, sent only after it is storedThe same client_id always gets the same seq back, so a retry is safe
event {n, chat, seq, message}Pushed to every connected device of every membern is the message’s place in this person’s inbox; the device acks n once it has saved it
read {chat, up_to_seq}NothingOne read marker per member per chat, not one row per message
GET /inbox?after=n&limit=100Up to 100 inbox entries, and whether more remainHow a device catches up after being away
GET /chats/{id}/messages?before=seq&limit=50The 50 messages before seqScrolling back through history
POST /chats {members, request_id}The new chat’s IDThe same request_id returns the same chat, so a retry does not make two

Three fields exist for a reason. client_id is made on the phone before sending, so it survives a retry. The cursor on connect lets the server send what the device missed before it sends anything new. And ack {n} is how the server learns a device has saved a message, which is what the second tick reports.

Why one open socket, instead of asking the server for news every few seconds? Count the asking. 40 million devices, each asking every 5 seconds, is 8 million requests a second, and nearly all of them answer “nothing new”. That is about 67 times the peak message rate, spent on silence. An open socket costs nothing while nobody talks. Long polling and server-sent events work too, and Messenger’s early mobile app used MQTT for the same job, because it is light on bandwidth and battery (Meta engineering). A WebSocket carries bytes in order while the connection lives. Anything in flight when it drops is gone. No transport gives a delivery guarantee, so every promise on this page comes from acks, numbers and retries above it.

Step 1: send a message and store it

Start with the send. Nila’s phone sends the message up its WebSocket to a connection server. The connection server passes it to the chat service. The chat service stores it in the message store and replies with its seq. Only then does the phone show one tick.

The chat service stores the message in one database transaction. It locks the chat’s row, raises its last_seq by one, inserts the message with that number and its client_id, and commits. The first deep dive shows why the client_id check belongs inside that same transaction.

Now size the store. A text message with its sender, chat, seq and timestamps is about 200 bytes. 5 billion messages × 200 bytes is 1 TB a day, and 365 TB a year, before any copies. No single database holds that. So split the store across many database shards by chat ID, with MySQL behind a sharding layer such as Vitess. Every message of one chat lives on one shard. The transaction that numbers a message never has to cross machines, and scrolling back reads one chat’s messages in seq order from one place.

The interactive version of this example is available when JavaScript loads.

The chat service keeps no state of its own, so any instance can take any send. The one tick means exactly one thing: the message is stored.

Step 2: deliver it to an online recipient

Priya’s phone is connected to a different connection server from Nila’s. Something has to carry the stored message across. The chat service could do it itself before replying. Then Nila’s tick would wait for every recipient. A crash halfway through a group would also leave some members without the message.

So delivery happens after the reply, from a log. In the same transaction that stores the message, the chat service writes a row to an outbox table. A relay copies outbox rows into a Kafka topic, keyed by chat ID, so one chat’s messages stay in order in one partition. Writing to Kafka straight after the commit would be simpler. But if the service died between the two writes, the message would stay stored and never be delivered to anyone. The outbox row commits with the message, so the relay can always catch up.

Delivery workers read the topic. For each message they look up where each recipient’s devices are connected, in a connection directory kept in Redis: one row per device, saying which connection server holds it. They send the message to that server, which writes it down the device’s socket. The device saves it and acks. A worker records its Kafka offset only after the message’s inbox entries are written. If it dies, another worker starts again from a message whose work is unfinished.

The interactive version of this example is available when JavaScript loads.

This works while everyone is online and every lookup is right. Neither holds for long.

Step 3: catch up after being offline, on every device

A socket only reaches a device that is connected. So the delivery worker also writes the message into each member’s inbox, with that member’s next inbox number. That write is the promise. The socket only makes the promise quick.

Each device keeps a cursor into its owner’s inbox. When it connects, it sends the cursor. The server answers with everything after it, a page of 100 entries at a time, then switches to live events. A device away for a minute gets a short page. A device away for six hours gets a few.

A phone that is off cannot be reached at all. When the delivery worker finds no device of Priya’s online, it asks the push service to send a notification through Apple’s APNs or Google’s FCM. That wakes the phone, or at least shows her something, and the app catches up from its cursor when she opens it.

The interactive version of this example is available when JavaScript loads.

The inbox is the record of what each person should have. The socket and the push are only ways to get it there sooner.

Step 4: ticks, online status and typing

Three tick states tell the sender what happened. One tick means stored: it is the reply to the send. Two ticks mean delivered: a device of the recipient has saved the message and acked it. The ticks turn blue when the message is read. That comes from a separate number, the member’s read marker: “Priya has read up to seq 41 in this chat.” The read marker is one number per member per chat, moved forward as she reads. It is never a row per message.

Online status and typing are different in kind. They matter for a few seconds and then stop mattering. Each connection server reports the devices it holds to a presence store, as entries that expire after 60 seconds unless renewed. Typing goes only to people who have the chat open, and is never stored.

The interactive version of this example is available when JavaScript loads.

With a few thousand users this is already a working chat app. The deep dives take it to 120,000 messages a second and 40 million connected devices.

The server stored the message, but the reply never arrived. Does the retry send it twice?

Nila types “ok” as her train enters a tunnel. The phone sends it at 18:02:10 and shows a clock icon. The chat service stores it as seq 41 of “Saturday trip”, commits, and replies “stored, seq 41”. The reply leaves the server a moment after the train loses signal. It never arrives.

Twenty-one seconds later the train comes out and the phone reconnects. It finds a message still marked pending. It cannot tell whether the send died on the way in or the reply died on the way out. From the phone, both look the same: silence.

The phone has to send it again. A phone that gives up loses messages, and losing one is worse than anything else on this page. The obvious server stores whatever arrives. So the retry becomes seq 42, a second “ok”, and Priya sees Nila say “ok” twice.

Between friends, that is a small embarrassment. Now make the message “Sent you £50” in a family group, or “Yes, cancel it”. A duplicate can change what a conversation means.

The next idea is to spot the duplicate by its text. Drop a message if the same person sent the same words to the same chat in the last 60 seconds. The retry is dropped. Then Priya asks “North entrance at 6?” and Nila answers “ok”, 21 seconds after the retry. The server drops her real answer too. People repeat themselves, so text cannot tell a repeat from a retry.

The phone has to say which message it means. Before sending, it gives the message an ID of its own: 128 random bits, called c1 here. It saves c1 with the pending bubble and sends it with the text. The server stores c1 in the message row. A unique index on the chat and the client ID means c1 can be stored in that chat only once.

Replay the tunnel. The first send stores seq 41 with c1, and the reply is lost. The retry arrives carrying c1. The server finds c1 in the chat, sees seq 41, and replies “seq 41” again without storing anything. The phone swaps its pending bubble for the stored one, matching them by c1, so no second bubble appears. Priya’s question then gets an answer with a new ID, c2, which becomes seq 42. Each message has one row.

Now suppose the first send never arrived at all, and the phone resends on a new connection while an earlier resend is still in flight. Two copies of c1 reach the server at the same moment. If both looked up c1 before either stored it, both would find nothing. So each transaction first locks the chat’s row, and only then looks up c1. The first to get the lock finds nothing, stores seq 41 and commits. The second has been waiting on the lock. When it gets it, it finds c1 at seq 41 and replies 41 without storing anything. The unique index stays underneath as a backstop: if any path slips past, the database refuses the second row and that whole transaction rolls back. So the check runs inside the transaction that numbers the message, after the lock.

A design that keeps client IDs in a cache for ten minutes reopens the duplicate for any phone that retries after that. Phones sit in tunnels, and in drawers, for days. Here the ID is a column of the message row, so it lives as long as the message.

Delivery can repeat too. A delivery worker can crash after sending the message to Priya’s phone and before recording that it did. The Kafka log hands the message to another worker, and her phone receives it twice. Her phone saves each message under its number in her inbox, so the second copy lands on the first and nothing changes. The network delivers at least once. The IDs and numbers make each effect happen once (idempotency).

One more case comes from the same tunnel. Nila sends “ok” and then “see you at 6” before the signal returns. If the phone resends them in any order, the second can be stored first, and it will sit above the first on every screen. So the phone resends unsent messages oldest first. Each resend carries its own ID, so the server keeps what it already has and stores the rest in order.

The one tick the sender sees is the reply to the send. A tick shown as the message leaves the phone would promise something nobody knows yet. A tick shown after the commit promises one thing: the message is stored, once, at a number, and every device will get it. That is why the first tick waits for the commit.

The experiment replays the tunnel three ways. The tabs are a server that stores every arrival, one that drops repeated text, and one that checks the phone’s message ID.

The interactive version of this example is available when JavaScript loads.

The gap: The phone cannot tell a lost message from a lost reply, so it must retry, and the server must recognise the retry.

Option 1: Store every arrival

The server stores each message it receives.

Works when: Never on a phone network, where a lost reply is ordinary.

Breaks when: Every lost reply becomes a duplicate on every screen.

Option 2: Drop the same text for a minute

The server compares each message with the sender’s recent ones in that chat.

Works when: Only for a bot that never repeats itself on purpose.

Breaks when: A real “ok” sent twice in a minute is dropped, and nobody is told.

Option 3: A client message ID, checked in the storing transaction (start here)

The phone makes a random ID per message; a unique index on chat and ID turns a retry into a lookup of the stored seq.

Works when: Always.

Watch for: The phone must keep unsent messages with their IDs and resend them oldest first after a reconnect.

In the interview: Open with option 3, and say what the first tick means: stored, once. Use option 2 to show that text cannot tell a retry from a repeat. If the interviewer asks about exactly-once delivery, say the network delivers at least once and the IDs make the effect happen once.

Say this: A phone cannot tell a lost message from a lost reply, so it retries. Each message carries an ID the phone made, and a unique index on the chat and that ID turns a retry into a lookup that returns the same seq. The check runs in the transaction that stores the message, so two racing retries still make one row. Delivery can repeat too, and the phone saves by number, so nothing appears twice.

The interactive version of this example is available when JavaScript loads.

The code has four tabs: the storing transaction from this deep dive, the delivery worker from Step 2, the phone’s catch-up loop from the offline deep dive, and the directory cleanup from the next one.

Priya’s phone is connected to one of 100 servers. How does a message find the right one?

There are 100 connection servers, each holding about 400,000 phones. It is 17:10, and Priya is on her train home. Her phone holds an open connection to server 40. Nila’s phone is on server 12. Nila sends Priya a message. It is stored, and a delivery worker now holds it. The worker has to put it on a socket that only server 40 can write to. Nothing in the message says server 40.

The first idea is to ask. The worker sends the message to all 100 connection servers, and whichever holds Priya’s phone delivers it. It works, and it never misses. The cost is the problem. At the evening peak, 120,000 messages a second, each sent to 100 servers, is 12 million messages a second between the tiers. 99 of every 100 are wasted, and a group multiplies it again. Asking works with two servers and fails at a hundred.

The second idea is to compute the server from the user. Hash Priya’s user ID to server 40, and make every device of hers connect there. Now the worker needs no lookup. This breaks in ordinary places. Her phone and laptop must both reach server 40, wherever they are in the world. Consistent hashing keeps the moves small: adding server 101 moves about one user in a hundred. But every move cuts a live connection, and a dead server still sends its 400,000 users somewhere new at once. The load balancer can no longer send a phone to the nearest or the least busy server.

So write down where each device is. When Priya’s phone connects to server 40, the server writes one row to a directory: phone → server 40. It renews the row every minute, with a two-minute expiry, so a row whose server has died disappears on its own. The delivery worker asks the directory for all of Priya’s devices in one request. It gets server 40 for the phone and server 71 for the laptop, and sends one copy to each.

A Redis cluster suits the directory. 40 million small rows fit in memory, and a lookup takes well under a millisecond. Refreshing 40 million rows once a minute is about 667,000 small writes a second, spread across the cluster.

A few minutes earlier, her phone was on server 27. Her train passed under a bridge, the phone lost signal for a second, and it reconnected, this time to server 40. Server 40 wrote phone → server 40. A reconnect is the ordinary way a directory goes wrong.

Server 27 did not know yet. Its socket for Priya was dead, but a connection with no traffic can take 30 seconds or more to be noticed. When server 27 notices, it cleans up: it deletes Priya’s phone from the directory. The row it deletes is server 40’s. Her phone is connected and working, and the directory now says she is offline. Until server 40 next renews its row, up to a minute later, her messages go to push notifications and wait for her to open the app. A plain renewal can also go wrong the other way. Server 27’s last renewal, sent before it noticed the dead socket, can write its own stale row over server 40’s.

The fix is to number the connections. Each time the phone connects, it takes the next connection number for that device from Redis, with one INCR: 7 on server 27, then 8 on server 40. The row stores both: server 40, connection 8. A server may delete or renew a row only if the row still holds its own connection number, and a new connection may overwrite only a smaller number. Each of those checks and writes in one atomic step, a short Lua script run inside Redis. Server 27 asks to delete connection 7, finds 8, and leaves the row alone. Its last renewal before it noticed the dead socket found 8 too, and changed nothing.

The directory can still be wrong for a moment, for example in the two minutes after a server crashes. That is safe, and it is worth saying why in the interview. The directory only makes delivery fast. The inbox from Step 3 makes it certain. A message sent to a server that no longer holds the phone is dropped there. The phone notices the next time any message reaches it, because its inbox number jumps, and it fetches what it skipped. It also catches up every time the app comes to the front. A failed send counts as no device online, so a phone that is really off still gets its push. With those rules, no routing mistake can lose a message. It can only delay one.

The experiment follows one message to Priya. The tabs are asking every server, a plain directory, and a directory whose rows carry connection numbers.

The interactive version of this example is available when JavaScript loads.

Now the connection servers themselves. WhatsApp pushed one server past 2 million connections in 2012 (WhatsApp), and this design plans for 400,000. The reason is what happens when a server dies: every phone on it reconnects at once. 400,000 phones retrying within the same two seconds is 200,000 new connections a second. Each one needs an encrypted handshake, a token check, a directory write and a catch-up read of its inbox. The other 99 servers and the inbox store take that burst together. With 2 million phones on the dead server, the burst is five times larger.

Two changes turn the burst into a slope. Phones wait a random time before reconnecting, spread over 60 seconds, so 400,000 ÷ 60 is about 6,700 a second. And servers refuse new connections above a set rate, with a “try again in a few seconds” answer. An old app that ignores the random wait must not be able to cause the storm on its own. A deploy is the same event, planned: a server stops taking new connections and closes its old ones a few thousand at a time.

An open connection needs a socket, its encryption state and small buffers, a few tens of kilobytes. 400,000 of them fit comfortably in one server’s memory. The limits you meet first are how many phones you can afford to lose at once, and the work they bring back when they return.

The gap: A stored message must reach a socket that only one of 100 connection servers can write to.

Option 1: Ask every server

The worker sends each message to all the connection servers.

Works when: A handful of servers, as in a demo.

Breaks when: At 100 servers it is 12 million messages a second, 99 of every 100 wasted.

Option 2: Hash the user to a server

The user’s ID decides which server all their devices must connect to.

Works when: One device per user, one region, and a fleet that rarely changes.

Breaks when: A dead or added server moves users, and phones cannot use the nearest server.

Option 3: A directory of device → server, with connection numbers (start here)

Each server writes a row when a device connects and deletes it only if its connection number still matches.

Works when: Always, for one-to-one chats and groups up to the limit.

Watch for: A row can be stale for two minutes after a crash; the inbox covers whatever the socket missed.

Option 4: Publish and subscribe

Each connection server subscribes to the users or channels its devices need; workers publish once.

Works when: Very large channels, where many servers want the same stream.

Watch for: A message published while nobody is subscribed is gone, so the inbox still carries the promise.

In the interview: Open with option 3 and derive the fleet: 40 million devices at 400,000 each is 100 servers. Use option 1 to show why routing needs a lookup, and bring up the stale row and its connection number before the interviewer does. Keep option 4 for very large channels.

Say this: Each device holds a socket to one of about 100 connection servers, and each server writes device → server into a Redis directory with a connection number. A delivery worker looks up all of a user’s devices and sends one copy to each server. A server deletes a row only if its connection number still matches, so a slow cleanup cannot erase a reconnect. A wrong row only delays a message, because every device catches up from its inbox.

Two people send at almost the same moment. Does everyone see the same order?

In the “Saturday trip” group, Ben asks “North or south?” at 18:00:00. Nila answers “North!” a second and a half later. Her phone’s clock is three seconds slow, which is common: a phone sets its clock from the network, and one that has been in airplane mode drifts. Priya is reading the group on her laptop at home.

The first idea is to stamp each message with the time on the sender’s phone and sort by it. Nila’s reply carries 17:59:58.5, because her clock is slow. Every phone sorts it above Ben’s question. All three screens agree, and all three show an answer above its question. One wrong clock reorders the chat for everyone, and nothing in the system can notice.

The next idea is to trust nobody’s clock and show messages in the order they arrive. Ben’s screen shows his question, then the reply, and so does Nila’s. Priya’s laptop loses its Wi-Fi for a second between the two messages, and reconnects. Ben’s question went to its old connection and died with it. Nila’s reply arrives on the new connection at 18:00:01.8, and the question comes back from her inbox at 18:00:02.3. Her screen shows the answer above the question, and the three screens now disagree. Stamping each message with the server’s clock helps less than it seems. Two instances of the chat service have two clocks, and two messages a few milliseconds apart can swap.

The chat needs a turn for each message, and a clock cannot give one. Give every message the next number in its own chat, from one counter that only moves forward. Ben’s question is stored at 18:00:00.3 and takes seq 73. Nila’s reply is stored at 18:00:01.7 and takes seq 74. The number is the order. Every phone sorts by it, and no clock is involved.

The database hands out the number, inside the transaction from Step 1. The chat’s row holds last_seq, and storing a message raises it by one. If Ben and Nila send in the same millisecond, the row lock lets one transaction go first. The other waits a moment and takes the next number.

Even a busy group sends only a few messages a second. One row can take far more than that, so one counter per chat is enough. There are millions of chats, each with its own counter, on shards chosen by chat ID. There is no global order. A person reads one chat at a time, so no screen needs one chat’s messages ordered against another chat’s.

The number does a second job on the receiving phone. Priya’s laptop gets seq 74 before seq 73, because of the reconnect. Numbers in a chat have no holes, so her laptop knows seq 73 exists and has not arrived. It holds seq 74 back for a moment, and fetches seq 73 if it does not arrive within a second or two. Every screen settles on the question, then the answer. For this to hold, a deleted message keeps its number, marked deleted.

The experiment sends both messages to three phones. The tabs are sorting by the sender’s clock, showing messages in arrival order, and numbering them in the chat.

The interactive version of this example is available when JavaScript loads.

A common alternative is an ID that sorts by time, such as Twitter’s Snowflake: 41 bits of milliseconds, 10 bits naming the machine that made it, and 12 bits of sequence (Snowflake). Discord gives every message such an ID, and stores each channel’s messages in time buckets ordered by it (Discord). It needs no counter and no lock, which helps when a channel’s writes land on many machines.

The price is the problem this deep dive started with. Two machines stamp two messages with two clocks. Snowflake only promised its IDs would sort correctly to within about a second. In a lively group, two messages sent within the same second can swap. A chat that must never show an answer above its question needs a counter per chat. A huge channel that can accept a rare swap can use time-ordered IDs and drop the lock.

The phone still shows a time beside each message. It is the server’s time of storing, for display only. It never decides the order.

The gap: Messages from different people, on different clocks and links, must appear in one order on every screen.

Option 1: Sort by the sender’s clock

Each phone stamps its message; every screen sorts by the stamp.

Works when: Never for ordering, because phone clocks drift by seconds.

Breaks when: One slow clock puts an answer above its question on every screen.

Option 2: Show in arrival order

Each screen shows messages as they reach it.

Works when: One sender, or messages minutes apart.

Breaks when: Two screens on different links show two different orders.

Option 3: A number per chat, from a counter in the storing transaction (start here)

The chat’s row holds last_seq; storing a message takes the next number under the row lock.

Works when: Always, for chats where an answer must never sit above its question.

Watch for: One counter serialises a chat’s writes: fine at a few messages a second, a limit for a huge channel.

Option 4: Time-ordered IDs, such as Snowflake

A 64-bit ID with milliseconds in its top bits, made on any machine without a lock.

Works when: Huge channels whose writes land on many machines.

Watch for: Messages sent within a second of each other can swap, which the product must accept.

In the interview: Open with option 3 and say plainly that the number is the order. Use option 1 to show why a clock cannot decide it. If the interviewer asks about a huge channel, bring up option 4 and say what it gives up.

Say this: Phone clocks drift and links reorder, so neither can decide the order. Each chat has a counter, and the transaction that stores a message takes the next number under the row lock. Every screen sorts by that number, and a phone that gets seq 74 before seq 73 waits for 73. There is no global order, because nobody reads two chats as one list.

Priya’s phone was off for six hours while her laptop read everything. What does the phone get?

Recall the inbox from Step 3. Every message Priya receives, from any chat, takes the next number in her inbox: #1, #2, #3, with no gaps. Those numbers are hers alone, separate from each chat’s seq.

At 18:00 Priya switches her phone off and leaves it charging. Her laptop stays open at home. Over the evening, messages from several chats arrive and take numbers #101 to #106 in her inbox. The laptop shows each one live, and she reads them there. At 00:10 she switches the phone back on, and it reconnects.

The simplest record of what she has seen is one cursor for the account: “Priya is up to #106.” The laptop moves it forward as it saves each message. The phone reconnects and asks for everything after #106. The answer is empty. Six messages never appear on the phone, including the one about a changed meeting point. The laptop spoke for both devices.

So each device keeps its own cursor into Priya’s inbox. The laptop is at #106 and the phone at #100. The phone reconnects and asks for everything after #100. Catch-up comes in pages, 100 entries at a time in production and three in the experiment below. So the first page is #101 to #103.

Now a new message, #107, arrives live on the reconnected socket before the phone asks for the next page. A simple rule says the cursor is the highest number the device holds. The phone holds #107, so its cursor becomes #107. The next page asks for everything after #107 and gets nothing. #104 to #106 are skipped for good. Nothing notices, because a skipped number looks exactly like a number that was never sent.

The rule that works moves the cursor only through an unbroken run. The phone saves #107 when it arrives, and its cursor stays at #103, because #104 is missing. The next page asks for everything after #103 and gets #104 to #106. Now the run is unbroken up to #107, and the cursor moves there in one step.

The rule is only safe if inbox numbers have no holes. So the delivery worker takes Priya’s next number and writes the entry in one transaction on her inbox shard, the same way a chat numbers its messages. A crash cannot take a number and leave it empty. A unique key on the member, the chat and the seq means a redelivered message finds its entry already there, instead of taking a second number. So a missing number always means “not here yet”, never “never existed”.

Two details on the phone matter too. The phone saves a message to its own database before it moves the cursor or sends its ack. Otherwise a message drawn on screen and lost in a crash would count as delivered. And every write on the phone is keyed by inbox number, so a message that arrives both live and in a page is saved once.

That night her laptop was online, so the directory always had one of her devices. Had she closed the laptop too, the delivery worker would have found none of her devices in the directory. Then it sends a push notification through Apple’s APNs or Google’s FCM. Both cap a notification at 4 KB, 4,096 bytes (Apple, Firebase). That fits a sender’s name and a preview, never a backlog. So the push is a nudge. Her phone shows “Nila: see you at 6”. When she opens the app, it connects and catches up from its cursor like any other reconnect.

The phone’s operating system can delay or drop a push, so nothing depends on one arriving. Several pushes for one chat collapse into one notification. A chat she has muted sends none.

This gives the second tick an exact meaning. It means a device of the recipient has saved the message and acked its number. In a group, each member keeps a delivered marker beside the read marker: the highest seq one of their devices has saved. The sender sees two ticks once every member’s delivered marker has passed the message, and blue ticks once every read marker has. The message’s info screen lists each person.

The experiment follows Priya’s phone through the night. The tabs are one cursor for the account, a cursor that jumps to the highest number held, and a cursor per device that moves only without gaps.

The interactive version of this example is available when JavaScript loads.

A cursor per chat would work too, at a cost. Say Priya is in 60 chats. A phone coming back would have to ask all 60 for their news, and most would say nothing. The inbox answers in one request: here is everything, in the order it reached you. It also orders her chat list, most recent first. Each chat’s unread count comes from two numbers: the chat’s latest seq and her read marker.

The inbox keeps entries for as long as a device might plausibly come back, say 30 days. A device away longer than that does not replay a month. It fetches a fresh chat list and loads each chat’s recent history when it is opened.

The gap: Each device must end with every message, although devices go offline at different times and live events race catch-up pages.

Option 1: One cursor per account

The account records the last inbox number any device saved.

Works when: One device per user, ever.

Breaks when: A laptop that reads messages moves the cursor past everything the phone missed.

Option 2: A cursor per device, set to the highest number held

Each device asks for everything after the highest number it has.

Works when: Only if events arrive in order, which a reconnect breaks.

Breaks when: A live message that overtakes a catch-up page moves the cursor past the gap, and the gap is never fetched.

Option 3: A cursor per device that moves only through an unbroken run (start here)

Each device saves every event by its inbox number and advances the cursor only while the next number is present.

Works when: Always.

Watch for: Inbox numbers must have no holes, so a deleted message keeps its number as a marker.

In the interview: Open with option 3 and say why it is safe: inbox numbers have no holes, so a missing number always means not here yet. Then add push as a nudge, and define the second tick as a device saving the message.

Say this: Every message takes the next number in each recipient’s inbox, and each device keeps its own cursor. On reconnect the device asks for everything after its cursor, in pages. It saves live events as they come but moves the cursor only through an unbroken run. If no device is online, a push through APNs or FCM wakes the phone to catch up; it is capped at 4 KB, so it is a nudge, not the delivery.

A message goes to a group of 1,000, or a channel of 100,000. Who does the work?

Everything so far wrote one inbox entry per member. For the five people in “Saturday trip”, that is five small writes per message, and nobody would notice. Now take a company group of 1,000 members that gets about one message a second through the working day. And take a community channel of 100,000 members that gets five messages a second when something is happening.

Writing to every inbox costs one write per member per message. The company group costs 1,000 inbox writes a second. That is heavy but steady, and every member’s inbox stays exact. The community channel costs 100,000 × 5 = 500,000 inbox writes a second. The whole platform peaks at 120,000 messages a second. This one channel would write about four times as many inbox entries as the entire platform sends messages. Most of its 100,000 members will not even open it today.

Live delivery is the second cost. Say 12,000 of the channel’s members have a device online. Sending each device its own copy from the delivery workers is 12,000 × 5 = 60,000 copies a second, each looked up in the directory.

So a big channel stops writing to inboxes. It keeps only its own log: its messages numbered by seq, as before. Members get no inbox entry per message. When a member opens the channel, each device asks for everything after the highest seq it holds for that channel. It is the same unbroken-run rule as the inbox, kept per device. One message is one append, whatever the size. The member’s read marker still gives the unread count, against the channel’s latest seq.

Live delivery changes the same way. When a phone opens the channel, its connection server subscribes to it. The delivery worker sends each new message once to each connection server with a subscriber, at most 100 copies. Each server hands it to the phones it holds. Five messages a second becomes 500 copies a second between the tiers, instead of 60,000. The phones still receive 60,000 copies between them, because every screen needs its own. Slack works this way. Its gateway servers hold users’ WebSocket connections and channel subscriptions. Each channel’s messages go out from one channel server to every gateway subscribed to it (Slack engineering).

Somewhere between these two sizes, a group should become a channel. Below the line, inboxes are simple. They give each member things a channel has to rebuild: a push notification per message, an exact place in their inbox, a chat list that re-sorts itself. Above it, those become choices. A 100,000-member channel sends no push per message, only for mentions and replies. This design uses inboxes up to 1,000 members, the limit from Clarify first, and treats anything bigger as a channel that members read from. The limit is a product decision, and these numbers are what it rests on.

Read receipts grow with the group too. In a group of 1,000, a message is read by up to 1,000 people, and each read moves a read marker. Telling the sender about each read would be up to 1,000 receipts per message. So a phone moves its read marker every few seconds while the chat is open, and once more when the chat closes, never once per message. The sender sees a count, “read by 312”, worked out when they open the message’s info screen. Big channels show no read receipts at all.

A big channel also concentrates reads. When a match ends, thousands of phones open the same channel within seconds and ask for the same last 50 messages. Discord hit exactly this: busy channels made “hot partitions” in its message store. It put a layer of data services in front of the database. When many users ask for the same rows at the same moment, the database is queried once (Discord). The recent messages of a busy channel are also worth keeping in memory, because every phone wants the same ones.

The experiment posts one message to three groups. The tabs choose the group, and whether the message is written to every inbox or appended to one log that members read.

The interactive version of this example is available when JavaScript loads.

The gap: One message must reach every member, and the cost of copying it grows with the group.

Option 1: Write to every member’s inbox (start here)

One inbox entry per member per message, and one copy per online device.

Works when: Groups up to about 1,000 members, where every member wants a push and an exact inbox.

Watch for: A 100,000-member channel at 5 messages a second would be 500,000 writes a second, which is why channels switch.

Option 2: One log per channel that members read

One append per message; each member keeps a read number; connection servers subscribe and get one copy each.

Works when: Channels above the group limit, where most members read later.

Watch for: Pushes per message and exact inboxes are gone, so notify only mentions and replies.

In the interview: Open with option 1 for groups up to the limit, and give its cost: 1,000 members at one message a second is 1,000 writes a second. When the interviewer grows the group, do the arithmetic for 100,000 and switch to option 2. Say what option 2 gives up.

Say this: For groups up to 1,000 members, the delivery worker writes an entry in each member’s inbox and sends a copy to each online device. A 100,000-member channel at five messages a second would be 500,000 inbox writes a second, so a big channel keeps one log, each member keeps a read number, and each connection server subscribes and gets one copy. Read receipts become counts, and pushes go only to mentions.

Nila opens the app. Who needs to know she is online?

Nila has 400 contacts, and 120 of them are online right now. She opens the app on the train, and the dot beside her name should turn green. The question is who should be told.

The obvious answer is everyone who might see it: tell each online contact. That is 120 updates for one change of status, and every user does this many times a day. Each user changes status about 20 times a day, going online 10 times and offline 10 times as they open and close the app. 100 million users × 20 changes × 120 contacts is 240 billion updates a day. A day has 86,400 seconds, so that is about 2.8 million updates a second on average. The messages average about 58,000 a second, so the green dots would cost about 48 times as much as the messages. The green dots would cost far more than the messages.

Of Nila’s 120 online contacts, three have her chat open right now. Nobody else is looking at her name. So tell only those three.

When a phone opens a chat, its connection server subscribes to the status of the people in it. When the chat closes, it unsubscribes. Nila’s change reaches three people. A phone that opens her chat later reads her status once, then gets changes while it stays open. The platform sends about 2 billion changes × 3 ÷ 86,400, which is about 69,000 updates a second on average. That is about the same as the messages, instead of 48 times more.

The system learns Nila is online from her connection server, which knows her socket is open. It writes “online” to the presence store with a 60-second expiry, and renews it with each heartbeat while the socket lives. If her phone dies in a tunnel, nothing says goodbye. The entry expires, and she shows as offline. “Last seen 18:02” needs a stored time, because the expired entry is gone. So the connection server writes a last-seen time when a socket closes, including a socket it closes itself after the heartbeats stop. That is one small write per session. Renewing 40 million online entries once a minute is about 667,000 small writes a second, the same load as the directory. A design can keep both in one row. A connection number, as in the directory, stops an old server’s late cleanup from marking a newer connection offline.

In a group, the header can say “Ben, Priya online” for five people. For 1,000 it shows a count, or nothing.

Typing indicators are stricter still. The phone sends “typing” at most once every few seconds, only to people with the chat open, and nothing stores it. If one is lost, the dots vanish a few seconds later, which is correct. Under load, presence and typing are the first traffic to drop, because losing them costs nothing that matters.

Privacy settings sit on top. A user can hide their last-seen time and their read receipts. A common rule is that a user who hides theirs cannot see anyone else’s, so the setting cannot be used to watch without being watched.

The experiment turns Nila’s dot green. The tabs are telling every online contact, and telling only the people with her chat open.

The interactive version of this example is available when JavaScript loads.

The gap: A change of status is worth sending only to someone who is looking at it.

Option 1: Tell every online contact

Each change of status goes to all of the user’s online contacts.

Works when: Small apps where people have a few dozen contacts.

Breaks when: 120 updates per change is 2.8 million a second, about 48 times the messages.

Option 2: Tell only who has the chat open (start here)

Connection servers subscribe to the status of people in open chats; everyone else reads it when they open a chat.

Works when: Always.

Watch for: Status can be up to 60 seconds late after a phone dies, until its entry expires.

Option 3: Show no online status

Show only “last seen”, read when a chat is opened.

Works when: Privacy-first products, or huge channels.

Watch for: Users lose the green dot, which is a product call more than an engineering one.

In the interview: Open with option 2, but do the multiplication for option 1 first, because the number makes the case. Say that presence and typing expire instead of being deleted, and that they are dropped first under load.

Say this: Telling every online contact is 120 updates per change, about 2.8 million a second, about 48 times the messages. So only people with the chat open are told, through subscriptions on their connection servers, and everyone else reads the status when they open the chat. Presence is written with a 60-second expiry and renewed by heartbeats, so a dead phone goes offline by itself. Typing is never stored.

If they push: how does a photo travel?

A photo never goes through the chat transaction or a connection server. Nila’s phone first asks the chat service for an upload address, a pre-signed URL for object storage such as S3, and uploads the photo there directly. Then it sends an ordinary message carrying the photo’s key, its size and a tiny blurred preview of a few hundred bytes. Recipients see the preview at once and download the full photo from a CDN, through a short-lived signed link issued only to members of the chat. A 5 MB photo sent to a group of 1,000 is stored once. An upload that is never sent is deleted after a day.

If they push: a member is removed while a message is in flight

Treat the removal as an event in the chat’s own sequence, numbered like a message: “Priya removed Tom” is seq 57. A message goes to the members as of its number. Seq 56 goes to Tom and seq 58 does not. The order the delivery workers process them in makes no difference, because each worker reads the member list at the message’s number. Tom’s connection server drops his subscription to the chat. What Tom already has stays on his phone. Removal stops future messages; it cannot recall past ones.

If they push: what changes with end-to-end encryption?

With end-to-end encryption, only the devices can read messages, and the server stores and forwards ciphertext. WhatsApp’s design shows what that costs (WhatsApp encryption overview). A message to a person with several devices is encrypted once per device, and the sending phone must name every destination device when it sends. In a group, each sender first hands a “Sender Key” to every member device over the one-to-one sessions. After that, each message is one ciphertext that the server copies to the group. When a member leaves, everyone clears their sender keys and starts again.

The server loses things it used to do: search, previews in push notifications, and scanning content for abuse. A new device cannot read old history unless it is transferred from another device or restored from a backup. The machinery on this page does not change: client IDs, seq numbers, inboxes and cursors all work on sealed envelopes.

If they push: users in different countries

Connection servers go close to users, in several regions, so a phone’s socket and its handshake stay short. Each chat’s messages live in one home region, chosen by where most of its members are, so the transaction that numbers a message stays in one place. A message between two countries crosses the ocean once, from the sender’s region to the chat’s home, and its delivery crosses back once. Slack reports delivering messages across the world within 500 milliseconds, with gateway servers in several regions (Slack engineering).

Walk one message through the final design

Nila types “ok”. Her phone gives it client ID c1, saves it as pending and sends it up its socket to connection server 12. The chat service opens a transaction on the shard that owns “Saturday trip”. It locks the chat’s row, finds that c1 is new, raises last_seq to 41, stores the message and an outbox row, and commits. It replies “seq 41”, and one tick appears.

The relay copies the outbox row into Kafka, in the chat’s partition. A delivery worker reads it and writes an entry in each member’s inbox: #101 for Priya. It asks the directory where her devices are: the laptop on server 71, connection 3, and no row for the phone, which is off. It sends the message to server 71, whose socket carries it to the laptop. The laptop saves it and acks #101. Ben’s phone does the same a moment later, and Nila sees two ticks. No push is needed, because one of Priya’s devices is online.

At 00:10 the phone connects to server 40 with cursor #100. It gets its pages, saves #101 to #107, and moves its cursor only through the unbroken run.

The interactive version of this example is available when JavaScript loads.

RequirementWhere it is metThe trade-off
FR1 send to a person or a groupChat service; one transaction numbers and stores the message, checks its client IDOne counter per chat serialises that chat’s writes
FR2 deliver in real timeOutbox, Kafka, delivery workers, a Redis directory with connection numbersA stale row delays a message until the device catches up
FR3 catch up on every deviceAn inbox per person, a cursor per device, push to wake a phoneAn inbox write per member per message, up to 1,000 members
FR4 ticksStored on commit; delivered and read markers per memberGroup receipts are counts, and big channels have none
FR5 online and typingPresence entries that expire in 60 seconds; subscriptions for open chats onlyStatus can be up to a minute late

How does the answer change for WhatsApp, Messenger, Slack or Discord?

Interview variantWhat carries overWhat changes
Design WhatsApp, or SignalEverything on this pageEnd-to-end encryption moves to the centre: a copy per device, Sender Keys for groups, and the server may delete messages once delivered
Design Facebook MessengerEverything on this pageHistory kept forever, on every device, drives the inbox and its retention
Design SlackConnection servers, channel logs and subscriptionsChannels and workspaces are the main unit; threads and search over history get time
Design DiscordBig channels read from one log, and hot channel readsCommunities of hundreds of thousands, storage by channel and time, and voice
Design live comments for a streamFan-out to connection servers through subscriptionsViewers only read: no inboxes, no receipts, and late comments can be dropped
Design a notification servicePush through APNs and FCM, devices and retriesOne-way, with no conversation order and no catch-up. See the notification service breakdown

What should an answer reach at each level?

LevelWhat the answer shows
Intern or mid-levelDraws phone, WebSocket, chat server, database and recipient. Explains why an open socket beats polling. Stores messages by chat.
SeniorMakes the send safe to retry with a client ID. Routes through a directory. Numbers messages per chat. Catches up each device from its own cursor, with push as a nudge. Defines each tick.
StaffSizes the connection fleet and plans for a server’s phones reconnecting at once. Handles the stale directory row. Moves big channels to one log with subscriptions. Batches read receipts. Works out what online status costs.
PrincipalChooses retention and encryption with the product, and names what each takes away: search, previews, moderation, history on a new device. Plans regions, the group limit, and what degrades first under load.

Test yourself with the quiz, then pick another problem from the System Design interview breakdowns.

By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.