Chat
What we are building
Section titled “What we are building”A chat service lets people send short messages to one person or to a group, and see them arrive at once on every device they have open. The pieces that make it different from the services before it in this module are two: the connection stays open, so the server must remember who is connected where, and the messages of one conversation must be seen in one order by everyone.
Functional requirements. Send a message to one person or to a group. Receive it at once when online, and receive it later when offline. See each conversation in the same order as everyone else. Show who is online. Photos and videos, calls, search and end-to-end encryption are real features and are left out here, so that the lesson stays on delivery. This case study is one region; the global messaging case study builds on it.
Non-functional requirements. These are the targets we choose, not figures from a real service. A message reaches an online recipient in under 500 ms at the 99th percentile. A message that the sender saw as sent is never lost. Messages of one conversation appear in the same order for all members. The service stays available when one server is lost.
Scale. 10 million daily users, each sending 30 messages a day. 90% of the messages are one-to-one and 10% go to a group of 20 members. At the busiest moment, 20% of the daily users are connected.
Mental model. A chat service is a post office that also keeps a telephone line open to each customer. The mail (the messages) is small. The telephone lines (the connections) are the heavy part, and so is the fact that one letter to a group is a delivery for every member.
Estimate before you design
Section titled “Estimate before you design”The requests per second lesson gives the method. Here it is for this system, with the assumptions in the table.
| Quantity | Working | Result |
|---|---|---|
| Messages per day | 10 million × 30 | 300 million |
| Messages per second, on average | 300 million ÷ 86,400 | about 3,500 |
| Peak, assuming 3 times the average | 3,500 × 3 | about 10,000 messages per second |
| Recipients per message | 0.9 × 1 + 0.1 × 19 | 2.8 |
| Deliveries per second at the peak | 10,000 × 2.8 | 28,000 |
| Open connections at the peak | 20% of 10 million | 2 million |
| Gateway servers, at 50,000 connections each | 2 million ÷ 50,000 | 40 |
| Heartbeats, one per connection every 30 s | 2 million ÷ 30 | about 66,700 per second |
| Storage per year | 300 million × 200 bytes × 365 | about 22 TB, and about 66 TB with 3 copies |
| Traffic in, and out | 10,000 × 200 bytes, and 28,000 × 200 bytes | about 2 MB/s in, and about 5.6 MB/s (45 Mbit/s) out |
The 3, the 200 bytes, the 20% and the 50,000 connections per server are assumptions. The last is conservative: in 2012 WhatsApp reported more than 2 million TCP connections on one server, which is a good reminder that this figure depends on the hardware and the software more than on the protocol. Three things follow from the arithmetic whatever the exact values. Storage and bandwidth are modest: tens of terabytes a year and a few megabytes a second. The message rate is moderate. What is large is the number of open connections, 2 million, and the traffic of the heartbeats that keep them alive, 66,700 a second, which is 6.7 times the rate of the messages themselves. Chat is a connection-holding problem with a small amount of data.
The API and the data
Section titled “The API and the data”A phone opens one WebSocket when the app starts. RFC 6455 defines it as a handshake over HTTP that turns the connection into a channel on which either side can send. Everything below travels on it, as small frames.
client → server send {"id": "9f1c…", "conversation": "c42", "body": "On my way"}server → client ack {"id": "9f1c…", "seq": 413}server → client msg {"conversation": "c42", "seq": 413, "from": "u7", "body": "On my way"}client → server sync {"conversation": "c42", "after": 410}The id is made by the phone, once, and sent again unchanged if the phone has to retry; it is what makes a repeat harmless. The seq is made by the server: it is the number of the message inside its conversation, and it is the order everyone sees. History is also served by an ordinary request, GET /conversations/c42/messages?after=410, which is what sync does on the open connection.
The data is a table of messages, read by conversation and by number, and nothing else.
| Column | Meaning |
|---|---|
conversation |
The partition key: all messages of a conversation live together. |
seq |
The number inside the conversation: 1, 2, 3 … It is the second part of the key, so the messages of a conversation are stored in order. |
id |
The phone’s message id, kept to recognise a retry. |
sender, body, sent_at |
Who, what, and when the server accepted it. |
Discord describes the same shape. Its Cassandra table has the channel id as the partition key and a time-sortable message id as the clustering key, so that loading a channel is a range scan inside one partition. It also had to bound the size of a partition: a channel can exist for years, and Discord split each channel’s messages into time buckets, sized at about 10 days of messages so that a partition could stay under 100 MB. Our store is partitioned the same way, by conversation.
Five stages, each forced by a number
Section titled “Five stages, each forced by a number”The lab starts with the simplest design that works and adds one thing at a time. One request in it is one message sent. Each stage is designed for a load, and the slider raises the load to 3 times and 10 times that, which shows where the stage runs out. Every figure is model output with illustrative inputs, and the model notes under the lab list what it leaves out.
A chat service that delivers one-to-one and group messages, in order within each conversation, to users who are online or offline. Here one request is one message sent. Step through five stages, each adding the one thing the previous stage’s numbers called for, and raise the load to see what breaks.
Start simple: one chat server and one database
Design load of this stage: 100 req/s
- What we add
- Phones keep a WebSocket open to one chat server. A message arrives on the sender’s connection, is written to one database and is pushed down the recipient’s connection if the recipient is connected to the same server.
- Why: the number that forced it
- At 100 messages per second, a small database that stores a message in about 5 ms, 4 at a time, is at 13% of its 800 writes per second. Nothing else is close to its limit.
- What it costs
- Cheap and easy to reason about: one program, one database, and the order of messages is whatever order the database commits them in. The price is that every message is a database write, and each part is a single point of failure.
- What breaks next
- At 10 times the load, 1,000 messages per second, the writes alone ask the database for more than its 800 per second: it is overloaded and a fifth of the messages fail.
Each dot stands for many requests. The numbers show the real rate.
No bottleneck: every component has headroom.
Figures at this load
- Busiest component
- DatabaseHealthy13% of its capacity
- p95, whole request
- 20 ms
- p99, whole request
- 28 ms
- Requests served
- 100%100 req/s
- Requests failed
- 0%0 req/s
- Bottleneck
- none
| Component | State | Utilisation | Offered (req/s) | Served (req/s) | Rejected (req/s) | p50 | p95 | p99 |
|---|---|---|---|---|---|---|---|---|
| Phones and browsers | Healthy | <1% | 100 | 100 | 0 | 0 ms | 0 ms | 0 ms |
| Chat server | Healthy | 4% | 100 | 100 | 0 | 2.1 ms | 9 ms | 14 ms |
| Database | Healthy | 13% | 100 | 100 | 0 | 3.5 ms | 15 ms | 23 ms |
- Traffic
- 100 req/s
- Successful
- 100 req/s
- Error rate
- 0%
- Mean latency
- 8.6 ms
All stages at a glance
Each cell is the engine’s steady state for that stage at that load: the busiest component, how much of its capacity it uses, and the share of requests that fail.
| Stage | Design load | Design load | 3× the design load | 10× the design load |
|---|---|---|---|---|
| 1. Start simple: one chat server and one database | 100 req/s | 100 req/sDatabase: 13%none fail | 300 req/sDatabase: 38%none fail | 1K req/sDatabase: 125%20% fail |
| 2. Partition the messages by conversation | 1K req/s | 1K req/sChat server: 38%none fail | 3K req/sChat server: 113%11% fail | 10K req/sChat server: 375%73% fail |
| 3. Spread the connections over gateway servers and keep a registry | 10K req/s | 10K req/sConnection registry (Redis): 59%none fail | 30K req/sConnection registry (Redis): 178%80% fail | 100K req/sGateway servers (open connections): 250%96% fail |
| 4. Split the registry by user | 10K req/s | 10K req/sGateway servers (open connections): 25%none fail | 30K req/sGateway servers (open connections): 75%none fail | 100K req/sGateway servers (open connections): 250%60% fail |
| 5. Deliver through a log and delivery workers | 10K req/s | 10K req/sMessage store (partitioned by conversation): 9%none fail | 30K req/sMessage store (partitioned by conversation): 28%none fail | 100K req/sMessage store (partitioned by conversation): 94%none fail |
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Requests arrive at random, as a Poisson process, at a constant average rate.
- Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
- Service times are random with the stated mean; by default they are exponentially distributed.
- Each node is analysed separately, with the traffic it receives treated as Poisson.
- One request is one message sent. The mix is 90% one-to-one messages and 10% group messages sent in groups of 20 members, which is 19 recipients, so a message has 2.8 recipients on average, and 30% of the recipients are offline when it is delivered. These are teaching figures, not measurements of a real service.
- Every number (service times, capacities, connections per server, the design loads) is illustrative model output, chosen to make the limit of each stage visible. None of them is a benchmark of a real database, cache or server.
- Presence is counted as heartbeats: 2 million connected users, one heartbeat every 30 s, is 66,700 a second, which is 6.7 for each of the 10,000 messages a second of the peak. The lab sends 6.7 heartbeats with every message, so they grow with the load.
Simplifications
- Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
- Percentiles assume an exponential tail. A service-time variability other than exponential changes the mean wait but not the shape of the tail.
- A node frees its slot as soon as it has done its own work, before waiting on the services it calls. Real thread-per-request servers hold the slot, so a slow dependency exhausts them faster than this model shows.
- A request calls its dependencies one after another. Parallel fan-out is not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
- Retries add load. Their backoff and jitter decide when that load arrives, which only the per-request simulation shows.
- Retry feedback is solved from the healthy starting point, so it finds one stable outcome. Systems that stay stuck in overload after the cause is gone are not shown.
- A throughput limit (for example maximum writes per second) is modelled as slower service, not as a separate rate limiter.
- A caller’s timeout counts the mean time its dependencies take, not their full distribution.
- Latency percentiles for a whole request are estimated, over every request, including those that are rejected and fail quickly. The mean is exact, and the percentiles come from a gamma distribution that has that mean and the variance of the time spent in each component.
- Each stage is shown in a steady state: the load is held and the engine says where queues build. A burst, a mass reconnection after an outage and a deploy are not modelled.
- The engine measures load, not guarantees. Order, duplicates and lost messages are not simulated; the lesson explains how each stage keeps them.
- In stages 3 and 4 a gateway server spends about 4 ms on a message: 1.2 ms of its own work and about 1 ms for each of the 2.8 recipients. In stage 5 the work for the recipients moves to the delivery workers, whose 3 ms covers it. Writing to the recipient’s socket is counted in that time, not as a separate step.
- Reading history, media, typing indicators, read receipts and abuse prevention are not modelled. Photos and videos would go to object storage, with only a link in the message.
Parameter values are illustrative. They are not benchmarks of any real product.
Stage 1, one chat server and one database. At 100 messages per second the database is at 13% of its 800 writes per second. Raise the load to 10 times, 1,000 messages per second, and the writes alone are 125% of what it can do: a fifth of the messages fail. The number that ends this stage is the database’s 800, against a peak of 10,000.
Stage 2, messages partitioned by conversation. The database becomes a store of 40 nodes. A message goes to the node chosen by hashing its conversation id, so a conversation always lives on one node, and that node numbers its messages. The 40 nodes can take about 107,000 writes per second between them, and at 1,000 messages per second the store is at 1%. Now the single chat server runs out: it also holds every connection, and it can serve 2,667 messages per second. At 3 times the load, 3,000 per second, it is at 113% and about 11% of the messages fail.
Stage 3, gateway servers and a registry. The connections are spread over 40 gateway servers, about 50,000 each, which is where the 2 million come from. A registry in Redis records which gateway holds which user. When a message arrives, the sender’s gateway looks each recipient up there and hands the message to the right gateway. At 10,000 messages per second the gateways are at 25%. The registry is asked for 94,700 operations per second, 2.8 lookups and 6.7 heartbeats for each message, which is 59% of its 160,000. At 3 times the load it needs about 284,100 against 160,000, which is 178%, and 4 messages in 5 fail, because each one needs several lookups.
Stage 4, the registry split by user. The registry becomes 8 nodes, and a user’s entry is on the node chosen by hashing the user id. Together they can do 1,280,000 operations per second, and at 3 times the load the registry is at 22%. Now the gateways give way. A message occupies a gateway for about 4 ms: 1.2 ms of its own work and about 1 ms for each of its 2.8 recipients. The 40 gateways can do 40,000 messages per second, so at 10 times the load, 100,000 per second, they are at 250% and 60% of the messages fail.
Stage 5, a log and delivery workers. The gateway now only checks the message, writes it to the store, appends it to a message log and acknowledges the sender. 64 delivery workers read the log, look each recipient up in the registry, hand the message to the recipient’s gateway, or, when the recipient is not connected, send a push notification and leave the message in the store. A gateway spends 1.2 ms per message and can do 133,333 per second; the workers can do 170,667. At 10 times the load the gateways are at 75%, the workers at 59% and the registry at 74%, and the store is the first to run short at 94% of its 106,667 writes per second. Nothing fails, but a burst would overload it. The next steps, which the lab leaves out, are more store nodes, splitting the busiest conversations, and a second region.
One order per conversation
Section titled “One order per conversation”Everyone in a conversation must see the messages in the same order. The tempting way is to sort by the time the phone says it sent them. The lesson on physical clocks shows why that fails: two phones’ clocks differ, so a reply can be stamped earlier than the question it answers.
The design avoids clocks. All messages of a conversation go to one partition, because the key is the conversation id, and that partition gives each message the next number: 1, 2, 3. The partition is the only writer for that conversation, so there is no disagreement to resolve: the order is the order in which the partition accepted the messages, and every member is shown the messages by number. The order is only per conversation. Two conversations have no relative order, and nobody needs one.
The price of this is that one conversation is limited by one node. A group that sends thousands of messages a second would overload its partition, and the lab does not show it, because every conversation is small in it. Real services keep groups small, or split a very large channel into several streams. Slack’s channel servers, for example, are assigned channels by consistent hashing, so that a conversation always has the same owner, and a failed owner is replaced in under 20 seconds, during which its channels see slower delivery.
Acknowledged, delivered, de-duplicated
Section titled “Acknowledged, delivered, de-duplicated”A sent message goes through three moments, and the design keeps them apart.
- Accepted. The gateway checks the message, the store writes it with its number, and only then does the sender receive
ack. If the gateway crashes before that, the sender gets noack, sends again with the sameid, and the store, which has seen thatid, answers with the number it already gave instead of writing the message twice. - Delivered. A worker hands the message to each recipient’s gateway, which writes it to the recipient’s connection. The delivery semantics lesson names the rule: a system that retries after a failure delivers at least once. A worker that crashes after delivering but before recording its position in the log delivers again.
- Seen once. The phone keeps the numbers it already has for each conversation and ignores a message whose number it holds. This is an idempotency key at the receiving end: at-least-once delivery plus a check for repeats looks like exactly once to the person reading.
Offline users
Section titled “Offline users”At the peak 30% of the recipients are offline when a message arrives, which is 8,400 push notifications a second at 10,000 messages. The message is already in the store. The worker sends a push notification through the phone maker’s service, whose only job is to wake the app or to show a notice; it does not carry the conversation.
When the phone reconnects, it sends the last number it holds for each conversation and the server sends what follows, the sync call above. Facebook’s Messenger describes a version of this that keeps one ordered queue of updates per user, with a separate pointer for the last update sent to the app and the last written to long-term storage; when the phone is offline its pointer simply stays where it was while new messages are queued. The idea is the same: the server remembers a position, and the client asks for everything after it.
Presence
Section titled “Presence”Presence is the green dot, and it is a surprise in the arithmetic. A connected phone sends a heartbeat every 30 s so that the registry can expire the entry of a phone that disappeared. Two million connections give about 66,700 heartbeats a second, 6.7 times the 10,000 messages of the peak, and in the lab the heartbeats are the largest part of the registry’s load at stage 3. If every change of presence were also sent to everyone who has that person as a contact, the traffic would multiply again by the number of contacts.
Slack’s answer is to send a client presence notifications only for the users visible on its screen at that moment, and to keep presence in servers that are reached by hashing the user. The choice is the same as for groups: do the work for the people who will look.
What happens if a gateway server dies
Section titled “What happens if a gateway server dies”A gateway holds about 50,000 connections. When it dies, they all drop and the phones reconnect to the 39 others. If they all do it at the same instant, the registry takes 50,000 writes at once and the surviving gateways take 50,000 handshakes. If each phone waits a random time up to 30 s before reconnecting, jitter turns the burst into about 1,667 reconnections a second. Meanwhile the registry still points at the dead gateway: a worker that hands a message to it gets no answer and treats the user as offline, so the message is stored and a push notification is sent. No message is lost, because it was stored before it was delivered.
What happens if the registry is lost
Section titled “What happens if the registry is lost”The registry is a cache of where users are, not the truth: the store holds the messages and the phones hold the connections. If the registry is lost, every lookup finds nobody, and every recipient looks offline. The workers send a push notification for every delivery: 2.8 for each message, 28,000 a second at the peak instead of the 8,400 of the normal 30%, which is 3.3 times as many. Users get notices instead of live messages until the heartbeats rebuild the entries, which takes up to 30 s. The cost is noise and delay, not loss, and that is why the registry is allowed to be an in-memory store.
Trade-offs
Section titled “Trade-offs”Each row is a decision in the lab, written with what it buys, what it costs and when the other choice is better.
| Decision | What you gain | What you pay | When to choose otherwise |
|---|---|---|---|
| A WebSocket per phone | Messages arrive at once, with no request per message | Millions of open connections to hold, a registry, and heartbeats | When updates are rare and a delay of seconds is fine: polling is simpler to run |
| One order from the partition, not from clocks | Everyone sees one order, whatever their clocks say | One conversation is limited by one node | When conversations are huge and order matters little, as in a broadcast channel |
| Acknowledge after the write | A message the sender saw as sent is never lost | The sender waits for the store, a few milliseconds | When losing the odd message is acceptable, for example typing indicators |
| A log and workers for delivery | A slow recipient or a large group does not slow the sender | A log to run, and delivery that happens a moment after the send | When groups are tiny and the load low: delivering inline is simpler |
| Presence for the contacts on screen | Far less presence traffic | A dot that is not updated for a contact you are not looking at | When the user list is tiny: sending presence to everyone is easy |
Defend your design
Section titled “Defend your design”An interviewer asks for this system in 45 minutes. A good answer begins with the numbers (the messages are small, the connections are the load), puts the order in the partition and not in the clocks, and says out loud what happens when a gateway or the registry is lost. Write your answer before you read the strong one.
Interview question
Writing and reviewing an answer needs JavaScript.
The interviewer asks
Design a chat service for 10 million daily users, with one-to-one and group conversations. Messages must arrive in order within a conversation and must not be lost when the recipient is offline.
Assume each user sends 30 messages a day, the busiest moment is 3 times the average, groups have up to 100 members, and a connected phone keeps one open connection. Media is handled elsewhere.
Write your answer first. The strong answer unlocks once you have written a real attempt.
0 of 80 characters written to unlock the strong answer
- 10 million users at 30 messages make 300 million messages a day: about 3,500 a second, about 10,000 at the peak. Storage is about 22 TB a year. The load is 2 million open connections and 66,700 heartbeats a second, 6.7 per message.
- Stage 1 puts everything in one database: 13% at 100 messages per second, 125% at 1,000. A store of 40 nodes partitioned by conversation takes about 107,000 writes per second, and its node numbers the messages of a conversation.
- 40 gateways hold the 2 million connections. A single registry at 160,000 operations per second is at 59% at 10,000 messages per second and at 178% at 3 times that; 8 nodes make it 22%.
- A gateway that fans out inline occupies about 4 ms per message and gives way at 40,000 messages per second. A log and 64 delivery workers bring the gateway to 1.2 ms, and leave the store at 94% at 100,000 messages per second.
- The order is the partition’s number, not a clock. A message is stored before it is acknowledged, delivered at least once and ignored when the phone already has it. Offline users catch up from the last number they hold.
- Losing the registry sends 28,000 push notifications a second instead of 8,400, 3.3 times as many, and loses no message.
Next: Social feed, where one post must reach a very large number of followers.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.