InterviewDryRun
Lesson 8 · 22 min video · free

Design a Chat App

A chat app has to deliver a message in a fraction of a second when the other person is online, keep it safely when they are not, show sent, delivered and read ticks, and keep every conversation in order across phones and laptops. This lesson designs one-to-one and group chat end to end, covering the full 45-minute interview answer.

What you will learn

  • Keep a persistent connection per device to a gateway, and route messages between gateways.
  • Store the message durably before acknowledging it; delivery comes after.
  • Order messages per conversation with a sequence number assigned by the conversation's owner.
  • Clients sync by asking for everything after the last sequence number they have.
  • Fan out small groups on write; very large groups need a different, pull-based path.
  • Presence is high-volume and lossy: heartbeats with timeouts, fanned out lazily.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: How clients stay connected
  5. Step 4: The high-level design
  6. Step 5: The protocol
  7. Step 6: Message ids and ordering
  8. Step 7: Receipts, offline users and sync
  9. Step 8: Group chats
  10. Step 9: Storing history
  11. Step 10: Photos, videos and voice notes
  12. Step 11: Online status
  13. Step 12: Failures and security
  14. Step 13: The follow-up questions
  15. Recap

Short on time? Read the answer outline for design a Chat App.

Practice this question with Max

The question

Welcome to lesson eight of the InterviewDryRun system design course. Today we design a chat app: one-to-one conversations and group chats, with the little ticks that tell you a message was sent, delivered and read, and with history that follows you from your phone to your laptop.

Chat is a favourite interview question because it is real-time. Most systems we have designed so far answer requests: the client asks, the server replies. In chat, the server has to push messages to a client that did not ask, within a fraction of a second, to hundreds of millions of devices at once. That changes the architecture. And chat users are unforgiving: a lost message, or messages that show up out of order, is a broken product.

Max asks

“Design one-to-one and group chat with delivery receipts, offline users and message history.”

That is how Max, our AI interviewer, asks it. Four things are named: one-to-one and group, receipts, offline users, and history. Each will get its own part of the answer. And there is an unnamed fifth one that every interviewer will ask about: ordering. Messages in a conversation must appear in the same order for everyone.

The plan: requirements and numbers, then how clients stay connected, then the high-level design and the path of one message. Then the deep dives: ids and ordering, receipts, offline users and sync across devices, groups, storage, and presence. And the follow-up questions at the end.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    One-to-one chatText, with images as links to uploaded media
  2. 02
    Group chatUp to a few hundred members
  3. 03
    ReceiptsSent, delivered, read
  4. 04
    Offline deliveryMessages wait, then arrive when you reconnect
  5. 05
    History on every devicePhone, tablet and laptop see the same conversation
  6. 06
    Online statusOnline now, or last seen

Start with questions, and pin down scope, because chat can grow into voice calls, video, stories and payments. Say clearly that you will focus on messaging.

One-to-one and group chat. Ask how big groups can be. A few hundred members is typical. If the interviewer says a hundred thousand, that is closer to a broadcast channel, and needs a different design, which we will touch on later. Media, like photos, is uploaded separately to object storage, and the message just carries a link.

Receipts: sent means our server has the message, delivered means it reached the recipient's device, and read means they opened it. And offline users: if the recipient's phone is off, the message must wait and arrive when they come back, with a push notification in the meantime.

History on every device: a user can have a phone and a laptop signed in at once, and both must show the same conversation, in the same order, including messages sent from the other device. And online status, which sounds tiny but generates a surprising amount of traffic.

Non-functional requirements
  1. 01
    Low latencyUnder 200 ms end to end when both are online
  2. 02
    Never lose a messageOnce sent shows, it is stored
  3. 03
    OrderedSame order in a conversation for everyone
  4. 04
    Highly availableChat is used during emergencies
  5. 05
    SecureEncrypted in transit, ideally end to end

The qualities. Messages between two online users should arrive in well under a quarter of a second. Once the sender sees the single tick, the message must never be lost. And within a conversation, everyone must see the same order.

Availability matters more than people think, because chat is how people reach each other in emergencies. And security: encryption in transit at least, and many apps offer end-to-end encryption, where even our servers cannot read messages. Ask whether that is in scope. Say you will mention how it affects the design, but focus on delivery.

Step 2: Back-of-the-envelope estimates

Sizing the system
Daily active users500 millionabout 1.5 devices each
Concurrent connectionsabout 200 millionat peak
Messages a day50 billionabout 600,000 a second
Peakabout 2 million / sevenings, holidays
Message sizeabout 200 bytesplus metadata
Storageabout 10 TB / daybefore replication

Let us size it.

Say five hundred million daily active users, with about one and a half devices each. At peak, around two hundred million devices are connected at the same moment. That number drives the connection layer: if one server can hold a few hundred thousand open connections, we need roughly a thousand gateway servers just to keep everyone connected.

Messages: say a hundred per user per day, so fifty billion a day, around six hundred thousand a second on average, and a couple of million at peak, on evenings and holidays like new year's eve.

Each message is small, a couple of hundred bytes of text plus ids and timestamps. Fifty billion a day is about ten terabytes a day, several petabytes a year with replication. So history storage is big, append-heavy, and read mostly by recent time. That points to a wide-column or log-structured store, which we will come back to.

And the connection count deserves a second look, because it is unusual. Most services size servers by requests per second. Here, a large share of the cost is simply holding connections open: memory for each connection's buffers and encryption state, and the heartbeats every thirty seconds. Two hundred million connections with a heartbeat every thirty seconds is nearly seven million tiny frames a second before anyone sends a single message. That is why the gateway layer is its own tier, tuned for connections rather than for logic.

Step 3: How clients stay connected

Getting messages to the client
TechniqueHowVerdict
Pollingask every few secondsslow and wasteful
Long pollinghold the request until there is newsworks, but heavy
Server-sent eventsserver streams to clientone direction only
WebSocketone persistent two-way connectionthe usual choice

The first real decision is how the server sends a message to a client that did not ask for it. There are four options, and naming them shows you know why the answer is the answer.

Polling, asking every few seconds whether there is anything new, is simple but either slow or wasteful: poll every second and two hundred million devices create two hundred million requests a second, almost all saying nothing new. Long polling improves it: the server holds the request open until a message arrives. It works, but every message costs a new request and connection setup.

Server-sent events stream from server to client, but only in one direction. A WebSocket gives one persistent, two-way connection: the client sends messages up it and the server pushes messages down it, with very little overhead per message. For chat, that is the standard answer. Mobile apps may use a similar custom protocol over a persistent connection, but the idea is the same.

Persistent connections have a cost: they are stateful. A given device is connected to one specific gateway server. So the rest of the system must know which gateway holds which device, and must handle that gateway going away. Most of the design follows from this one fact.

Also say what keeps connections alive. Mobile networks silently drop idle connections, so the client sends a tiny heartbeat every thirty seconds or so, and reconnects with backoff when the connection breaks. Phones switch between mobile data and Wi-Fi constantly, so reconnects are routine, and the design must make them cheap and lossless.

Step 4: The high-level design

High-level design
send1. store2. where?3. deliverCLIENTSender's phoneEDGEGateway Aholds connectionsSERVICEChat servicestore, sequence, routeSTOREMessage storeby conversationCACHESession registrydevice to gatewayEDGEGateway BCLIENTRecipient

Now the architecture. Every device holds a persistent connection to a gateway server. Gateways are deliberately thin: they terminate connections, authenticate, and pass messages in both directions. They contain no chat logic, so they can be restarted and scaled independently.

When the sender's phone sends a message, its gateway forwards it to the chat service. The chat service is where the logic lives: it validates the message, assigns its place in the conversation, stores it and routes it.

Step one, always, is to store the message durably in the message store. Only after the write succeeds does the chat service acknowledge back to the sender, and only then does the sender's app show the single tick, sent. That ordering is how we keep the promise that a message with a tick is never lost.

Step two: find the recipient. A session registry, an in-memory store, maps every connected device to the gateway that holds its connection. Gateways update it when devices connect and disconnect, with a time to live so entries from crashed gateways expire.

Step three: the chat service sends the message to each gateway holding one of the recipient's devices, and those gateways push it down the open connections. When the device receives it, it acknowledges, and that acknowledgement flows back as the delivered receipt. If the recipient has no connected devices, we send a push notification instead, and the message waits in the store until they reconnect.

An alternative for step three, worth mentioning, is a publish and subscribe layer: each gateway subscribes to a channel per connected user, and the chat service publishes to the recipient's channel. It removes the registry lookup but adds a message broker with hundreds of millions of channels. Either works; the registry approach is simpler to reason about, so I would start there.

Step 5: The protocol

Frames on the connection
client → server
  send    { clientMsgId, conv, body }
  ack     { conv, seq }                 // delivered
  read    { conv, upToSeq }
  ping

server → client
  sent    { clientMsgId, conv, seq }
  message { conv, seq, sender, body }
  receipt { conv, seq, user, state }
  presence{ user, online, lastSeen }

Because the connection is persistent, the API is not a set of web endpoints but a small set of frames sent in both directions over the connection. It is worth writing them down, because they make the rest of the design concrete.

From the client: send a message, with the client's own message id; acknowledge that a message arrived; report how far the user has read in a conversation; and a ping for keeping the connection alive. From the server: confirm that a message was stored, with its sequence number; deliver a new message; deliver a receipt; and presence updates.

A few things are deliberately not on the connection. Uploading photos and videos goes over ordinary web requests to object storage, so large uploads never clog the chat connection. And history sync, catching up after being offline, is an ordinary request too, because it can return a lot of data and benefits from normal caching and pagination. Keep the persistent connection for small, real-time frames.

Step 6: Message ids and ordering

Ordering within a conversation
client sends: { clientMsgId: "c_77a1", conv: "conv_42", text }

chat service (owner of conv_42):
  seq = conv_42.nextSeq++          // 1041
  store (conv_42, seq 1041, msg)
  ack sender { clientMsgId: "c_77a1", seq: 1041 }

every device shows conv_42 sorted by seq

Now ordering, which interviewers always probe. Using timestamps from the phones does not work: phone clocks are wrong, and two messages sent at nearly the same moment can be stamped in the wrong order. Server timestamps are better, but servers' clocks also differ slightly, and two chat servers handling the same conversation could still disagree.

The clean answer is a sequence number per conversation. Each conversation is owned by one chat service instance at a time, chosen by hashing the conversation id. That owner hands out numbers: one, two, three, for each message in the conversation. Everyone sorts by that number, so everyone sees the same order. We do not need a global order across all conversations, which would be impossibly expensive; we only need order within each conversation, which is cheap.

The sender also attaches its own client message id, a random id generated on the phone. If the network drops after sending and the phone retries, the chat service recognises the client id and returns the existing sequence number instead of storing the message twice. That is the idempotency key pattern again, and it is how we avoid duplicate messages on flaky mobile networks.

What if the owner of a conversation fails? Ownership moves to another instance, coordinated with a lease, and the new owner reads the highest stored sequence number before handing out new ones. Because a message is only acknowledged after it is stored, no acknowledged sequence number is ever reused. Say that sentence, because it shows you have checked the failure case of your own design.

Notice that routing every message in a conversation through one owner also makes that owner a potential hot spot. For one-to-one chats and normal groups, a conversation produces at most a few messages a second, so a single owner is nothing. Only giant channels produce heavy traffic through one owner, and that is one more reason to treat them with the separate broadcast design we will discuss under groups.

Step 7: Receipts, offline users and sync

Three ticks
  1. 01
    SentServer stored it and acknowledged the sender
  2. 02
    DeliveredA recipient device acknowledged receiving it
  3. 03
    ReadThe recipient opened the conversation past it

Receipts are themselves small messages travelling the same paths. Sent is the server's acknowledgement to the sender, which we already have.

Delivered is an acknowledgement from the recipient's device, sent back through its gateway to the chat service, which updates the message's status and forwards a receipt to the sender's devices. If the sender is offline by then, the receipt waits like any other message.

Read is not one receipt per message. When the recipient opens the conversation, the device sends one event: read up to sequence one thousand and forty-one. That single number covers every earlier message. Per-message read receipts would multiply traffic for no benefit. In groups, we store each member's read-up-to number, and the sender can see who has read how far.

Sync after being offline
device keeps: lastSeq per conversation

on reconnect:
  GET /sync?since={conv_42: 1012, conv_77: 380, ...}
  → all messages after those numbers,
    receipts, and new conversations

server keeps per user: conversations changed recently

Now offline users and multiple devices, which turn out to be the same problem. Each device remembers, for each conversation, the last sequence number it has. When it reconnects, it asks: give me everything after these numbers. The server answers with the missing messages, in order.

To make that efficient for a user with hundreds of conversations, the server keeps a small per-user list of conversations that changed recently, with their latest sequence numbers. The device compares, and only fetches conversations that actually moved. A phone that was off for a weekend catches up in one or two requests.

This sync model is what makes multiple devices easy. A message sent from your laptop is stored in the conversation like any other, and your phone picks it up through the same sync, or immediately if it is online. There is no special case for your own devices: they are just more recipients of the conversation.

Step 8: Group chats

Delivering to groups
Group sizeApproachWhy
Up to a few hundredfan out on write: deliver to each membercheap, instant
Thousandsfan out in batches through a queuesmooth the burst
Huge channelsmembers pull recent messagesfan-out would be millions of pushes

Groups reuse everything. A group is a conversation with more members. The message is stored once, with one sequence number, and the chat service looks up the members and delivers to each member's connected devices. For groups of a few hundred, that is a few hundred pushes per message, which is fine.

For larger groups, a single message would block the conversation owner while it fans out to thousands of members. So put the fan-out on a queue: the owner stores and sequences the message, then hands delivery to workers. The message is already safe and ordered; delivery can take a moment longer.

And for huge broadcast channels, with hundreds of thousands of members, do not push every message to every member at all. Notify members cheaply that the channel has new messages, and let their devices pull the latest when they open it. This is the same push versus pull trade-off we saw in the news feed lesson, and it is worth saying so: you are recognising a pattern, not inventing a one-off.

Membership changes deserve a sentence. When someone joins a group, should they see earlier history? Usually only from the point they joined. So membership changes are themselves messages in the conversation, with sequence numbers, and a member's view starts at the sequence of their join message. That also makes removed members simple: messages after their removal are never delivered to them.

Step 9: Storing history

messages (partitioned by conversation)
ColumnTypeWhy
conversation_idpartition keyall of a chat in one place
seqclustering key, descendingnewest first, range reads
sender_idid
client_msg_ididdeduplicate retries
bodybytestext or media link; ciphertext if end-to-end
created_attimestampdisplay only, not ordering

History storage has a very clear access pattern: write messages to a conversation in order, and read the most recent ones, then older ones as the user scrolls up. So partition by conversation id, and sort within the partition by sequence number, newest first.

A wide-column store fits this perfectly: writes are appends, the latest page of a conversation is one contiguous read, and it scales horizontally to petabytes. Note that the created time is only for display. Ordering always uses the sequence number.

One trap to mention: a very old, very busy group chat could grow one partition to an enormous size. Bucket long conversations by time, for example one partition per conversation per month, so no single partition grows without limit. Reading recent history then touches only the latest bucket.

And a policy question: do we keep messages forever? Ask. Some apps keep history only on devices, deleting from the server after delivery, which makes end-to-end encryption easier and storage tiny. Others keep everything in the cloud, which makes new devices easy to set up. Each is a valid product choice; say which you assume and how it changes storage.

Step 10: Photos, videos and voice notes

Media in messages
  1. 01
    Upload firstSigned URL to object storage, then send a message with the link
  2. 02
    ThumbnailsA tiny preview travels inside the message
  3. 03
    Download on demandThrough a CDN, when the user opens it
  4. 04
    Encrypted blobsWith end-to-end encryption, the key travels in the message

Media is most of the bytes in a chat app, so handle it outside the message path. The sender's app uploads the photo to object storage using a signed upload link, then sends an ordinary message containing the link and some metadata. The message stays small, and the chat servers never touch the large file.

So that the recipient sees something immediately, the message carries a tiny, blurry thumbnail, a few hundred bytes, inline. The full image is downloaded through a content delivery network when the user opens the conversation, or automatically on Wi-Fi.

With end-to-end encryption, the sender encrypts the file with a random key before uploading, and puts that key inside the encrypted message. Storage holds only scrambled bytes, and only the recipients can decrypt them. It is a neat example of how the media path and the message path work together without the server ever seeing content.

Forwarded media is common: the same funny video sent through thousands of chats. Without encryption, we can deduplicate by content hash and store it once. With encryption, each copy has its own key, so deduplication is limited. Mention it as a cost trade-off of end-to-end encryption, which interviewers find a thoughtful point.

Step 11: Online status

Presence without melting the servers
  1. 01
    HeartbeatsOnline while heartbeats arrive; offline after a timeout
  2. 02
    StoreIn-memory map: user to last seen
  3. 03
    Lazy fan-outOnly send status to people looking at that chat
  4. 04
    DebounceIgnore flapping on a bad network

Online status looks trivial and is not. Every user's status changes many times a day, and each change could interest hundreds of contacts. Pushing every change to every contact would be billions of updates a day that nobody reads.

So keep presence in an in-memory store, updated by the gateways from the heartbeats they already receive: last seen at this time. A user is online if a heartbeat arrived within the last minute or so.

And fan it out lazily. Only push a status change to users who are currently looking at a conversation with that person. Everyone else reads the status when they open the chat. Add debouncing, so a phone flipping between networks does not produce a stream of online, offline, online. Presence is allowed to be slightly wrong; treat it as best effort and say so.

Step 12: Failures and security

What breaks
  1. 01
    Gateway diesClients reconnect elsewhere and sync from last seq
  2. 02
    Chat owner diesLease moves; new owner continues the sequence
  3. 03
    Region outageClients connect to another region; store replicated
  4. 04
    DeploysDrain gateways slowly to avoid reconnect storms

If a gateway dies, its hundreds of thousands of clients notice their connection drop, reconnect to other gateways, and sync from their last sequence numbers. Nothing is lost, because nothing lived only on the gateway. That is the payoff of keeping gateways thin.

If a chat service instance dies, its conversations move to others through leases, as we discussed, and sequencing continues from the stored maximum.

For a whole region, clients reconnect to the next region and the message store is replicated across regions. And one operational point interviewers like: when deploying gateways, drain them slowly, a few at a time, with randomised reconnect delays on clients. Dropping a million connections at once creates a reconnect storm that can overload authentication and sync.

On security, mention end-to-end encryption briefly. If it is required, devices exchange keys, and the server stores and forwards ciphertext it cannot read. The routing, sequencing, receipts and sync all still work, because they only need metadata. What changes is that server-side features, like search over message text, must move onto the devices.

Step 13: The follow-up questions

Max asks

“Two people in a group send a message at exactly the same moment. What order do members see?”

Whichever reaches the conversation's owner first gets the lower sequence number, and every member sees that order. It may not match the order the two people pressed send, but it is the same for everyone, which is what matters. Each sender's own message appears in their app immediately with a pending state, and then moves into its final position once the sequence number comes back.

Max asks

“How do you send a push notification without showing it twice when the user is also online on their laptop?”

Check the session registry first. If any of the user's devices is connected and has acknowledged the message, skip the push. If only the laptop is online, we might still push to the phone, but mark it so that opening it on one device clears it on the others. A short delay before pushing, a second or two, avoids notifying for messages the user already saw on an active device.

Max asks

“How would you add message search?”

Without end-to-end encryption, index messages asynchronously into a search index partitioned by user, fed from the same stream of stored messages, so the send path stays fast. With end-to-end encryption, the server cannot read messages, so search runs on the device over its local history. Say the trade-off clearly: server search is better and works across devices, device search preserves privacy.

Max asks

“A user deletes a message for everyone. How does that work?”

The delete is itself a new message in the conversation, with its own sequence number, saying hide message one thousand and forty-one. Every device applies it when it arrives or when it syncs, and the server marks the original as deleted. Devices that were offline learn about it in their normal sync. Treating edits and deletes as new events, rather than changing old ones, keeps ordering and sync simple.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsOne-to-one, groups, ticks, offline, multi-device
  2. 02
    5 to 10: estimates and connections200 M connections; WebSockets on thin gateways
  3. 03
    10 to 20: the message pathStore, then registry lookup, then push; ack on store
  4. 04
    20 to 35: deep divesPer-conversation sequence, receipts, sync, groups
  5. 05
    35 to 45: storage and failureWide-column by conversation, presence, reconnects

On the clock: five minutes of requirements, including receipts, offline users and multiple devices. Five minutes of numbers and the connection decision: hundreds of millions of persistent connections on thin gateways.

Ten minutes on the path of a message: store durably, acknowledge, look up the recipient's gateways, push, and fall back to a push notification when they are offline.

Fifteen minutes on ordering with per-conversation sequence numbers, receipts as small messages, and sync by last sequence number, which handles both offline users and multiple devices. And the final ten on groups, storage, presence and failures. If your answer keeps returning to two ideas, store before acknowledging, and order per conversation, the interviewer will trust the rest.

Chat answers often get lost in connection details and never reach ordering and sync. Practicing out loud is how you learn to pace it. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson nine.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.