Design a Chat System
Ch. 13 Case Studies System designThe problem
A chat system moves a short piece of text from one person to another, keeps a copy you can scroll back to, and tells you whether the other person is there right now. Everyone uses one, and yet the three jobs — deliver, persist, track presence — pull in different directions, so the design has to decide explicitly how they trade off.
The hardest constraint is that the recipient is a device, not a server: it may be asleep, offline, or on another network. So the system must know when a message can be pushed straight through and when it has to be held and handed over later.
Today you will build one: scope the problem, pick a transport that does not burn the battery, design the message server, model the data, track presence, and wire the delivery path end to end.
Requirements
Functional — what it must do
- One-to-one direct messages between two users, with a running history you can open at any time and scroll back through.
- A message sent while the recipient is online arrives in under about half a second; sent while offline, it is delivered on the recipient's next connection, in order.
- Show who is online, and mark each message as sent, delivered, or read.
- Group chat: one sender, many recipients, with the sender's copy and every recipient's copy staying in order and in sync.
Non-functional — how well it must do it
- Latency: p99 delivery to an online recipient under 300 ms at the edge, most of it network.
- Durability: no sent message is lost, whether the server or the recipient fails mid-flight.
- Scale: tens of millions of simultaneous open connections, each a live session that must be kept cheap in memory.
- Ordering: messages from a sender arrive in the order sent; a recipient's outbox drains first-in-first-out.
Scale — how much it must take
- 10,000,000 users online at peak, sending about 50,000 messages per second in total; reads run roughly five times the write rate.
Assumptions — the numbers this design is sized for
A rate limit means nothing without a scale. These are the figures every later part relies on: how much traffic arrives, how much work the limiter has to do per second, and how much latency and memory it may spend doing it.
Takeaways
- Scope first: 1:1, group, and room chat all reuse the same server, storage, and presence — only the delivery fan-out changes.
- Pick the transport deliberately: WebSockets for low-latency push, with the price of per-socket memory sized into the fleet.
- Make the chat server stateless so a dead node's clients reattach elsewhere without losing a message.
- Key messages by conversation, not user, and keep the last hundred hot in cache for sub-millisecond reads.
- Presence is its own service, kept honest by heartbeats with a grace window, sharded by user id.
- One write, two roads: online recipients get a push, offline recipients get an outbox entry drained first-in-first-out on reconnect.
- A sequence number (or a snowflake id) is what keeps order intact across pushes, queues, and reconnects.
Scope: who is talking to whom
A 'chat' system can be a phone text, an office room, or a game lobby. The design changes a lot between them, so pin down which one you are building.
- 1Three different chats
A phone app like Messenger is mostly one-to-one. An office tool like Slack is mostly groups and channels. A game lobby like Discord wants many-to-many with very low latency. Each one stresses a different part of the design.
- 2Pick the hard one
We scope to one-to-one with a running history and presence, the common core. If it must also do groups, the only real change is delivery: one message fans out to many recipients instead of one. Everything else — server, storage, presence — stays the same.
Getting it across the wire
How does the recipient's phone learn a message is waiting? Polling burns battery; a held connection costs server memory. The choice is the whole story of a chat app.
- 1Short polling
The naive idea: the client asks 'anything for me?' every few seconds. It is simple and stateless, but an idle client still wakes every interval, so 10,000,000 phones × a request every 5 seconds is a flood of empty round trips and dead battery.
- 2Long polling
Better: the client asks, and the server holds the request open until a message arrives or a timeout hits, then the client immediately asks again. The phone sleeps until it has work, so empty polls disappear — at the cost of one held request per client.
- 3WebSockets
The modern default: open one persistent, full-duplex connection and let the server push the moment a message is ready. No polling at all, lowest latency. The price is real server memory per open socket — 10,000,000 of them — which is why the chat fleet is sized around connection state, not CPU.
The message server
A stateless fleet of chat servers sits in front of the data. Each one owns a slice of the live connections and a slice of the stores behind it.
- 1A stateless fleet
Many identical chat servers sit behind a load balancer. A client's connection is pinned to one server, which routes that client's messages to the stores. 'Stateless' means no server is special: if one dies, its clients reconnect elsewhere and pick up where they left off.
- 2What each one owns
Each chat server holds the live sockets of its assigned users, the hot cache of their last hundred messages, and a small outbox for anyone currently offline. It is the outbox — not the live socket — that makes delivery reliable when the recipient is away.
- 3Why it is stateless
The server keeps no long-lived per-user record of its own: the source of truth is the shared message store, and the outbox is just a queue it can rebuild. That is what lets a dead server's clients be reattached to a live one without losing a single message.
The data model
Four tables carry a chat system: people, conversations, messages, and the offline backlog. How they key decides how you shard.
- 1The four tables
A user is a row with an id and a presence flag. A conversation is a row per pair (or group) of users. A message belongs to a conversation, has a sender, a body, a time, and a delivery state. An outbox row is a message queued for a recipient who is offline.
- 2Key messages by conversation
Every message is stored under its conversation id. That is the unit people actually open: to read a chat you pull one conversation's rows, not a user's. It also means a conversation between two heavy users and one between two light users cost nothing different to look up.
- 3The outbox is the reliability anchor
The outbox row is written in the same step as the message itself. If the recipient is online it is pushed immediately and the outbox entry cleared; if offline it simply waits, and is drained in order the next time the recipient connects. One write, two consumers, no message left behind.
Presence: who is online
Knowing the recipient is online is what turns a slow 'store and forward' into a fast push. It is a service of its own, updated by heartbeats.
- 1A presence service
A small service answers one question: is this user connected right now? The chat servers report their clients to it, and it holds a live map of user → online. When a message is routed, that lookup decides push-versus-outbox in a single millisecond.
- 2Heartbeats keep it honest
A socket can die silently, so presence cannot be inferred from a connection existing. Each client sends a heartbeat; the presence service marks a user offline if the heartbeat stops for a couple of intervals. That grace window absorbs a dropped packet without falsely showing someone as gone.
- 3Scale presence by user hash
The presence map is a key-value store sharded the same way as everything else: hash the user id and every heartbeat, lookup, and expiry lands on the same shard. No cross-shard traffic, and a user's presence is exactly as local as their messages.
Delivery: online push, offline queue
The same message takes two different roads depending on the recipient's presence. Group chat is the same idea with more recipients on the receiving end.
- 1Online: straight through
Alice sends a message. The router checks presence, sees Bob is online, and the server holding Bob's socket pushes it over his live connection. Total path is one hop to the store plus one push — well inside the 300 ms budget.
- 2Offline: into the outbox
If Bob is away, the router writes the message to his outbox instead of pushing. The moment he reconnects, the server drains his outbox in order, so he receives it then — and in the correct sequence relative to everything else he missed.
- 3Group: fan out on write
For a group message the router checks presence for every member. Online members get a push; offline members each get an outbox entry. Fanning out on write (not on read) is what keeps the recipient's device simple — it never has to ask 'was this for me?'
- 4Order is preserved
Because the outbox is a first-in-first-out queue drained on connect, and because every message carries a sequence number the client sorts by, the recipient sees Alice's messages in the order she sent them — whether they arrived live, a minute late, or interleaved with a reconnect.
End to end
One message, both roads: Alice writes, the server stores it, presence decides, and Bob receives it live while his offline friend gets it queued. That is the whole system in one picture.
- 1The whole system
Everything in one diagram. A client fleet talks over WebSockets to a stateless chat-server pool, which reads a presence service and writes to sharded message stores and per-user outboxes. The hot cache serves the last hundred messages of any conversation in a millisecond.
- 2Alice sends to Bob
Alice's message arrives at the server that owns her socket. It is written to the message store under the conversation id, a sequence number is assigned, and the router asks presence: is Bob online?
- 3Bob is online — pushed
Presence says yes. The server that owns Bob's socket pulls message 4821 and pushes it down his live WebSocket. He sees it, marks it read, and the read receipt travels back the same way. End to end, well under 300 ms.
- 4Carol is offline — queued
The same message also went to Carol, who is in a group with them. Presence says offline, so it lands in her outbox. She is on the subway with no signal; nothing is lost, it is just waiting, in order, for her next connection.
- 5Carol reconnects — drained
Carol's phone gets signal and opens a socket. The server sees her, checks presence, and drains her outbox first-in-first-out: message 4821 and everything else she missed arrive in order. Her read receipt confirms it. The system delivered both roads with the same write.
In the wild
The same three pieces — a push transport, a store-and-forward outbox, and a presence service — are what real messaging products run on. Here is where each shows up.
- 1These products run this design
Everything you just built is production messaging. The push-versus-outbox split, the presence service, and the per-conversation store are exactly the pieces the big chat products are built from. Let's match the diagram to the names.
- 2Messenger: fan-out at scale
Facebook's own engineering write-up describes exactly the fan-out-on-write pattern you built: a message to a conversation is written once and fanned out to each recipient's inbox, with online users pushed and the rest queued. That is your delivery section, at planetary scale.
- 3Discord: ids you can sort
Discord's messaging is famous for how it assigns ids. Rather than a database auto-increment, each message id is a snowflake — time, machine, and sequence packed into one big integer — so 'newer' is just 'larger' and no coordinator is needed to order a billion messages. That is your sequence-number idea, hardened for scale.
- 4Slack: an edge cache
Slack wrote about 'Flannel', an edge cache that sits in front of its origin to make it scale. That is your hot-cache layer — the last hundred messages served from the edge instead of a round trip to the store — used to keep a huge read rate from stampeding the database.
- 5WhatsApp and WeChat: the two extremes
WhatsApp's story is the transport and the trust: end-to-end encryption means the servers can queue and deliver your message without ever reading it. WeChat's story is the opposite pressure — one app that is also payment, a mini-app store, and a social graph. Both ride the same push/outbox skeleton you designed; they just lean on different parts of it.