Design a chat system
Read first: Networking for request paths, Partitioning and sharding, Queues and logs
A gateway holds the socket and nothing else that matters. The message is committed to a per-conversation log before anyone is told, that commit order is what the room sees, and a gateway that dies mid-fanout is repaired by cursor because push is best effort. Presence is a separate, lossy fact.
A chat message has two jobs, and they are not the same moment. It has to be stored, in an order the conversation agrees on, and it has to show up on other screens. If you show it before you store it, a dead process can display a message that history will never contain. The gateway holds the socket. It does not hold the truth.
Requirements
The user is a person in a team tool. They have one-to-one threads and groups. They expect a message they saw get an acknowledgement to still be there after a refresh, in the same place among its neighbors.
Functional requirements:
- Send a message. The ack means “stored,” not “every phone has rendered it.”
- Deliver to members who are online, usually within a second. Assumption of that “usually”: it is a target, not a contract you page on, because a dead gateway makes push latency infinite for the sockets it held.
- History on reconnect, and on scroll, in the conversation’s order.
- Groups and one-to-one use the same pipeline. The member list is the difference.
- Presence: a member can look roughly online or offline. It can be wrong for a few tens of seconds.
Non-goals:
- A room of a hundred thousand sockets. That is a broadcast tree. This design caps a group. Assumption: 300 members. Above that you are in a different system, and you should say so rather than stretch the member-list fanout.
- End-to-end encryption. Transport is TLS. The server reads the message so it can store it and push it. If the product cannot live with that, the design changes and this interview has not started.
- A total order across every conversation in the company. Nobody’s screen needs that.
- Typing indicators and presence as durable facts. They are hints.
Product assumption: the sender’s ack is p99 under 100 ms inside the region, which is one partition write, not a wait for 300 pushes.
Estimation
Assumptions:
- 150 million messages sent per day.
- Peak send rate is 4 times the average, during the workday. Assumption.
- 4 million people connected at the daily peak. Assumption, and it does not have to track the send peak one for one. People stay connected and type in bursts.
- One gateway process holds 40,000 sockets. Assumption you would measure. Use it as a sizing input, not as a benchmark you memorized.
- Average deliveries per message are 6, because most threads are one-to-one or small. Assumption. A 300-person group is the exception, not the multiplier you apply to every send.
- A stored message is 250 bytes of body plus ids. Assumption.
- Hot history is 30 days. Assumption.
150,000,000 / 86400 = 1,736 sends per second average
150,000,000 / 1e5 = 1,500 sends per second shortcut
peak sends, 4x = about 6,900 per second
deliveries at 6 each = about 42,000 socket writes per second at peak
A day is 86,400 seconds. The 1e5 shortcut is about 14 percent low. One million messages a day would be about 12 per second. You are past that, and the send path is still one write per message, not 6.
4,000,000 sockets / 40,000 per process = 100 processes at the peak
run them near 60 percent full so one death has somewhere to reconnect
4,000,000 / 0.6 / 40,000 = about 170 gateway processes
150e6 * 250 bytes = 37.5 GB/day
30 days * 37.5 GB = about 1.1 TB raw of hot history
times 3 replicas = about 3.4 TB
170 processes is a derivation from the connection assumption and the fill assumption. If a process really holds 80,000 sockets, you halve the fleet. The shape does not change. 3 TB of replicated history is a small partitioned store. The hard part is not the disk. It is a gateway that dies after some of the sockets have the message and the rest do not.
Slack has published that a message is persisted before it is broadcast, and that this persistence sits on the send path so the database has to be fast. That is the constraint you just sized. One in-region write at a few thousand per second is fast. A write that waits for every member is not. The published system is a useful check, not a diagram to redraw from memory. The Slack path is its own lesson.
High-level design
flowchart LR
sender[Sender] --> gwA[Gateway A]
gwA --> store[Message store]
store --> fanout[Fanout workers]
fanout --> gwB[Gateway B]
fanout --> gwC[Gateway C]
gwB --> sockets[Member sockets]
store --> history[History by cursor]
A client opens a WebSocket to a gateway. A WebSocket starts as an ordinary request and then stays full duplex, which is networking you should say in one sentence: the server holding the socket is stateful. The next packet from that client wants that process, or a directory that can find where the client went. The load balancer can balance the initial connection. After that, stickiness is just “the socket is already here.” Do not also pin every later HTTP call from that user to the same machine and call it a design. History fetches can land anywhere.
On connect, the gateway registers “user U, generation G, is on gateway A” in a directory with a short TTL, refreshed by heartbeat. Assumption: heartbeat every 10 seconds, directory expiry at 30 seconds. A new connection writes a higher generation. A disconnect deletes the row only if the generation still matches, so a slow disconnect cannot erase a reconnect that already won.
Send path:
- The gateway checks that this user is a member.
- It appends the message to the store, partitioned by conversation id.
- The store assigns the next sequence for that conversation and commits.
- The gateway acks the sender with that sequence.
- A fanout worker, reading a queue or the store’s log, looks up online members and tells their gateways to push.
The ack is step 4. Step 5 is not on the sender’s clock. Slack’s published choice is the same split. You are using the split because a phone that is offline, or a gateway that is dead, must not hold the sender’s request open.
Deep dive
Order per conversation, not global
The message store’s partition key is the conversation id. One primary per partition appends. The sequence it assigns, 1 then 2 then 3, is the order. Two messages that arrive at two gateways in the same millisecond are ordered by whichever commit happens first on that primary, and every client sees that order. Clients do not reorder by their own clocks. If they do, two people in the room disagree about which sentence came first.
There is no sequence across conversations. The inbox sorts each thread by the commit time of its latest message. A few milliseconds of disagreement between partitions does not matter for a list of threads. Building a global sequencer so that “the company has one order” adds a single point every message has to touch, and no screen was asking for it.
A hot conversation is a hot partition. Humans in a group of 300 cannot type fast enough to melt a partition. A bot can. If one conversation is a firehose, give it a time bucket in the partition key so the live bucket does not grow forever as one ever-hot range, and isolate it so its compaction and its latency do not punish every other conversation on the machine. Discord wrote up the version of this that hurt: a hot channel as a hot partition. You do not need their cluster size to make the point. One busy key is one busy partition, and adding partitions elsewhere does not move it.
One-to-one and group are the same log. A one-to-one thread is a conversation with two members and a list that does not change. A group is a conversation whose member list changes. Fanout reads the member list at push time. History reads enforce membership too, so a person who was removed does not keep pulling new sequences even if a stale push arrives. Assumption you state: a newly added member may read earlier history. If the product says they cannot, store the sequence at which they joined and start there. Either rule is fine. Leaving it unstated is not.
The sender of a one-to-one message waits for one commit, then the fanout is two directory lookups. The sender of a 300-person message also waits for one commit. They do not wait for 300 pushes. One dead socket in the room must not set send latency. The fanout cost is proportional to online members, and it is asynchronous. That is the entire difference between the two products. Resist a second architecture for one-to-one. You will forget to fix the small one when you fix the large one.
Persist, then fanout, and a gateway that dies in the middle
Put numbers on the failure, or it stays a slogan. A conversation has 40 members online, spread across 8 gateways. The message commits as sequence 88. The sender has the ack. Fanout has notified 3 gateways, 15 people, when the fanout worker dies. Separately, imagine gateway B holds 6 of those members, receives the push, writes it to 4 sockets, and then dies.
The 4 people who already rendered 88 keep it. It is in the log. The 2 on gateway B who never got the write reconnect to some other gateway and send “I have through 87 in this conversation.” The server returns 88. The gateways that were never notified get the fanout again, because the worker died before the ack and the queue redelivers. Those clients may receive 88 twice, once from a late push and once from history. They dedupe by conversation id and sequence.
If you had pushed before the commit, those 4 people would have rendered a message the log does not contain. On reconnect the cursor answers “87 is still the end,” and the sentence vanishes, or the commit lands later with a different sequence than the one you displayed. That is the bug. Persist first. The ack means stored. Delivery receipts, if the product wants them, are a second event, also stored, also allowed to arrive more than once and be deduped. They are not the send ack.
At-least-once fanout is what a queue gives you when the worker dies after some side effects and before the ack. Idempotency here is the client’s dedupe and the gateway’s willingness to push a sequence the client might already have. You do not need exactly-once sockets. You need a log you can re-read.
A deploy drains a gateway: stop taking new sockets, give existing clients time to move, then close. A crash skips the drain. 40,000 people reconnect, and the other gateways must have the slack you sized for at 60 percent fill. Each reconnecting client presents its cursors and gets the gap. The directory’s 30 second expiry is why those users also look offline for a moment even though the messages are safe. Presence is allowed to say offline. History is not allowed to say the message is gone.
Presence, kept off the log
Presence is “this gateway has heartbeated for this user inside the TTL.” When heartbeats stop, the directory drops the route and the user looks offline. A crashed gateway fails that way for every socket it held, within 30 seconds under the assumption above. You do not write presence into the message log. Mixing them means a presence flicker is an ordered event you have to store, replicate, and scroll past.
Do not broadcast presence to every member of every group. A group of 300 with a heartbeat every 10 seconds is 30 events per second of pure presence if each heartbeat is pushed to everyone else, and that is one group. The client subscribes to the people currently on screen. That is a published Slack approach and it is the right default. A one-to-one thread can subscribe to the other person for the whole time the thread is open. A group should not. The cost of being wrong is a green dot that lags by a TTL. The cost of being “right” is a presence system larger than the message system.
Group fanout uses the same directory presence already maintains. If the directory says the user has no gateway, skip the push. They will read history later. Do not block the fanout worker on a retried push to a socket that just died. One attempt, then move on. The log is the retry.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Persist, then ack, then fanout | A rendered message is in the log, and a dead gateway cannot erase it | The sender waits for a commit, and push is a second phase that can be partial |
| Push, then try to store | The happy path feels instant | A crash shows a message history will deny |
| Per-conversation sequence | One order the room agrees on, no clock skew inside the thread | No global order, and a hot thread is a hot partition |
| One global sequence | A total order nobody asked for | Every send shares one log’s throughput and its outage |
| Presence in the directory with a TTL | Online dots are cheap and a dead gateway clears itself | A user looks offline for the TTL after a crash, even though messages are fine |
| Presence as ordered messages | The dot and the log never disagree | You store and fan out a heartbeat product by accident |
| Wait for every socket before ack | The sender knows who received it | One dead phone sets send latency for the room |
The first row is the design. Delivery receipts can be added on top of it. They must not replace it.
Failure modes
- Gateway dies mid-fanout. Covered above. Symptom if you got the order wrong: support tickets that say “I saw it and then it was gone.” Symptom if you got it right: a short period where some clients have 88 and others pull it on reconnect. The second is the design working.
- Message store primary for a partition down. Sends in those conversations fail. Other conversations, on other primaries, keep going. That blast radius is why the partition key is the conversation and not “all chat.” Failover needs fencing so two primaries do not issue two versions of sequence 88. A duplicate sequence is a worse bug than a gap. A gap, the client can skip. A fork, the client cannot merge.
- Directory stale. Fanout pushes to a gateway that no longer has the user, or fails to push to the new one for up to the TTL. The user still has history. Do not treat a failed push as a failed send, or you will retry the send and risk a second sequence if the first commit actually happened. The sender already has the ack. Fanout retries are keyed by sequence, not by “insert the body again.”
- Retry storm on reconnect. 40,000 clients reconnect and each asks for history of every conversation they are in. That read spike, not the original crash, takes down the store. Clients ask for the cursors of the threads on screen first, and the rest in the background. The store sheds bulk history before it sheds the single-thread gap fill, because the gap fill is what makes the room look coherent.
- Hot bot conversation. One partition’s latency climbs and, if other conversations share the machine, their send p99 climbs with it. Isolate or bucket the firehose. More gateways do nothing. The gateway was never the bottleneck.
- Member removed, push still happens. A stale member cache of a second or two can deliver one extra message. History reads check membership again, so a refresh does not keep showing new messages. If even one extra push is unacceptable, check membership inside the fanout with a cache TTL you can name. Assumption: one second of staleness is acceptable for this product. Say it.
- Client dedupe missing. A redelivered push draws the same sentence twice. The sequence is the key. A client that dedupes on body text will hide a person who actually said the same thing twice.
In the interview
First five minutes: ack means stored, order is per conversation, groups and one-to-one share the path, presence is not the log. The number is about 1,500 sends per second with the shortcut, under 7,000 at a 4 times peak, and about 4 million sockets, which is on the order of 100 to 170 gateway processes depending on how full you run them. Draw gateway, store, fanout, directory. The bottleneck you name is the commit on a hot conversation, not the socket write.
Skip encryption, skip a global sequence, skip a hundred-thousand-person room. If they ask for the giant room, say you would change the design to a broadcast tier and that this interview’s group cap is 300.
The question that follows is the gateway dying after half the room has the push. You walk sequence 88, the cursor, and the dedupe. The tradeoff you admit: the sender is not told that every device displayed it, and presence can say offline while the log is healthy.
Check yourself
Fanout has reached 4 sockets when the gateway process dies, and the sender already has an ack for sequence 88. What is true of those 4 users after they reconnect?
The message is in the log, so reconnect does not delete it. They already have 88. Everyone who missed the push sends the last sequence they have, 87, and receives 88. If the push had happened before the commit, those 4 users would have rendered a message the log can deny, and reconnect would make it vanish.
Why is there no global message sequence across conversations?
No screen needs one total order of the whole company. A global sequence would put every send behind one log’s throughput and one log’s outage. Inside a conversation, the partition primary’s commit order is the order clients must share. Across conversations, sorting the inbox by each thread’s latest commit time is enough, and a few milliseconds of skew between partitions is invisible there.
A group has 300 members and one socket is dead. Why does the sender's ack not wait for 300 pushes?
The ack means the commit succeeded. Waiting for every push makes send latency depend on the worst phone in the room, and one dead socket holds it open until timeout. One-to-one and group share that rule. The only difference is how many directory lookups the asynchronous fanout does. Offline members read history later.
Where does presence live, and why is a heartbeat not a message?
Presence is a directory row with a TTL, refreshed by the gateway that holds the socket. It can be stale, and a crashed gateway makes those users look offline within the TTL. Writing heartbeats into the message log would store and replicate a second product, and broadcasting every heartbeat to a whole group costs more than the messages. Clients subscribe to the people on screen.
What is 150 million messages a day at a 4 times peak, with 86,400 and with the 1e5 shortcut?
150 million divided by 86,400 is about 1,736 per second. Divided by 1e5 it is 1,500. Four times the exact average is about 6,900 sends per second. Each send is one partition commit. Multiplying by the number of members is the fanout, and that multiplier is not on the ack path.
Based on: Slack Engineering, real-time messaging writeup; Discord message store writeup; Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes.