Design Facebook Messenger - 1:1 chats and small groups for 500 million daily users, where every member sees the same messages in the same order and a message that was confirmed is never lost. A chat feels live because of sockets, but it is correct because of a log. The senior signal is committing a numbered message first and delivering second, so that a dead socket, a wrong "online" flag or a lost answer costs a moment of freshness and never a message.
Written by a Staff+ Engineer and an Engineering Manager
12+ years of experience in distributed systems and real-time messaging. Tech lead for large-scale chat applications serving billions of users. Over 12 years of industry experience with 6 years in engineering leadership, building and scaling tech infrastructure teams that deliver end-to-end large-scale distributed systems.
Finished this lesson?
Sign in to save your progress across devices.
Tip: use ← and → to move between lessons.
Was this lesson helpful?
Rehearse this exact question with the author
45-minute mock with a Staff+ engineer who interviews at your target company. Premium members save $20.
What to Design?
Could you answer these today? Tick what you already know.
The happy path is quick to draw: a phone sends a message, a server stores it, a socket carries it to the other phone. The interview is decided by four questions about what happens when clocks differ, answers get lost and sockets die. Each one is a deep dive later on this page, with three designs side by side: the one that sounds right, a better one, and the one that holds.
Swipe to see all columns
| The four questions, and the answer that sounds right | |||
|---|---|---|---|
| # | The interviewer asks | The answer that sounds right | What it misses |
| DD1 | Two people send in the same moment. Who is first, on every screen? | Sort by time stamp | Clocks differ, and time stamps have holes. One counter per conversation, handed out by one owner, gives one order and shows a missing message |
| DD2 | The phone never got the answer and sends again. How many messages does the other side see? | The server filters duplicates for a minute | |
The same three habits answer all four:
Do not spend your questions on emoji and stickers. Spend them on what the chat promises.
Swipe to see all columns
| Scope Decisions | ||
|---|---|---|
| Question | Agreed answer | Why it matters |
| How big is a group? | At most 250 members. Most chats have 2 to 20 | One message goes to at most 249 people. No broadcast design is needed |
| What order do people see? | Everyone in a chat sees the same order. Order between two chats does not matter | Order is decided per conversation, not for the whole system (DD1) |
| When is a message "sent"? | When it is stored durably. The sender is told within 200 ms | |
Out of scope (say this out loud): voice and video calls, end-to-end encryption and its keys, editing and unsending, disappearing messages, full-text search, public channels with thousands of members, friend suggestions and ads.
FR1 — Send a message. A member sends text to a 1:1 chat or a group. Every member sees all messages of the chat in the same order.
FR2 — Deliver it live. A member whose app is open gets the message within a second over a WebSocket, a connection that stays open so the server can send without being asked. A member whose app is closed gets a push notification.
FR3 — Show the history. After a reconnect, an app restart or a login on a new device, the app loads the messages in order. A new group member can read everything that was said before.
FR4 — Send a photo. The bytes of the photo do not travel through the chat servers.
FR5 — Read marks and presence. The app shows how far each member has read, and roughly who is online.
The key principle behind all five
Swipe to see all columns
| Five facts and the conclusions they do not supportRead each row as: the fact on the left does not, by itself, imply the claim in the middle. | ||
|---|---|---|
| Fact | Does not imply | Why the gap exists |
| The phone sent the request | The message is stored | The request or the answer can be lost. Only a 201 with a sequence number says "stored" |
NFR1 — Nothing confirmed is lost. A message that got its 201 survives the loss of a server, a socket or a cache. Sending and reading history are available 99.95% of the time.
NFR2 — One order. Inside a conversation, every member and every device sees the same order.
NFR3 — Fast. The sender has the 201 within 200 ms (p95, meaning 95 of 100 sends). A connected member has the message within 1 second (p95).
NFR4 — No duplicates. A retry, a reconnect or a slow worker never makes a message appear twice.
NFR5 — Scale. 500 million daily users, 50 million open connections, 3 million messages a second at peak. The work for one send has a fixed upper bound.
| Capacity Thought Experiment | |
|---|---|
| Parameter | Value |
| Daily users | 500 million |
| Messages | 100 per user per day: 50 billion a day |
| Message rate | About 580,000 a second on average, 3 million a second at peak |
| One message row | About 1 KB: 50 TB a day |
| Connected devices | 50 million at peak, 10% of the daily users |
The number that identifies the real system is the gap between the whole and one chat:
all chats together 580,000 messages a second
one chat a few messages a second, at most
one message about 1 KB, to at most 249 people
photos 20 times more bytes than all text
Messenger is not one big ordering problem. It is a very small ordering problem, solved 580,000 times a second, side by side. And the photos are a storage problem that should never touch the chat path. Every number above is an illustrative assumption.
Interviewer signal: candidates who start with "millions of WebSockets" have started with the easy half. Candidates who say "first I decide where a message becomes true and how it gets its place in the order, then I make delivery a best-effort layer on top" have found the system.
Three ideas shape everything:
A message exists when it is committed to a durable log with a number. From then on, three things try to make the chat feel live: the socket, the record of who is online, the notification. Each of them can fail without anyone noticing. So none of them is ever trusted: when a phone is in doubt, it reads the log again.
Clocks differ between phones and between servers. A counter does not. Each conversation has its own counter, the sequence (short: seq), and exactly one server at a time is allowed to raise it. The numbers have no holes, so a phone that holds 1041 and receives 1043 knows that it is missing one.
Phones retry, workers repeat, two devices report the same thing. So every write is built to give the same result the second time: a send carries an id that the phone made up, and a read mark can only move forward.
The core recognition
This is a durable log per conversation, with a best-effort delivery layer on top. The log needs one owner, a counter and an id per send. The delivery layer needs sockets, a lookup table that may be wrong, and a way to notify. The two meet in one rule: when the phone is unsure, it asks the log.
| Design Decisions | |
|---|---|
| Design choice | Reason |
| One owner node per conversation | One place hands out the sequence, so there is one order |
| A sequence without holes | Sorting is trivial, and a missing message is visible |
Two tables carry the design:
messagesandread_cursors. The fields to explain areseq, which gives every message its place, andclient_message_id, which makes a retry harmless.
One row per message. All rows of one conversation are stored together, sorted by seq.
Swipe to see all columns
| messages | ||
|---|---|---|
| Field | Type | Comment |
conversation_id | STRING | Key, part 1. For example conv_77. All messages of a chat live in one partition |
seq | BIGINT | Key, part 2. The place of the message in the chat: 1040, 1041, 1042. No holes |
One row per person and conversation, shared by all devices of that person.
Swipe to see all columns
| read_cursors | ||
|---|---|---|
| Field | Type | Comment |
user_id, conversation_id | STRING | Key |
last_read_seq | BIGINT | The highest seq this person has read. It only moves forward (DD4) |
Swipe to see all columns
| Supporting records | ||
|---|---|---|
| Record | What it holds | Why it exists |
conversations | conversation_id, type (direct or group), title | The chat itself. A 1:1 chat is a conversation with two members |
conversation_members | (conversation_id, user_id | |
Swipe to see all columns
| Storage | ||
|---|---|---|
| Store | Data | Consistency |
| Wide-column store (Cassandra) | messages, message_ids, read_cursors | The source of truth. 2 of 3 copies confirm a write. A write can carry a condition |
| PostgreSQL | conversations, conversation_members, attachments | Small rows, changed rarely, in transactions |
| Redis | Session keys | Disposable. A lost key means one notification and one catch-up |
A wide-column store keeps all rows with the same partition key together and sorted. "Give me the messages of conv_77 after 1040" is one short read in one place, also when the store holds trillions of rows.
| The calls of the app | |
|---|---|
| Call | What it does |
POST /v1/conversations | Creates a 1:1 chat or a group from a list of members |
POST /v1/conversations/{id}/members | Adds members to a group. They can read the whole history |
GET /v1/conversations | The chat list of the caller, newest activity first |
POST /v1/conversations/{id}/messages | Sends a message: client_message_id |
The user always comes from the login token, never from a parameter. A signed URL is a link that carries its own permission and stops working after 10 minutes.
The contract in one sentence: the POST and the GET are the truth, the WebSocket is a shortcut. Anything the socket delivers can also be fetched with the GET, and a phone that doubts its socket uses the GET.
Present the design as four short stories, each in its own colour on one whiteboard: Phase 1 send and commit (black), Phase 2 deliver (blue), Phase 3 reconnect and read (green), Phase 4 send a photo (purple). All four happen in one group chat. The number on an arrow is the same number in the animation and in the step table.
Swipe to see all columns
| The four phases | |||
|---|---|---|---|
| Phase | Colour | Story | What it leaves behind |
| Phase 1: Send and commit (FR1) | Black | alice sends a message. The owner of the chat numbers it, commits it and answers | One message row with seq 1041. The message exists |
| Phase 2: Deliver (FR2) | Blue | bob is online and gets it over his socket. carol is not and gets a notification | Nothing durable. Delivery is an attempt |
How to read the picture
conv_77, with alice, bob and carol. Its last message has seq 1040. A 1:1 chat works the same way.Each phase below is an interactive walkthrough of the same picture. It plays on its own. You can pause it, step with the arrow keys, and click any component to read its role.
Goal: give the message its place in the chat and store it, before anybody is told about it.
/v1/conversations/conv_77/messagesalice's phone → GatewaysNothing is written in this step.
Swipe to see all columns
| Phase 1 step by step (black arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | 12:00:00. alice's phone sends "Landing at 6" to conv_77, with an id it made up: cm_91. | Nothing. The phone keeps cm_91 until it has an answer |
| 2 | The gateway passes the request to the owner of conv_77 | |
Why it is built this way
A single SQL database could: an auto-increment column per conversation. But 3 million writes a second do not fit in one database, and a store that is spread over many machines has no shared counter. So the counter moves in front of the store: one small owner per conversation, which is exactly the size of the ordering problem.
Goal: get the committed message to every member as fast as possible, and never pretend this cannot fail.
message committedChat service → Event log{ conv_77, seq 1041 }new rowSwipe to see all columns
| Phase 2 step by step (blue arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | After the commit, chat-3 writes an event to the event log: conv_77, seq 1041. | One event |
| 2 | A delivery worker reads the event and the member list of conv_77: alice, bob, carol. alice is the sender. | Nothing |
Why it is built this way
chat-3 dies between commit and event, nobody gets the message live. It is still in the log, and every phone finds it at its next catch-up (Phase 3).Presence (FR5). The green dot next to bob's name is the same session key: bob is shown as online while a key of his exists. It can be up to 30 seconds late, and no decision depends on it.
A direct call makes the send path depend on the delivery path. If the session store is slow or a gateway hangs, alice waits. With a log in between, the Chat service is done after one write, and three independent readers react to the same event at their own pace: delivery, notifications and, later, analytics or abuse checks. A reader that falls behind catches up from the log. The price is one more hop, a few milliseconds.
Goal: bring a phone back in line with the log with one cheap read, and record how far its owner has read.
connectcarol's phone → Gateways (gw-5)SET session:carol:c-phone { gw-5, c-12 } EX 30Gateways → Session storea heartbeat every 10 s renews itsession:carol:c-phonenew rowSwipe to see all columns
| Phase 3 step by step (green arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | 12:05:00. carol opens the app. It opens a WebSocket to gateway gw-5, socket c-12, and the gateway records it. | session:carol:c-phone: gw-5, c-12. Gone after 30 s unless a heartbeat renews it |
| 2 | carol's phone has everything up to seq 1040. It asks for the messages of conv_77 | |
Why it is built this way
New members (FR3). When dave is added to the group, his phone has seq 0 and asks for everything after 0, page by page. He reads the same log as everybody else.
No. It fetches the newest page of each chat she opens, and older pages only when she scrolls up. The call is the same range read, going backwards from the newest seq. For the chat list, the phone needs one number per chat: the last seq. The unread count is that number minus her cursor.
Goal: keep 2 MB of photo out of a path that is built for 1 KB of text.
/v1/media/upload-sessionsalice's phone → Gateways → Chat serviceattachment and a signed upload URLatt_55new rowSwipe to see all columns
| Phase 4 step by step (purple arrows) | ||
|---|---|---|
| Step | What happens | Data written |
| 1 | alice picks a photo of 2 MB. Her phone asks for an upload session, with the size and the hash of the file. It gets att_55 and a signed upload URL, valid 10 minutes. | attachments row att_55: PENDING, owner alice |
| 2 | The phone uploads the 2 MB straight to object storage with that URL. No chat server sees a byte. | |
Why it is built this way
FINALIZED says the first, the owner check says the second.REFERENCED is set before the commit. If the server dies between step 4 and step 5, a photo is kept that no message uses: a little wasted space. The other order could delete a photo that a message shows.The attachment stays PENDING or FINALIZED and is never REFERENCED. A cleanup job looks once an hour for attachments that are older than 24 hours and not REFERENCED, and deletes the row and the object. At 500 million photos a day, even 1% of abandoned uploads would be 10 TB a day of bytes nobody can see.
The deep dives are the four questions from the top of the page. Each one compares three designs for the same scenario: a Bad one, which is usually the answer that sounds right; a Good one, which still leaves a gap; and a Great one, which holds. The answers start covered. Read the scenario, decide what you would build, then click each card.
Swipe to see all columns
| Deep Dive Map | |||
|---|---|---|---|
| Deep Dive | Topic | Scenario | NFR |
Scenario: 12:00:00 in the Trip group. alice sends "Landing at 6". In the same 10 milliseconds bob sends "Which terminal?". At 12:00:05 carol answers "Terminal B". The clock of alice's phone is 2 minutes fast. In which order does each of the three see the messages?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. Every phone stamps its message with the time it was sent. The server stores the stamp and everybody sorts by it.
Where it breaks. alice's phone stamps her message 12:02:00. bob's is stamped 12:00:00 and carol's 12:00:05. Every screen shows bob, carol, alice: the message that was sent first is last, below the answer to it. Worse, a phone with a slow clock puts its message into the past, above messages people have already read. Nobody can ever say "I have everything up to here".
The idea. The chat server stamps each message when it arrives. Phone clocks no longer matter.
What it fixes. A wrong phone clock. Server clocks are kept within a few milliseconds of each other.
What it still misses. There are many servers. alice's request reaches server S1, which stamps it 12:00:00.004 and writes it at once. bob's reaches S2, which stamps it 12:00:00.002, but its write is slow and lands at 12:00:00.009. carol's phone reads "everything so far" at 12:00:00.006 and gets alice's message. Next time it asks for "everything after .004". bob's message carries .002: carol never gets it. Time stamps have holes by nature, so no phone can tell that something is missing.
The key idea. Do not measure when a message arrived. Decide its place: one server hands out the numbers 1041, 1042, 1043 for this chat, and nobody else does.
How it works
conv_77 has one owner, the node chat-3. Both requests are sent to it.chat-3 dies, another node owns the partition 10 seconds later, reads the highest seq and goes on from there. If the old owner is still alive and writes the same number, only one write wins.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
two messages, sent in the same 10 msalice's phone, bob's phone → Chat serverNothing is written in this step.
The figure keeps the same boxes in all three tabs. Each design uses only some of them.
Swipe to see all columns
| DD1 side by side | |||
|---|---|---|---|
| Bad: the phone's clock | Good: the server's clock | Great: one counter, one owner | |
| What orders the messages | The clock of each phone | The clock of each server | A counter per conversation |
| alice's and bob's messages | alice's is shown last | In the order of two clocks and two write speeds | 1041, then 1042, on every screen |
Check it against the scenario
| Two messages in 10 milliseconds | |
|---|---|
| Situation | Outcome with the Great option |
| alice and bob send in the same 10 ms | The owner handles one, then the other. Whichever it takes first is 1041 |
| alice's phone clock is 2 minutes fast | It is not used. The shown time is the server's commit time |
| carol's phone has 1041 and receives 1043 | It sees the hole and fetches the messages after 1041 |
chat-3 dies | Sends to its conversations fail for about 10 s. The phones retry with the same id (DD2) |
The trade-off to name. An owner is a single point for its conversations. When the node dies, about 20 of 4,096 partitions, 0.5% of all chats, cannot send for about 10 seconds. That fits the promise: 99.95% allows about 22 minutes a month. In return, order costs nothing: no clocks to compare, no conflicts to merge. The conditional write is slower than a blind one, and it is the reason a confused old owner can do no harm.
No, and asking for it would ruin the design. A global order needs one counter for 3 million messages a second: one machine that everything waits for. Nobody ever compares the position of a message in one chat with a message in another chat. Order is only needed inside a conversation, where the traffic is a few messages a second.
"Ordering is per conversation, not global. I give each conversation a sequence counter and exactly one owner: conversations are hashed into partitions, and each partition is leased to one chat service node. The owner assigns the next sequence and commits the message with a conditional write, so even with two nodes that both think they are the owner only one can take a given number. Clients sort by sequence. Because the numbers are dense, a client that sees a gap knows it missed something and fetches the range. I do not use time stamps for order at all: phone clocks are wrong, server clocks differ, and time has holes."
Follow-up: "What happens when the owner dies?" — Its lease runs out after about ten seconds and another node takes the partition. It reads the highest committed sequence for a conversation the first time it is asked and continues from there. During those seconds sends fail and the clients retry with the same client id.
Scenario: alice's train enters a tunnel. Her phone sends "Landing at 6". The server commits it as 1041, but the 201 never reaches the phone. The phone sends again. How many times does bob see "Landing at 6"?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. The server stores whatever arrives. If the phone gets no answer, it sends again.
Where it breaks. The first request was stored as 1041. The retry after 5 seconds is stored as 1042. bob sees "Landing at 6" twice. alice too: her phone gets the answer for 1042, and at the next sync 1041 shows up as well. The phone could not have known. A lost request and a lost answer look exactly the same from the phone's side.
The idea. The phone adds an id of its own to every message: cm_91. A chat server first looks for the key sent:conv_77:cm_91 in a cache. If it is not there, the server commits the message and stores the key for 60 seconds.
What it fixes. The quick retry. After 5 seconds the key is found and the phone gets 1041 back.
What it still misses. Three cases. The tunnel is long and the retry comes after 3 minutes: the key is gone, and the message is stored again as 1042. The first request is slow, the phone gives up and sends again: two servers look in the cache at the same moment, both find nothing, both commit. And when the cache restarts, every key is gone at once. Looking up, committing and storing the key are three steps, and the memory of them is not durable.
The key idea. "Was this already sent?" is a fact about the log, so it is stored in the log: in the same write as the message, by the same owner that numbers it.
How it works
cm_91. The owner chat-3 looks in message_ids for (conv_77, cm_91): not found.201 is lost in the tunnel.The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
/v1/conversations/conv_77/messagesalice's phone → Chat server → Message store(conv_77, 1041)new rowThe figure keeps the same boxes in all three tabs. Each design uses only some of them.
Swipe to see all columns
| DD2 side by side | |||
|---|---|---|---|
| Bad: every request is new | Good: a cache for 60 s | Great: an id row in the log | |
| Where "already sent" is known | Nowhere | In a cache key, for 60 s | In a row committed with the message |
| Retry after 5 seconds | A second message | The same message | The same message |
Check it against the scenario
| The 201 is lost | |
|---|---|
| Situation | Outcome with the Great option |
| The request never reached the server | The retry finds no id row and is committed as a new message. One message |
| The request was committed, the answer was lost | The retry finds the id row and gets the same 201. One message |
| The app is killed and started again | cm_91 was saved on the phone with the unsent message. The retry uses it |
| The owner died between the two tries | The new owner reads the same message_ids table. The row is there |
The trade-off to name. One more read and one more small row for every message: 50 billion id rows a day, each kept for 7 days. And the id only works because the phone creates it once, saves it with the message and reuses it. A phone that makes a new id for every try has turned the design back into the Bad one.
Because people send the same text twice on purpose: "ok", "ok". The server cannot tell a retry from a second "ok" by looking at the content, and a time window does not help: a quick double "ok" is real, and a retry after three minutes is not. Only the phone knows whether it is trying again, and the id is how it says so.
"Every send carries a client message id that the app generates once and stores with the pending message. The owner of the conversation first looks that id up in a small table keyed by conversation and client id. If it finds it, it returns the stored sequence and message id and writes nothing. If not, it assigns the next sequence and commits the message row and the id row in one batch. So a lost response, a slow first request and an app restart all end the same way: one message, and the client gets the same answer. I do not use a cache with a time limit for this, because a retry can come later than any limit and the lookup and the write would not be atomic."
Follow-up: "Why is there no race between two retries?" — Both are routed to the single owner of that conversation, which processes its sends in order. The second one sees the row the first one wrote.
Scenario: 12:00:00, alice's message 1041 is committed. bob's phone is online on gateway gw-7. bob's laptop lost its Wi-Fi at 11:59:45 without closing its socket: its session key says "online on gw-2" until 12:00:15. carol's app is closed. The laptop reconnects at 12:00:40. At 12:01:00 alice sends 1042. Which device ends up with which messages?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. Nobody keeps track of where a device is connected. Every message is sent to all 100 gateways, and each gateway writes it to the sockets it has for the members.
Where it breaks. gw-7 has bob's phone: delivered. The other 99 gateways throw the message away. At 580,000 messages a second that is 58 million messages a second between servers, 99% of them for nothing. gw-2 writes into the laptop's dead socket: lost. carol has no socket at all: she gets nothing, not even a notification. And when the laptop reconnects and carol opens her app, both only get what is sent from then on. Message 1041 never shows up there.
The idea. Every gateway records its sockets in a session store: user, device, gateway, for 30 seconds at a time. A delivery worker looks up each member, sends the message to exactly the right gateway, and asks for a push notification when it finds no session.
What it fixes. The waste and the silence. One message per online device, not 100. carol gets a notification.
What it still misses. The session store is a guess. It says the laptop is online, so the worker sends 1041 to gw-2, which writes it into a dead socket. Because the laptop looked online, no notification is sent either. The laptop reconnects at 12:00:40 and gets 1042 live at 12:01:00. Its screen shows 1040, then 1042. Nothing tells it that a message is missing.
The key idea. Do not try to make delivery reliable. Make it checkable: every message carries its number, and every phone compares.
How it works
The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
envelope 1041Delivery workers → all 100 gatewaysNothing is written in this step.
The figure keeps the same boxes in all three tabs. Each design uses only some of them.
Swipe to see all columns
| DD3 side by side | |||
|---|---|---|---|
| Bad: every gateway | Good: look up and route | Great: route, and ask the log | |
| Who knows where a device is | Nobody | The session store | The session store |
| Server messages per chat message | 100 | One per online device | One per online device |
Check it against the scenario
| A socket that looks alive | |
|---|---|
| Situation | Outcome with the Great option |
| bob's phone, online on gw-7 | Gets 1041 live at about 12:00:00.3, and 1042 at 12:01 |
| bob's laptop, dead socket until 12:00:40 | 1041 is written into the dead socket. At 12:00:40 the laptop fetches the messages after 1040 and has it |
| carol, app closed | A notification for 1041 and for 1042. At 12:05 her app fetches both |
| A gateway crashes with 500,000 sockets | The phones reconnect to other gateways and each asks for the messages after its last seq |
| The event for 1041 was never written | |
The trade-off to name. After a big outage, millions of phones reconnect and each sends one range read per open chat. That read is cheap, one partition and a few rows, but it has to be planned for: spread the reconnects over some seconds with a random delay. And a silent chat hides a missed message until the phone reconnects, so a phone also asks after a longer pause, for example when the app comes to the front.
That builds a second reliable log, per device, on top of the first one: a record of what each of 50 million devices has confirmed, timers, resends. And it still needs the catch-up for a phone that was off for a day. The phone already knows what it has: one number per chat. Asking "what is after 1040?" is simpler than the server tracking it.
"Gateways hold the sockets and register each one in Redis with a short lifetime and a heartbeat: user, device, gateway. After a message is committed, a delivery worker reads the event, looks up the members' sessions and sends the message to exactly those gateways. If a member has no session, it triggers a push notification. I treat all of this as best effort. Every message on the socket carries its sequence. A client fetches everything after its last sequence whenever it connects, and whenever a live message does not follow directly on the last one it has. So a stale session record, a dead socket, a crashed gateway or a Redis outage costs latency, never a message."
Follow-up: "What if Redis is down?" — Nothing durable lives there. Delivery workers find no sessions and fall back to notifications. Clients catch up from the log when they open the app. Presence shows everybody as offline until the keys are rebuilt by the next heartbeats.
Scenario: bob reads the Trip chat on his phone up to 1041. One second later his laptop, which was behind, reports that it has shown everything up to 1038. And in another group with 250 members, everybody reads every message. What does alice see under her message, and what does all this cost?
Three ways to build it. Decide what you would do first. The answers are covered: click a card to reveal it.
The idea. When a phone shows a message, it reports it. The server stores a row (message, reader) and pushes it to the other members, so everybody sees "Seen by" at once.
Where it breaks. bob's phone shows three messages: three calls, three rows. In the group of 250, one message is read by 249 members: 249 rows. Each row is pushed to the other 249 members: 249 times 249, about 62,000 pushes for one message. That group has 200 messages a day: about 12.4 million pushes a day for read marks alone. And "what has bob not read?" means comparing every message of the chat with every row of bob.
The idea. Reading goes in order. So store one number per person and chat: "read up to here". bob's phone reports once: 1041.
What it fixes. The rows. Three became one, and 249 rows per message became 249 rows per chat.
What it still misses. Two things. bob's laptop reports 1038 one second later, and the last write wins: the row goes back to 1038. alice's "Seen by bob" under 1041 disappears, and bob's phone shows three unread messages again. And every move of a cursor is still pushed to all other members: in the big group that is again up to 62,000 pushes each time everybody reads.
The key idea. A read mark can only grow. And only somebody who is looking at the chat right now needs to see it move.
How it works
The three designs side by side, in one picture:
Play the three options. Switch between them with the tabs at the top of the figure.
a read receipt per messagebob's phone → Chat service → Message store(1039, bob), (1040, bob), (1041, bob)new rowThe figure keeps the same boxes in all three tabs. Each design uses only some of them.
Swipe to see all columns
| DD4 side by side | |||
|---|---|---|---|
| Bad: a row per message and reader | Good: a cursor, last write wins | Great: a forward-only cursor | |
| What is stored | A row per message and reader | One row per person and chat | One row per person and chat |
| A late report from the second device | One more row, harmless | The cursor goes back | Refused |
Check it against the scenario
| Two devices and a big group | |
|---|---|
| Situation | Outcome with the Great option |
| bob's phone reports 1041, his laptop 1038 a second later | The cursor stays at 1041. The laptop learns 1041 from the answer |
| Both devices report 1041 at the same moment | One write is applied, the other finds nothing to do. Same result |
| The phone sends the same report twice | The second one changes nothing |
| alice has the chat open | She sees "Seen by bob" within a second |
| alice opens the chat an hour later | Her phone reads the cursors of the members with the first page of messages |
The trade-off to name. A cursor cannot say "bob read 1041 but skipped 1039". Reading is treated as a line, not as a set, which is how a chat is read. And a member whose chat is closed sees read marks a little late, when the chat is opened. Both are choices of the product, taken to keep the work per message bounded.
It can be: a second number per person and chat, the highest seq any of their devices holds, also forward only. Many designs skip it and derive it: if a device of bob has fetched or received 1041, his next catch-up call says "after 1041", which is the same information. Either way it is one number, never a row per message.
"I model read state as one cursor per user and conversation: the highest sequence that user has read on any device. Clients send it at most about once a second. The server applies it with a conditional update that only moves it forward, so a late report from a second device cannot move it back and repeated reports are harmless. Whether a given message was read by someone is a comparison of two numbers. For fan-out I push cursor changes only to clients that currently have the conversation open and let everyone else read the cursors when they open it. That keeps a group of 250 from turning every message into tens of thousands of receipt events."
Follow-up: "And per-message receipts for a 1:1 chat?" — Same cursor. In a 1:1 chat the other person's cursor is exactly the "seen" marker under my last message.
| If the interviewer keeps going | |
|---|---|
| Question | Short answer |
| How is "online" shown? | From the session keys: a person is online while one of their devices has a key. It is up to 30 seconds late, and friends ask for it only for the chats on their screen. It is never used to decide anything |
| Typing indicators? | Never stored. The phone sends "typing" over its socket, the gateway passes it to the online members, and a late one is dropped. If it is lost, nothing is wrong |
| The owner of a conversation dies | Its lease ends after about 10 s and another node takes the partition. Sends fail meanwhile and the phones retry with the same id. One node is 0.5% of the chats, and 99.95% allows about 22 minutes a month |
| More than one region? | Each conversation has a home region that owns its counter. A send from far away pays one hop to that region. History is read from a copy nearby, and from the home region when the copy is behind |
Two neighbours of this question on the site: Slack is the same log with workspaces and channels of thousands of members, where fan-out becomes the hard part. Notification System is the push side on its own. The limit per user at the gateway is the topic of Distributed Rate Limiter.
Sockets are the delivery layer, and delivery may fail. Decide first where a message becomes true and how it gets its place in the order.
Phone clocks are wrong and server clocks differ. Use one counter per conversation, handed out by one owner.
A tick on the sender's screen is a promise. Give it only after the message is stored durably.
Then one phone in a tunnel decides how long the sender waits. The 201 follows the commit, and delivery runs after it.
Without client_message_id a retry is a new message. A cache with a time limit only hides the problem for a minute.
A session record is up to 30 seconds old. Route with it, and let every phone check the numbers and ask the log.
A group of 250 turns one message into 249 rows and about 62,000 pushes. Store one cursor per person that only moves forward.
Photos are 20 times more bytes than all text. Upload them straight to object storage and put only the id into the message.
The shape of a strong answer: start with one server and one table, and show that polling is slow and that time stamps do not give an order. Give each conversation one owner and one counter. Commit the message with the phone's own id, answer, and only then deliver. Route with a session store that is allowed to be wrong, and let every phone ask the log for what follows its last number. Keep read state as one cursor that only moves forward. Send photos around the chat path.
Commit first, deliver second
A message exists when it is in the log with a sequence number. The sender is told at that moment. Sockets, sessions and notifications only make it arrive sooner.
One counter per conversation, one owner
Order is a number without holes. Every screen sorts by it, and a phone that sees 1043 after 1041 knows what to fetch.
Make every write safe to repeat
A send carries the phone's own id and returns the first result. A read mark is applied only if it is higher. Retries, two devices and slow workers change nothing.
| What the interviewer expects at each level | |
|---|---|
| Level | A strong answer shows |
| Junior | Storing messages and delivering them are two things. A message table with a sequence per chat. Why polling alone is not enough for a live chat |
| Mid-level | Walks through the send: commit, sequence, 201, then delivery. Catch-up after a reconnect with after_seq. Puts Redis in a disposable role and says why the log stays the truth |
| Senior | One coherent story: an owner per conversation, the conditional commit, the id row, events after the commit, routing with a fallback, forward-only cursors, photo states. Names the failures unasked: a dead owner, a dead socket that looks alive, a restarted gateway, an upload nobody sends |
These aren't toy problems — they reflect real infrastructure challenges at companies that run chat for hundreds of millions of people. If you want to walk through this design in a mock interview or get feedback on your own approach, book a session with us. We're here to help you sharpen your thinking, build your confidence, and land your next offer.
Pick an answer for each question, and you see at once whether it is right. Show explanation opens the answer, why it is right, and why each of the other options fails.
Question 1 of 10
alice sends a message to a group of three. When does her phone get the 201?
Question 2 of 10
What decides the order of the messages in a conversation?
Question 3 of 10
A phone holds the messages of a chat up to seq 1041. A live message with seq 1043 arrives. What does the phone do?
Question 4 of 10
The 201 for a send is lost. The phone sends again with the same client_message_id. What does the owner of the conversation do?
Question 5 of 10
Why is a cache that remembers each client_message_id for 60 seconds not enough?
Question 6 of 10
What does the session store (Redis) hold in this design?
Question 7 of 10
The session store is down for five minutes. What happens to messages sent in that time?
Question 8 of 10
bob's phone reports "read up to 1041". One second later his laptop reports "read up to 1038". What is bob's cursor?
Question 9 of 10
A group has 250 members. The design stores a receipt per message and reader and pushes each receipt to all other members. How many pushes does one message cause when everybody reads it?
Question 10 of 10
alice sends a photo of 2 MB. Which way do the bytes take?
| A minute is not enough, and a cache forgets. The phone's own id is committed in the same write as the message |
| DD3 | The server pushes a message into a socket that died ten seconds ago. Who notices? | Nobody has to: we know who is online | "Online" is a guess that is up to 30 seconds old. Every message carries its number, and every reconnect asks the log |
| DD4 | A group of 250 reads a message. What do you store, and what do you push? | A read receipt per message and reader | 249 rows and about 62,000 pushes for one message. One cursor per person that only moves forward, pushed only to open chats |
| The answer waits for the commit, and never for the delivery (DD2) |
| What about a member who is offline? | A notification now, the full history when the app opens | Delivery may fail. The history may not (DD3) |
| Read marks per device? | No. One mark per person and chat is enough | A cursor, not a table of devices and messages (DD4) |
| What does a new group member see? | The whole history of the group | One log for everybody. No filter per member |
| How exact is "online"? | It may be a few seconds late | Presence is a hint. No decision depends on it |
| The message is stored | bob has it | Storing and delivering are two jobs. The second one may fail and be repeated |
| The session store says "online" | The socket is alive | The record is renewed every 10 seconds and lives 30. A phone in a tunnel still looks online |
| The server wrote to the socket | The phone showed the message | A dead socket accepts bytes for a while. Only the phone knows what it has |
| bob's laptop showed up to 1038 | bob has read up to 1038 | His phone may be further. The mark is the highest number any of his devices reported |
| 500,000 sockets each: 100 gateways |
| Session records | 50 million times 200 bytes: 10 GB, all in memory |
| Photos | 1% of the messages, about 2 MB each: 500 million a day, 1,000 TB a day |
| Group size | Mostly 2 to 20. Never more than 250 |
| One conversation | A few messages a second at the very most |
client_message_id on every send |
| A retry returns the first result. It never creates a second message |
| The 201 comes after the commit, before delivery | The sender waits 80 ms, not for 249 phones |
| An event log after the commit | Delivery, notifications and read marks react to messages that really exist |
| Sessions in Redis with a lifetime of 30 s | Fast to look up, cleans itself, and nothing breaks when it is wrong |
Catch-up by after_seq | One cheap range read brings a phone back in line with the log |
| One read cursor per person and chat, forward only | One small row replaces a row per message, and two devices cannot fight |
| Photos go straight to object storage | 2 MB never pass a chat server. The message holds an id |
message_idSTRING |
| For example msg_1041 |
sender_id | STRING | Who sent it |
client_message_id | STRING | The id the phone made up for this send, for example cm_91 (DD2) |
text | STRING | The text. Empty for a photo without a caption |
attachment_id | STRING | Points to a photo, for example att_55. The bytes are in object storage |
created_at | TIMESTAMP | Server time of the commit. For display only, never for order |
updated_at | TIMESTAMP | When it last moved |
joined_at| Who may read and send. Checked on every call |
message_ids | (conversation_id, client_message_id) and the seq it got. Kept 7 days | The answer to "was this already sent?" (DD2) |
attachments | attachment_id, owner, object key, size, hash, status | The life of a photo: PENDING, FINALIZED, REFERENCED |
| Session key | session:bob:b-phone: gateway gw-7, socket c-88. Gone after 30 s | Where to send a live message. Renewed by a heartbeat every 10 s (DD3) |
| Event | conv_77, seq 1041 | Tells the delivery workers that a message was committed |
| Kafka | One event per committed message or cursor change | At least once. A reader may see an event twice |
| Object storage (S3) | Photo bytes | Written once by the phone, read with signed URLs |
textattachment_idseqmessage_idclient_message_idGET /v1/conversations/{id}/messages?after_seq=1040&limit=50 | The messages after a seq, in order. The way to catch up |
PUT /v1/conversations/{id}/read-cursor | "I have read up to this seq." Lower values are ignored |
POST /v1/media/upload-sessions | Asks for a place to upload a photo. Answers with an attachment_id and a signed URL |
POST /v1/media/upload-sessions/{id}/complete | Says the upload is finished. The server checks the object |
WebSocket /v1/stream | Server to phone: new messages, read marks, typing, presence. Each message carries its seq |
| Phase 3: Reconnect and read (FR3, FR5) |
| Green |
| carol opens the app, fetches what she missed and marks it as read |
| A session key that expires, and carol's cursor at 1041 |
| Phase 4: Send a photo (FR4) | Purple | alice uploads a photo straight to object storage and sends a message that points to it | A 2 MB object and a 1 KB message row |
chat-3| Nothing |
| 3 | chat-3 checks that alice is a member of conv_77. She is. | Nothing |
| 4 | chat-3 looks for (conv_77, cm_91) in message_ids. Not found: this is a new message. | Nothing |
| 5 | chat-3 takes the next number, 1041, and commits two rows in one batch, on the condition that seq 1041 is still free. | messages row (conv_77, 1041): msg_1041, alice, "Landing at 6". message_ids row cm_91: 1041 |
| 6 | alice's phone gets 201 Created with seq 1041, about 80 ms after step 1. It shows one tick. | Nothing. Nobody else has seen the message yet |
The worker asks the session store where bob and carol are connected. bob: b-phone on gateway gw-7, socket c-88. carol: no key. |
| Nothing |
| 4 | The worker hands the message to gw-7, which writes it to socket c-88. bob sees it about 300 ms after alice sent it. | Nothing |
| 5 | carol is offline. The worker asks the push service to notify her: "alice: Landing at 6". | Nothing |
| 6 | The worker moves its position in the event log past this event. | The position. No "delivered" row anywhere |
| Nothing |
| 3 | The Chat service reads the message store: conv_77, seq above 1040, in order, at most 50. One row comes back: 1041. | Nothing |
| 4 | carol reads the message. Her phone reports: read up to 1041. | Nothing yet |
| 5 | The Chat service moves carol's cursor, on the condition that the stored value is lower. It was 1040. | read_cursors (carol, conv_77): 1040 to 1041 |
| 6 | alice has the chat open. The change reaches her socket the same way a message does, and her phone shows "Seen by carol". | Nothing |
media/att_55| 3 | The phone says the upload is complete. The Chat service checks that the object exists and has the promised size. | att_55: PENDING to FINALIZED |
| 4 | The phone sends a message to conv_77 with cm_92 and att_55. The Chat service checks that att_55 is FINALIZED and belongs to alice. | att_55: FINALIZED to REFERENCED |
| 5 | The message is committed as in Phase 1, with seq 1042. The row holds the id of the photo, not the photo. | messages row (conv_77, 1042) with att_55. message_ids row cm_92: 1042 |
| 6 | alice's phone gets 201 Created with seq 1042. Delivery is Phase 2. | Nothing |
| DD1 |
| One counter per conversation |
| Two messages in the same 10 milliseconds |
| NFR2 — One order |
| DD2 | The same id is the same message | The 201 is lost and the phone sends again | NFR1, NFR4 — Nothing lost, no duplicates |
| DD3 | The socket is a hint | A socket that died 15 seconds ago still looks online | NFR1, NFR3 — Nothing lost, fast |
| DD4 | A cursor that only moves forward | Two devices and a group of 250 | NFR5 — Bounded work |
| Can a phone see that a message is missing? |
| No |
| No |
| Yes: a hole in the numbers |
| The price | None | None | All sends of a chat go to one node |
conv_77| Both try to commit 1044. The condition lets one through. The other reads the new highest seq and tries 1045 |
| A chat with a message every second | Still far below what one node can number. The owner is never the limit |
cm_91, after 5 seconds or after 3 minutes. The owner finds the id row.201: seq 1041. Nothing is written, and bob sees one message.| Retry after 3 minutes |
| A second message |
| A second message |
| The same message |
| Two retries at the same moment | Two messages | Two messages | One message |
| bob sees "Landing at 6" | Twice | Once or twice | Once |
| The server died in the middle of the commit | The batch is all or nothing. Either both rows exist, or the retry is a first try |
| A retry after 8 days | The id row is gone after 7 days. No phone retries that long: it shows "not sent" after a few minutes |
| A member who is offline |
| Gets nothing |
| A notification |
| A notification, then a catch-up |
| A dead socket that looks alive | The message is lost | The message is lost | Fetched at the reconnect, or at the next live message |
| The session store is down | Not used | Live delivery stops. Messages are missed | Notifications and catch-up. Nothing is missed |
| No live delivery and no notification. The next message, or the next reconnect, shows the hole |
| The same message arrives twice on a socket | The phone already has that seq and drops the copy |
| A group of 250, one message read by all |
| About 62,000 pushes |
| Up to 62,000 pushes |
| Only the open chats get one |
| "Has bob read 1040?" | Look for the row | Is the cursor at 1040 or above? | Is the cursor at 1040 or above? |
| The group of 250, everybody reads | 249 small writes. A push only to the members who are looking |
| The home region is down | Stop sending in its conversations until a new owner is chosen from a region with a complete copy of the log. Accepting writes in two places would give two orders |
| A new member should not see old messages | Store joined_at_seq on the member row and let the history read start there. The log stays one log |
| A gateway is restarted for a deploy | It stops taking new sockets and tells its phones to reconnect, a few thousand at a time. Its session keys expire by themselves, and every phone catches up after it reconnects |
| Too many notifications | None when a device of that person has the chat open. One summary per chat when several messages arrive close together. People who are annoyed switch notifications off, and then offline delivery is gone |
| Why a wide-column store for the messages? | The two access patterns are "append to a chat" and "read a range of a chat", both by one key, at 50 TB a day. Members and attachments need transactions and stay in SQL |
| Kafka or a simple queue? | Several readers need the same event: delivery, notifications, abuse checks. A log lets each read at its own pace and replay. A queue is enough if delivery is the only reader |
| Spam and floods | A limit per user and per device at the gateway, and a block list that the delivery path checks before it sends |
| How is the chat list built? | One row per member and chat with the last seq and the time of the last message, updated by a reader of the event log. Sorted by last activity. Unread is last seq minus the cursor |