Design a Chat App

How a chat app routes messages to connected users, keeps one order per conversation, delivers to offline users and shows receipts and presence.

Case study28 minLesson 5 of 7
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A chat app lets users send text messages to one person or to a group, shows each message to the recipients within a fraction of a second, and keeps messages for recipients who are offline until they return. It also shows receipts (sent, delivered, read) and whether a contact is online.

It is a common interview question because it needs what request-and-response designs do not: millions of long-lived connections, routing a message to the server that holds the recipient's connection, one agreed order in every conversation, and a clear meaning for "delivered". Read Realtime Communication first if WebSockets are new to you. The steps follow A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design a chat app like the ones on your phone.

You

Do we need one-to-one chats and groups, and how large can a group be? Do we need read receipts and an online status?

Interviewer

Groups can have up to 200 people. Yes to receipts, and yes to an online or last-seen indicator.

You

One device per user, text only? And how many daily users and messages?

Interviewer

Yes to both. Assume 50 million daily active users sending about 40 messages each per day.

You

Then my priorities are these. A message acknowledged to the sender is never lost, everyone in a conversation sees the same order, and delivery to an online user takes well under a second. Online status may be a few seconds stale. I will leave out encryption, search and media.

  • Functional requirements: one-to-one and group messages (up to 200 members), delivery to users who were offline, history, sent, delivered and read receipts, and online and last-seen status.
  • Non-functional requirements: an acknowledged message is never lost, each conversation has one agreed order, delivery to an online user takes under 500 ms, sending is 99.99% available, and online status may be a few seconds stale.
  • Out of scope: end-to-end encryption, search, media and multiple devices per user.

Estimate the scale

  • Messages sent: 50 million users × 40 messages is 2 billion messages a day. Dividing by 86,400 seconds gives about 23,000 a second, and a peak of three times the average is about 70,000 a second.
  • Messages delivered: assume 80% of messages go to one person and 20% go to a group with 20 other members on average. The average message then has 0.8 × 1 + 0.2 × 20 = 4.8 recipients, which gives about 110,000 deliveries a second on average and 330,000 at the peak.
  • Connections: if 20% of daily users are connected at the peak, that is 10 million WebSockets. One server can hold about 100,000 of them (roughly 1 GB at 10 KB each), so 100 connection servers are enough and 200 leaves room for failures and deploys.
  • Heartbeats: a ping every 30 seconds from 10 million connections is about 330,000 pings a second, as many as the peak deliveries, so connection servers answer pings themselves.
Estimate: Message storage per year

How much storage do one year of messages take, before replication?

You know
  • 2 billion messages a day
  • About 200 bytes per stored message (100 bytes of text plus ids and timestamps)
  • A group message is stored once, not once per member

Show the working
  1. 2 × 109 × 200 B = 400 GB a day
  2. 400 GB × 365 ≈ 146 TB a year
  3. With 3 replicas: about 440 TB of disk a year

Estimate 146 TB (anything from 50 TB to 500 TB is a good answer)

Storing a group message once per member would multiply this by 4.8.

Your turn: Define the API

List what should go over the open connection and what should stay plain HTTP. Then say how a client can retry a send safely.

Compare with a model answer

Sends, deliveries, acknowledgements, receipts and presence go over the WebSocket, and history and catch-up use HTTP with a cursor. The client puts its own id on each send, so the server can recognise a retry.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

WebSocket messages and HTTP endpoints
Client to server, over the WebSocket
  send     { client_msg_id: "c-7f3a", conv_id: "c_123", body: "lunch?" }
  ack      { conv_id: "c_123", up_to_seq: 1044 }       "I have everything up to 1044"
  read     { conv_id: "c_123", up_to_seq: 1044 }       "I have seen everything up to 1044"
  ping     every 30 s
 
Server to client
  sent     { client_msg_id: "c-7f3a", conv_id: "c_123", seq: 1044, ts: ... }
  message  { conv_id: "c_123", seq: 1044, sender: "ana", body: "lunch?", ts: ... }
  receipt  { conv_id: "c_123", user: "ben", kind: "delivered" | "read", up_to_seq: 1044 }
  presence { user: "ben", online: false, last_seen: ... }
  error    { client_msg_id: "c-7f3a", code: "not_member" | "too_large" | "rate_limited" }
 
HTTP
  GET  /v1/conversations/{conv_id}/messages?before_seq=1000&limit=50   history, newest first
  GET  /v1/sync?since={user_cursor}                                    what changed while offline
  POST /v1/conversations   { members: [...] }                          create a group
       403 not allowed, 404 no such conversation, 429 rate limited

The decision to argue about is who gives a message its identity. The client attaches a client_msg_id, an idempotency key: if the connection drops before the sent reply arrives and the client sends again, the server returns the existing message instead of storing a second one. The server assigns seq, the message's position in its conversation, and clients sort by it. Acknowledgements and receipts say "up to seq N", so one small message confirms a whole batch.

Your turn: Model the data

Describe a stored message, the queries that must be fast and the partition key.

Compare with a model answer

Each message is stored once per conversation, ordered by seq, in a wide-column store partitioned by conversation id.

Model the data

Tables
messages                       -- about 200 bytes a row
  conv_id        BIGINT        -- partition key (with bucket)
  bucket         INT           -- month number, keeps partitions bounded
  seq            BIGINT        -- clustering key: order inside the conversation
  sender_id      BIGINT
  client_msg_id  VARCHAR(36)
  body           TEXT          -- up to 4 KB
  created_at     TIMESTAMP
  PRIMARY KEY ((conv_id, bucket), seq)
 
dedupe                         -- PRIMARY KEY (conv_id, client_msg_id) -> seq
                               --   kept 1 day; a retried send gets the stored seq back
conversations                  -- conv_id, kind (direct | group), members, last_seq
members                        -- PRIMARY KEY (user_id, conv_id):
                               --   last_delivered_seq, last_read_seq, last_activity

The access patterns are narrow: append one message to one conversation about 23,000 times a second, and read either the newest 50 messages of a conversation or everything after a given seq. A wide-column store such as Cassandra keeps the rows of a partition together, sorted by the clustering key, so both reads are one sequential scan. A relational database would need manual sharding at 146 TB a year. The members table is keyed by user and answers which conversations a user has and how far the user has read in each.

Your turn: High-level design

Sketch the system. Where do connections live, how does a message reach the server that holds the recipient, and what happens when the recipient is offline?

Compare with a model answer

Connection servers hold the sockets, a stateless chat service orders, stores and forwards each message, and offline recipients get a push notification and catch up from the store.

High-level design

A client opens one WebSocket through a load balancer that picks a connection server, and the connection then stays on that server. The system is split by what each part remembers. Connection servers hold the sockets and contain no business logic, so they are redeployed rarely. The chat service holds no state and can be redeployed freely. The session cache records which user is connected to which connection server.

The chat service orders and stores each message, then looks up the recipient's connection server in the session cache, and offline recipients get a phone push instead.Phones and browsers and Connection servers (WebSocket); Connection servers and Chat service (send / deliver); Connection servers to Sessions and presence (who is here); Chat service to Sessions and presence (where is Ben?); Chat service to Message store (append); Chat service to Push notifier (Ben offline), asynchronous; Push notifier to Phone push services (notify).Phones andbrowsersConnectionserversSessions andpresenceChat serviceMessage storePush notifierPhone pushservicesWebSocketsend / deliverwho is herewhere is Ben?appendBen offlinenotify

request and replyasynchronous message

The chat service orders and stores each message, then looks up the recipient's connection server in the session cache, and offline recipients get a phone push instead.
Ana messages Ben, Ben goes offline, Ben catches upUse the arrows or ← → keys
  1. Ana messages Ben, Ben goes offline, Ben catches up, step 1Ana and Conn server 1; Ben and Conn server 2; Conn server 1 and Chat service; Conn server 2 and Chat service; Conn server 2 to Sessions; Chat service to Sessions; Chat service to Message store; Chat service to Phone push, asynchronous.AnaBenConn server 1Conn server 2Chat servicePhone pushMessage storeSessions
    conversation
    c_123

    1Ana's app tags the message "lunch?" with the id c-7f3a and sends it to connection server 1.

  2. Ana messages Ben, Ben goes offline, Ben catches up, step 2Ana and Conn server 1; Ben and Conn server 2; Conn server 1 and Chat service; Conn server 2 and Chat service; Conn server 2 to Sessions; Chat service to Sessions; Chat service to Message store; Chat service to Phone push, asynchronous.AnaBenConn server 1Conn server 2Chat servicePhone pushMessage storec_123 / 1044Sessions
    conversation
    c_123
    seq
    1044

    2The chat service gives the message the conversation's next number, 1044, and writes it to the store, waiting until 2 of the 3 replicas have it.

  3. Ana messages Ben, Ben goes offline, Ben catches up, step 3Ana and Conn server 1; Ben and Conn server 2; Conn server 1 and Chat service; Conn server 2 and Chat service; Conn server 2 to Sessions; Chat service to Sessions; Chat service to Message store; Chat service to Phone push, asynchronous.Ana1 tickBenConn server 1Conn server 2Chat servicePhone pushMessage storeSessions
    conversation
    c_123
    seq
    1044

    3Ana receives a sent reply with seq 1044, and her app shows one tick.

  4. Ana messages Ben, Ben goes offline, Ben catches up, step 4Ana and Conn server 1; Ben and Conn server 2; Conn server 1 and Chat service; Conn server 2 and Chat service; Conn server 2 to Sessions; Chat service to Sessions; Chat service to Message store; Chat service to Phone push, asynchronous.AnaBengot 1044Conn server 1Conn server 2Chat servicePhone pushMessage storeSessionsben: server 2
    conversation
    c_123
    seq
    1044
    Ben has up to
    1044

    4The session cache tells the chat service that Ben is on connection server 2, so the service forwards message 1044 there and it goes down Ben's socket.

  5. Ana messages Ben, Ben goes offline, Ben catches up, step 5Ana and Conn server 1; Ben and Conn server 2; Conn server 1 and Chat service; Conn server 2 and Chat service; Conn server 2 to Sessions; Chat service to Sessions; Chat service to Message store; Chat service to Phone push, asynchronous.Ana2 ticksBenConn server 1Conn server 2Chat servicePhone pushMessage storeSessions
    conversation
    c_123
    seq
    1044
    Ben has up to
    1044

    5Ben's app acknowledges up to 1044. The chat service saves Ben's delivered position and tells Ana, whose app now shows two ticks.

  6. Ana messages Ben, Ben goes offline, Ben catches up, step 6Ana and Conn server 1; Ben and Conn server 2; Conn server 1 and Chat service; Conn server 2 and Chat service; Conn server 2 to Sessions; Chat service to Sessions; Chat service to Message store; Chat service to Phone push, asynchronous.AnaBendownConn server 1Conn server 2Chat servicePhone pushMessage storeSessionsben: none
    conversation
    c_123
    seq
    1044
    Ben has up to
    1044

    6Ben enters a tunnel and his pings stop. After 60 seconds, connection server 2 closes his socket and removes his session entry.

  7. Ana messages Ben, Ben goes offline, Ben catches up, step 7Ana and Conn server 1; Ben and Conn server 2; Conn server 1 and Chat service; Conn server 2 and Chat service; Conn server 2 to Sessions; Chat service to Sessions; Chat service to Message store; Chat service to Phone push, asynchronous.AnaBendownConn server 1Conn server 2Chat servicePhone pushnotify benMessage storec_123 / 1045Sessions
    conversation
    c_123
    seq
    1045
    Ben has up to
    1044

    7Ana sends "12:30?", which becomes message 1045 and is stored. Ben has no session, so the chat service asks the push notifier to tell Ben to open the app.

  8. Ana messages Ben, Ben goes offline, Ben catches up, step 8Ana and Conn server 1; Ben and Conn server 2; Conn server 1 and Chat service; Conn server 2 and Chat service; Conn server 2 to Sessions; Chat service to Sessions; Chat service to Message store; Chat service to Phone push, asynchronous.AnaBenConn server 1Conn server 2Chat servicePhone pushMessage storeread after 1044Sessions
    conversation
    c_123
    seq
    1045
    Ben has up to
    1044

    8Ben reconnects and asks to sync. The chat service sees that c_123 has activity after his last position, 1044, and reads everything after 1044 from the store, which is one message.

  9. Ana messages Ben, Ben goes offline, Ben catches up, step 9Ana and Conn server 1; Ben and Conn server 2; Conn server 1 and Chat service; Conn server 2 and Chat service; Conn server 2 to Sessions; Chat service to Sessions; Chat service to Message store; Chat service to Phone push, asynchronous.AnaBenConn server 1Conn server 2Chat servicePhone pushMessage storeSessions
    conversation
    c_123
    seq
    1045
    Ben has up to
    1045

    9Message 1045 goes down the new socket, Ben acknowledges it, and Ana sees two ticks.

1 / 9

Deep dives

Routing a message to the recipient's connection server

With 10 million sockets on 100 to 200 servers, Ana and Ben are almost never on the same server, so the chat service needs a way to reach the one server that holds Ben's socket.

A session registry is a shared cache in which each connection server writes "user Ben is on server 2" when Ben connects. To deliver, the chat service looks up the recipients and calls the right servers. For a group message it looks up all members in one batch and makes one call per server that holds at least one member. A crashed server leaves stale entries, so each server refreshes its entries every 30 seconds and they expire after 90. A message sent to a dead server is not lost, because it is already stored.

With a pub/sub channel per user, Ben's server subscribes to a channel named for Ben, and the chat service delivers by publishing to it. This needs no registry, but it means about 10 million live channels in a pub/sub system that must itself be sharded, and a group message becomes 199 publishes.

The third approach is to broadcast to every connection server and let each one discard messages for users it does not hold. At 330,000 deliveries a second and 200 servers that is 66 million messages a second, nearly all thrown away.

Getting a message to the server that holds the recipient
OptionGood atBad atPick it when
Session registry Usual defaultOne lookup per recipient, and a group send is one call per server.A crashed server leaves stale entries until they expire.Use it at large scale. It is my choice here.
Pub/sub channel per userThere is no registry to maintain.It needs 10 million channels, and a group message costs 199 publishes.Use it when pub/sub is already in the stack and groups are small.
Broadcast to every serverThere is nothing to look up.It creates 66 million messages a second at this scale.Use it only with a handful of servers.

Delivery guarantees and ordering

A weak answer promises "exactly once" delivery. The server sends a message and waits for an acknowledgement, and if the acknowledgement is lost it must send the message again, so delivery is at least once. The client ignores any (conv_id, seq) pair it already has. The server must also store the message, then acknowledge it to the sender, and only then deliver it. If it delivered first and crashed before storing, Ben would have seen a message that no longer exists, and Ana's retry would create a second copy.

For ordering, the sender's clock is useless, because phone clocks can be wrong by seconds or hours and two people would see different orders. A server timestamp is closer, but two messages in one conversation can tie. A sequence number per conversation gives one agreed order, and a gap tells a client that it missed a message. The cost is that one place per conversation must issue the numbers.

The interviewer will ask where the number comes from. One answer is to route every send for conversation c_123 to one chat service instance, chosen by consistent hashing on the conversation id, which keeps the counter. The other is to keep the counter in a store with an atomic increment or conditional write. Plain quorum reads and writes are not enough, because two servers can both write 1044.

The next question is what happens when the owning instance crashes. Another instance takes over and continues from the highest stored seq. During the handover two instances may both believe they own the conversation, so the store write is conditional on that seq not existing yet, and the instance that loses retries with the next number. A number that was issued but never stored leaves a gap, which is harmless.

Offline delivery and sync

The message store guarantees delivery, and sockets and push notifications only tell the client that something is new. On reconnect the client calls /v1/sync. The server reads the user's members rows, finds the conversations with activity after the cursor, and returns each one's last_seq. The client compares that with its own position and fetches the missing range.

A phone push service can delay or drop notifications, so "push sent" never means "delivered". A socket can also die unnoticed, so if Ben does not acknowledge within about 10 seconds, the chat service sends a push anyway. The notification system case study covers push in detail.

Read receipts and presence

A receipt is stored as a position in the conversation rather than as a row for each message. Ben's members row holds a delivered position and a read position, so "read up to 1045" is one small write. In a one-to-one chat the server pushes each change to the other person. In a group of 200, pushing every cursor change to every member is about 200 × 199 = 40,000 messages when everyone reads one message, so groups compute "read by 37" only when someone opens the message info.

Presence is usually the most expensive feature. It lives only in the session cache with the 90 second expiry. If each user goes online or offline about 20 times a day, 50 million users cause about 11,600 changes a second. Pushing each change to 100 contacts would be about 1.16 million presence messages a second, ten times the delivery rate, so the server pushes presence only to users who have that contact's chat open, and everyone else fetches it when they open the chat.

Storage and the partition key

Partitioning by message id spreads data perfectly evenly, but reading the last 50 messages of a chat then touches up to 50 partitions. Partitioning by recipient user id, an inbox per user, makes sync one read, but every message is written once per recipient, 4.8 copies on average and 199 in a full group. Partitioning by conversation id plus a month bucket stores each message once, and both history and catch-up read one partition. The cost is that sync must first find the changed conversations in members, and a history read across a month boundary needs a second query.

The bucket stops a busy conversation from growing one partition forever. A full group in which everyone sends 40 messages a day writes 200 × 40 × 200 B = 1.6 MB a day, so a monthly bucket stays near 48 MB.

Bottlenecks and failures

At 10 times the load, with 500 million daily users, peak deliveries reach about 3.3 million a second. The connection tier needs about 1,000 servers for 100 million sockets, which is more servers but no design change. The message store adds nodes. The session cache strains first, so shard it by user id.

Component that failsWhat happensWhat you do
A connection serverIts 100,000 users lose their sockets.Their apps reconnect to other servers after a random delay and sync from their last seq.
A chat service instanceSends in flight time out.Clients retry with the same client_msg_id, and the conversations it owned move to another instance.
The session cacheThe chat service cannot find recipients.Messages still arrive through sync. Do not push for every message. Replicate the cache, and servers re-register their users within one refresh.
A message store replicaOne of three copies is gone.Majority reads and writes keep working while you rebuild it. The majority matters because 2 + 2 > 3, so a catch-up read always sees the latest write.
The phone push servicesOffline users are not nudged.Messages wait in the store until sync.

What a strong answer sounds like

LevelWhat the answer does
JuniorUses WebSockets and a database, orders by timestamp, and says "exactly once" without explaining how.
Mid-levelSeparates connection servers from chat logic, routes with a registry or pub/sub, stores before delivering, and uses sync for offline users.
SeniorExplains at-least-once delivery with deduplication, names the source of the sequence and what happens when its owner fails, derives the partition key from group fan-out, and notices that heartbeats and presence can cost more than messages.
Defending the orderingStrong answer
Interviewer

Why not order messages by timestamp?

You

Clocks drift, so two people could see different orders. Instead each conversation gets a sequence number from one owner, the chat server its id hashes to. Everyone sorts by that number, and a gap tells a client it missed a message.

Interviewer

What happens if that owner crashes in the middle of a conversation?

You

Another instance takes over, reads the highest stored seq and continues. Two servers might briefly both think they own it, so the write is conditional on that seq not existing. The one that loses retries with the next number.

Follow-up questions

Why use WebSockets instead of polling?

With polling, a message waits up to one polling interval before it appears, and every idle client still sends requests. A WebSocket lets the server push a message the moment it is stored, and an idle connection costs only a ping every 30 seconds. See Realtime Communication for the alternatives.

How do you handle a very large group or channel?

Delivering a message to every member does not scale to thousands of members, so large groups stop pushing each message to every socket. Members who are connected get a short "new messages" signal and fetch from the store, and members who are offline sync later.

How do you support several devices per user?

The registry maps a user to a list of (device, server) pairs, and each device keeps its own delivered position. A new message goes to every connected device, and "delivered" to the sender means that at least one device acknowledged it. Read state is shared through the read cursor.

Where do photos and videos go?

The client uploads the file to blob storage with a short-lived signed URL, then sends a normal message containing the file's id. The file never passes through the chat path.

How would you run this across several regions?

Each user connects to the nearest region, and each conversation has a home region that owns its sequence numbers. A sender in another region pays one cross-region round trip per message.

Self-review: chat app0 of 13

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure