Case studies

Design a chat system

Deliver messages between people in real time, in order and exactly once from the user's point of view, across phones that are offline half the time and users with several devices.

Case study25 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

HTTP is request and response: the client asks, the server answers. Chat needs the opposite. When Alice sends Bob a message, the server must tell Bob, and Bob did not ask. Early web chat faked this with polling, in which every client asks “anything new?” every few seconds. With a million users polling every three seconds, that is over 300,000 requests a second, nearly all answered with “no”, and messages still arrive up to three seconds late.

Persistent connections fix the latency and create a different problem. A server now holds state: Bob’s socket lives on one particular machine out of hundreds, and whichever machine receives Alice’s message has to find it. Phones make it harder. Mobile operating systems suspend background apps and close their sockets, networks drop between cell towers, and one person may have a phone, a laptop and a tablet that all need the same history.

Interviewers use this question to test whether you can design around stateful connections, give a clear answer on ordering and duplicates, and handle the offline case as the normal case.

Requirements

Functional

  • One-to-one messaging and group chat, with groups up to about 500 members.
  • Messages are delivered in real time when the recipient is online, and when they next connect otherwise.
  • Sent, delivered and read receipts.
  • Online and last-seen presence.
  • Several devices per user, each with the full conversation history.
  • Push notifications to offline devices.

Out of scope unless asked: media attachments (upload to object storage and send a reference), voice and video calls, search, and end-to-end encryption, which is discussed as an extension.

Non-functional

  • Latency: an online recipient receives a message within about 500 ms.
  • Durability: an acknowledged message is never lost.
  • Ordering: every participant sees a conversation in the same order.
  • No visible duplicates, even when clients retry.
  • Availability: 99.99%. If real-time delivery degrades, messages must still arrive later.
  • Scale: 100 million daily active users.

Capacity estimates

Quantity Working Result
Messages 100M users x 40 a day / 86,400 about 46,000 per second, 140,000 at peak
Message storage 4B a day x 200 bytes 800 GB a day, about 290 TB a year
Open connections 25% of daily users online at peak 25 million
Gateway servers 25M / 250,000 connections each 100, plus headroom
Gateway memory 250,000 connections x 10 KB 2.5 GB per server
Heartbeats 25M connections / 30 seconds about 830,000 per second

The conclusions: the message rate is high and append-only, which suits a store built on LSM trees. The number of connections, not the number of messages, sets the size of the gateway fleet. And heartbeats outnumber messages by more than ten to one, so presence must be cheap.

API

Real-time traffic uses a WebSocket: one TCP connection, opened with an HTTP upgrade and authenticated once, over which either side can send frames at any time.

client -> server   { "type": "send", "client_msg_id": "c81f...", "conversation_id": "c_77", "body": "On my way" }
server -> client   { "type": "ack", "client_msg_id": "c81f...", "seq": 42, "sent_at": "2026-03-01T09:30:00Z" }
server -> client   { "type": "message", "conversation_id": "c_77", "seq": 42, "sender_id": "u_1", "body": "On my way" }
client -> server   { "type": "receipt", "conversation_id": "c_77", "delivered_up_to": 42, "read_up_to": 40 }
client -> server   { "type": "sync", "cursors": { "c_77": 37, "c_12": 9 } }

The client generates client_msg_id before the first attempt and reuses it on every retry. Ordinary HTTPS endpoints cover everything that is not real-time: GET /v1/conversations/{id}/messages?before_seq=38&limit=50 for scrolling back through history, creating groups, and registering a device’s push token.

Data model

Store Key Contents
Messages conversation_id and time bucket, then seq sender, client id, body, sent time
Conversations conversation_id type, title, last_seq
Members by conversation and by user role, the user’s read_up_to
Device cursors user_id, device_id, conversation_id delivered_up_to
Session registry user_id device id to gateway id, with a TTL

A message is stored once per conversation, not once per recipient. In a 500-member group that is one row and not 500.

The message table is append-heavy and always read as “one conversation, a range of sequence numbers”. A wide-column store such as Cassandra, ScyllaDB or HBase fits: partition by conversation, cluster by sequence. A busy conversation would grow one partition without limit, so add a time bucket to the partition key. Discord has described this layout, with a bucket of about ten days, for its message store.

High-level architecture

Chat system reference architecture11 components: Load balancer, Presence store, Phones and browsers, WebSocket gateways, Session registry, Message store, Chat service, APNs and FCM, Push workers, Push queue, Conversation store. Connections: Phones and browsers to Load balancer (WebSocket); Load balancer to WebSocket gateways; WebSocket gateways to Presence store (heartbeats); WebSocket gateways to Session registry (register device); WebSocket gateways and Chat service (send and deliver); Chat service to Session registry (where is Bob?); Chat service to Message store (append message); Chat service to Conversation store (members, next seq); Chat service to Push queue (if offline); Push queue to Push workers; Push workers to APNs and FCM; APNs and FCM to Phones and browsers (wake the device); Load balancer to Chat service (history over HTTPS).Load balancerlong-lived connectionsPresence storekeys with a TTLPhones andbrowsersWebSocketgatewayshold the connectionsSessionregistrydevice → gatewayMessage storewide-columnChat serviceorder, persist, routeAPNs and FCMPush workersPush queueConversationstoremembers, cursorsWebSocketheartbeatsregister devicesend and deliverwhere is Bob?append messagemembers, next seqif offlinewake the devicehistory over HTTPS
Chat system reference architecture

Connecting. A device opens a WebSocket through the load balancer to any gateway. The gateway authenticates the token, writes “this device is on this gateway” to the session registry, and marks the user online in the presence store.

Sending. The sender’s gateway forwards the frame to the chat service. The chat service checks membership, assigns the next sequence number for the conversation, appends the message to the message store, and acknowledges to the sender.

Delivering. For each member, the chat service looks up connected devices in the registry and calls the gateway that holds each socket. The gateway writes the frame, and the device acknowledges with a receipt.

Offline. For devices with no session, the chat service puts a job on the push queue. Push workers call APNs or FCM, which wake the device. See the notification service for that path in full.

Catching up. On every connect, a device sends its cursors. The chat service compares them with each conversation’s last_seq and returns what is missing. Older history is fetched over HTTPS on demand.

Deep dives

Connections and routing

Gateways and the chat service are separate for a practical reason. Dropping a gateway process drops every socket on it, and all those clients reconnect at once. So gateways should contain as little logic as possible and be deployed rarely. The chat service has the logic that changes weekly, and it is stateless, so it can be deployed at any time.

The load balancer only matters at connection time. It should balance by least connections, because connections last for hours and round-robin leaves new servers nearly empty.

Routing uses the session registry. An entry can be wrong: the gateway may have died, or the phone may have walked into a lift. The design tolerates that because routing is an optimisation on top of storage. If the gateway call fails, the device is treated as offline. The message is already in the store, and the device will fetch it when it reconnects.

An alternative is publish and subscribe: each gateway subscribes to a channel per connected user, and the chat service publishes without a lookup. It is simpler to reason about and puts more load on the broker.

When a gateway dies, 250,000 clients reconnect. They must use exponential backoff with jitter (retries and timeouts), or the reconnect wave and its sync requests overload the remaining gateways and the chat service. For a planned deploy, drain gradually by asking clients to reconnect elsewhere over several minutes.

Ordering and delivery guarantees

One chat message, from send to delivered on every device9 components: Alice's phone, Gateway 1, Message store, Chat service, Bob's phone, Gateway 2, Session registry, APNs or FCM, Bob's tablet. Connections: Alice's phone and Gateway 1; Gateway 1 and Chat service; Chat service to Message store (append); Chat service to Session registry (lookup); Chat service and Gateway 2; Gateway 2 and Bob's phone; Chat service to APNs or FCM (push); APNs or FCM to Bob's tablet.Alice's phoneoutbox holds 1Gateway 1Message storeChat serviceBob's phoneonlineGateway 2SessionregistryAPNs or FCMBob's tabletofflineappendlookuppush

Step 1 of 9

Alice sends a message to Bob. Before sending, her phone gives the message a random id of its own and keeps a copy in a local outbox until the server confirms it.

Read the steps as text
  1. Alice sends a message to Bob. Before sending, her phone gives the message a random id of its own and keeps a copy in a local outbox until the server confirms it.
  2. Gateway 1 only holds connections. It forwards the frame to the chat service, which checks that Alice belongs to this conversation and assigns the next sequence number, 42.
  3. The chat service appends the message to the message store, and acknowledges only after the write is durable. If a server crashed before this point, Alice's phone would simply send again with the same id.
  4. The acknowledgement carries the sequence number back. Alice's phone clears its outbox and shows the message as sent. If the acknowledgement were lost and she retried, the server would recognise the id and return 42 again without storing a duplicate.
  5. Now delivery. The chat service asks the session registry where Bob is connected. Bob's phone has a WebSocket open on gateway 2. His tablet has no connection at all.
  6. The chat service hands the message to gateway 2, which writes it down Bob's socket. Bob's phone compares the sequence number with the last one it holds. It had 41 and now receives 42, so nothing is missing.
  7. Bob's phone acknowledges everything up to 42. The server advances that device's cursor and sends Alice a delivery receipt. This is a second acknowledgement, separate from the one that told Alice the server had stored her message.
  8. The tablet is offline, so the chat service asks APNs or FCM to wake it with a push notification. The push is a hint and not the message. It can arrive late, or never.
  9. When the tablet next connects, it reports its own cursor, 37, and the server returns messages 38 to 42 from the store. Every device catches up from the durable log, so delivery never depends on a push arriving.
One chat message, from send to delivered on every device

Order. Sender timestamps cannot be trusted, because phone clocks differ. The server assigns each message the next sequence number in its conversation. Everyone sorts by that number, and a device that holds 41 and receives 43 knows 42 is missing. Assigning gap-free numbers needs one writer per conversation at a time. Route all sends for a conversation to the same partition or chat shard, keep the counter there, and recover it from last_seq after a restart.

No loss. The chat service acknowledges only after the write is durable. If anything fails before that, the sender has no acknowledgement and retries.

No duplicates. Retries mean a message can arrive twice. The server stores client_msg_id with the message and, on a repeat, returns the original sequence number. Receivers ignore any sequence number they already hold. Delivery is at least once, and both ends are idempotent, so users see each message once.

Receipts. “Delivered” and “read” are stored as cursors, not as a flag per message. “Delivered up to 42” is one small write however many messages it covers. In a group, the sender’s client compares members’ cursors with a message’s sequence number to show who has read it. Large groups usually turn receipts off, because every read would fan out to every member.

Offline delivery, devices and presence

Push is a hint. APNs and FCM are best effort: a notification can be delayed, collapsed with others or dropped. The push says “you have a message”, and the app connects and syncs from the store.

Several devices. Each device has its own connection and delivery cursor. A message Alice sends from her phone is delivered to her laptop exactly as it is to Bob. The read cursor is per user, so reading on one device clears the badge on the others.

Groups. Delivery in a 500-member group is up to 500 registry lookups and gateway calls for one stored message. That is fine at this size. For channels with tens of thousands of members, stop pushing to everyone. Deliver in real time only to members who have the channel open, and let the rest see an unread count when they next sync.

Presence. A user is online while a key with a TTL of about a minute exists in the presence store. Gateways refresh it in bulk for all their connections, not once per heartbeat. Letting the key expire, instead of deleting it on disconnect, gives a grace period so a phone changing networks does not flicker offline and online. Do not broadcast presence to every contact: a user with a thousand contacts would cause a thousand messages each time they open the app. Clients subscribe to presence only for the contacts currently on screen.

End-to-end encryption changes less of this design than you might expect. With a protocol such as Signal’s, which WhatsApp has used for all chats since 2016, devices hold the keys and the server stores and routes ciphertext. Sequencing, routing and sync are unchanged. What the server loses is the ability to read content, so search, link previews and spam filtering move to the client, and each message is encrypted separately for every recipient device. See encryption.

Bottlenecks and failure modes

  • Gateway crash. Sockets drop, clients reconnect with jitter to other gateways and sync. Registry entries for the dead gateway expire by TTL.
  • Session registry lost. Every user looks offline, so messages are stored and pushed but not delivered in real time. Gateways re-register their connections on the next heartbeat.
  • Slow client. A phone on a weak network cannot drain its socket. Give each connection a bounded send buffer, and when it fills, close the connection and let the client resync. See backpressure.
  • Hot conversation. A very active group concentrates writes on one partition and one sequence counter. Time buckets bound the partition, and the group size limit bounds the fan-out.
  • Push provider outage. Offline devices are not woken. Messages wait in the store and arrive when the user opens the app.
  • Chat service crash between store and deliver. The message is durable but nobody was told. The sender retries and gets the same sequence number, and recipients pick it up on their next sync, so run a periodic sync on idle connections too.

Trade-offs

Decision Chosen Alternative Why
Transport WebSocket Long polling Server can push at once with low overhead; stateful servers complicate deploys
Ordering Sequence number per conversation Time-ordered ids Gap detection and simple sync; needs one writer per conversation
Storage One copy per conversation, cursors per device An inbox per recipient Cheap for groups and full history; sync touches many conversations
Routing Registry lookup and direct call Pub/sub channel per user Targeted and easy to observe; entries can be stale
Receipts Cursors Status per message One write covers many messages; no per-message read time

45-minute interview script

A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.

  1. 0:00 to 5:00

    Requirements 5 min

    Confirm one-to-one and group chat, the maximum group size, whether history is kept on the server, receipts, presence and multiple devices. Park media and end-to-end encryption as extensions. State the delivery latency target.

  2. 5:00 to 9:00

    Capacity estimates 4 min

    Derive messages per second, storage per year, concurrent connections and the number of gateway servers. Point out that heartbeats outnumber messages.

  3. 9:00 to 13:00

    API 4 min

    A WebSocket with a small set of frame types (send, ack, message, receipt, sync), plus HTTPS for history and group management. Explain the client-generated message id.

  4. 13:00 to 17:00

    Data model 4 min

    Messages partitioned by conversation and ordered by sequence number, membership in both directions, per-device cursors, and the session registry in a cache.

  5. 17:00 to 25:00

    High-level design 8 min

    Draw clients, load balancer, gateways, session registry, chat service, message store and the push path. Narrate one message from the sender's tap to the recipient's screen, then the offline case.

  6. 25:00 to 31:00

    Deep dive: connections and routing 6 min

    Why gateways are separate from chat logic, how the registry maps a device to a gateway, what happens when the entry is stale, and how deploys and crashes cause reconnect storms.

  7. 31:00 to 38:00

    Deep dive: ordering and delivery guarantees 7 min

    Server-assigned sequence numbers per conversation, deduplication with the client id, the two acknowledgements, sync by cursor, and receipts as cursors.

  8. 38:00 to 43:00

    Offline, presence, failures and trade-offs 5 min

    Push as a hint, multi-device sync, presence with a TTL and limited fan-out, gateway loss, slow clients. Mention end-to-end encryption and what it changes.

  9. 43:00 to 45:00

    Wrap-up 2 min

    Summarise the design. The store is the source of truth, sockets are an optimisation, and every device catches up by cursor.

Sketch this design on the whiteboard Run it as a timed mock

Key takeaways

  • Separate the servers that hold connections (gateways) from the service that orders, stores and routes messages. Gateways are stateful and simple, the chat service is stateless and complex.
  • A session registry maps each connected device to its gateway. It can be stale, and that is safe because the message is already stored.
  • Assign a sequence number per conversation on the server. Clients use it to order messages, detect gaps and ask for everything after a cursor.
  • Persist before acknowledging. A client-generated id makes retries idempotent, so at-least-once delivery looks like exactly-once to users.
  • A push notification is a hint to wake the app, never the delivery mechanism. Offline devices catch up from the message store when they reconnect.
  • Delivered and read receipts are cursors ("up to sequence 42"), so one small write covers any number of messages.
  • Presence is high-volume and low-value. Expire it with a TTL and send updates only to users who are looking.

Check yourself

1. Alice sends a message, the server stores it, and the acknowledgement is lost on a bad network. Her app retries. What prevents Bob from seeing the message twice?
2. The session registry says Bob's phone is on gateway 7, but gateway 7 crashed ten seconds ago. What should happen to a message for Bob?
3. Why assign sequence numbers per conversation on the server instead of ordering by the sender's timestamp?
4. With 25 million open connections and a heartbeat every 30 seconds, roughly how many heartbeats per second arrive, and what does that imply?
5. A user has a phone and a laptop. They read a conversation on the phone. How does the laptop's unread badge clear?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

Why split WebSocket gateways from the chat service?

Gateways hold millions of long-lived connections and little logic, so they are rarely deployed. The chat service is stateless and changes often. Splitting them means a logic deploy does not drop connections.

What is the session registry?

A cache that maps each connected device to the gateway holding its socket, with a TTL refreshed by heartbeats. The chat service consults it to route a message to the right gateway.

What are the two acknowledgements in chat delivery?

Server to sender, after the message is durably stored (sent). Recipient device to server, after it has received the message (delivered). A read receipt is a third signal, sent when the user views it.

How does a device catch up after being offline?

It sends its last sequence number per conversation, and the server returns everything after that from the message store. Push notifications only prompt it to connect.

How do you stop presence updates overwhelming the system?

Keep presence as a key with a TTL refreshed in bulk by gateways, add a grace period before showing offline, and send changes only to users who currently have that contact on screen.

What changes with end-to-end encryption?

The server routes and stores ciphertext it cannot read, keys live on devices, and each message is encrypted for every recipient device. Server-side search and content filtering are no longer possible.

Review the deck