A chat app lets people send messages and media to one another, one to one or in groups, and see them arrive in real time. It's a good problem because the hard parts aren't the messages themselves. They're the long-lived connections, delivering to people who are offline, and keeping that working for a billion users. This page runs it through the Interview Approach, one step at a time.
1. Functional requirements#
Four actions define the product:
- A user can start a group chat with other participants, up to 100 per group.
- A user can send and receive messages.
- A user receives messages sent while they were offline, for up to 30 days.
- A user can send and receive media (images, video, files) in their messages.
A one-to-one chat is just a chat with two participants, so it needs no separate design.
Out of scope: voice and video calls, end-to-end encryption details, read receipts, typing indicators, and message search.
2. Non-functional requirements#
These qualities shape the design. Each one gets a number or a clear rule:
| Quality | Requirement |
|---|---|
| Scalable | A billion active users |
| Large storage | Billions of messages and media files a day. Spread the database across nodes by sharding on an ID |
| Low latency | A message reaches an online recipient in under 200 ms |
| Consistency over availability | Every message is delivered, in order, exactly as sent. Rejecting a send is better than losing one |
| Fault tolerant | A crashed server or database node never loses a message |
A quick estimate shows where the pressure is. The numbers per user are assumptions you'd state out loud:
- Messages: 1 billion users × 40 messages a day = 40 billion a day. 40 billion ÷ 86,400 ≈ 460,000 per second on average, about 1 million at peak. One database can't take that, which is why sharding is in the requirements.
- Storage: at about 200 bytes per text message, 40 billion a day is about 8 TB a day. Media is far bigger, so it goes to blob storage, not the database.
- Connections: if 200 million users are online at once and one chat server holds about 100,000 open connections, you need about 2,000 chat servers. The connection count, not the message rate, sets the size of the fleet.
3. Actors#
One kind of person uses the app, but it helps to split them by role and by device:
| Actor | What they do | Access |
|---|---|---|
| Chat creator | Starts a group and picks its participants | Signed in |
| Participant (sender) | Sends messages and media to a chat they belong to | Signed in, must be a member of the chat |
| Participant (recipient) | Receives messages, live or after coming back online | Signed in, must be a member of the chat |
| Client device | One phone, laptop or browser of a user. A user can have several, and each needs every message | Its own client ID, tied to the user |
The client device row matters later. Delivery happens per device, not per person.
4. API routing#
Chat is two-way: the server has to push messages to you without you asking. Plain request and response can't do that well, so use WebSockets for bidirectional chatting. The client opens one long-lived connection, and both sides send events over it.
Sent by the client:
| Event | Body | Response |
|---|---|---|
createChat |
name, participants |
The new chatId |
sendMessage |
chatId, message, mediaUrl |
200 success once the message is stored |
{
"event": "sendMessage",
"chatId": string,
"message": string,
"mediaUrl": string (optional)
}
Sent by the server:
| Event | Body | Client reply |
|---|---|---|
chatUpdate |
chatId, participants |
Acknowledges it received the update |
newMessage |
chatId, message, media, senderId |
Acknowledges it received the message |
{
"event": "newMessage",
"chatId": string,
"messageId": string,
"senderId": string,
"message": string,
"media": string (optional)
}
The client's acknowledgement is what tells the server a message was delivered. Without it, the server can't tell a delivered message from one lost on a dropped connection.
To show older messages when you scroll up, add a plain HTTP endpoint with pagination, such as GET /v1/chats/{chatId}/messages?limit=50. Offset-based pagination is the simplest start. Step 6 explains why a cursor works better here.
5. High-level design#
Build the design one functional requirement at a time. Keep it simple and don't optimize yet.
Connect. The user opens a WebSocket connection. It goes through a network load balancer to a chat server, which keeps the connection open for as long as the app is open. A network (layer 4) load balancer suits this because it just passes long-lived TCP connections through. See layer 4 and 7.
Create a group (requirement 1). The client sends createChat. The chat server checks the group has at most 100 participants, then stores the data in a Postgres database:
| Table | Columns |
|---|---|
chat |
id, name, metadata |
chat_participants |
chat_id, participant_id |
It returns the chatId and sends a chatUpdate to each participant, so the new group shows up on their devices.
Send and receive (requirement 2). The client sends sendMessage. The chat server updates the database with the message details. It writes one row to message, and one row to inbox for each participant who should receive it:
| Table | Columns |
|---|---|
message |
message_id, chat_id, sender_id, message, media_url, created_at |
inbox |
recipient_id, message_id, timestamp |
The inbox is a to-do list: one row per message a recipient hasn't received yet. Once both writes succeed, the chat server returns 200 to the sender and puts the message on a queue to send. A worker reads from the queue, looks up the chat's participants, and sends newMessage to each of them. The worker doesn't hold connections itself. It hands each message to the chat server that holds the recipient's connection, and that server pushes it down the WebSocket. When the recipient acknowledges, its inbox row is deleted.
Offline delivery (requirement 3). If a recipient is offline, there's no connection to push to, so the inbox row simply stays. When the user comes back online:
- The user's client connects to a chat server.
- The chat server checks the user's inbox. Every row still there is a message they haven't received. It loads those messages, adds them to the queue, and the worker delivers them as usual.
So a user coming online triggers delivery of their waiting records. For 30-day retention, a background job deletes inbox rows and messages older than 30 days.
Media (requirement 4). Media is too large for the database. The chat server reads and writes media in blob storage such as Amazon S3. The client uploads the file first and gets back a URL link, and the message carries only that media_url. The recipient's client downloads the file from the link.
6. Address the non-functional requirements#
The basic design works for a small group of users. Now take each quality and find where the design breaks it.
Scalable#
A billion users means thousands of chat servers, and the sender and recipient are almost never on the same one. The worker needs to know where each recipient is connected. Keep a connection registry in Redis: when a client connects, its chat server writes client_id → chat server, and deletes it on disconnect. The worker looks up each recipient and sends to the right server.
| Approach | How it works | Trade-off |
|---|---|---|
| Registry lookup | The worker reads client_id → chat server from Redis and calls that server directly |
One extra lookup per recipient. Entries go stale if a server dies without cleaning up, so give them a short TTL refreshed by heartbeats |
| Pub/sub per user | Each chat server subscribes to a channel for every user it holds. The worker publishes to the user's channel | No lookup, but millions of channels to manage, and Redis pub/sub drops messages nobody is listening for, so the inbox is still the safety net |
The registry is simpler to reason about. The load balancer should spread new connections by least connections, not round robin, because connections last hours and round robin lets some servers fill up.
Large storage#
At 8 TB of text a day, one Postgres node won't hold the data. Shard by ID (see choosing a shard key):
messagebychat_id. All of one chat's history lives on one shard, so loading a chat is a single-shard query.inboxbyrecipient_id. The "what did I miss" query on reconnect touches one shard.chatandchat_participantsbychat_id. Finding a chat's members, which every send does, stays on one shard.
The trade-off is that one send writes to several shards: the message on the chat's shard, and inbox rows on each recipient's shard. That's acceptable because each write is small and the queue retries failures. A query like "list all my chats" now spans shards, so keep a small per-user copy of chat IDs.
Media stays out of the database entirely. To keep large files off the chat servers too, give the client a pre-signed S3 URL. It uploads straight to S3, then sends the message with the link. The chat server only signs the URL.
Low latency#
Under 200 ms leaves no room for several database reads per message. A Redis cache holds the data per client ID or user ID that every send needs: the connection registry from above, and each chat's participant list. The hot path becomes write to the database, enqueue, look up in Redis, push. See distributed cache.
The history endpoint needs a fix too. Offset pagination (?offset=100) slows down as the offset grows, and new messages arriving shift the offsets, so the user sees duplicates or gaps while scrolling. Use a cursor instead: "50 messages before message_id X". It stays fast and stable, since messages are only ever added.
Consistency over availability#
This is the choice from step 2: guaranteed delivery of every message, in order. Three rules make that happen:
- Store before you acknowledge. The sender gets
200only after the message and inbox rows are written. If the database is unreachable, the send fails and the client retries. You lose availability for a moment, but never a message. - A durable queue holds messages until they're delivered. Use a log-based queue like Kafka, partitioned by
chat_id. Messages in one chat stay in order, because one partition is read in order. - Delete only on acknowledgement. The inbox row goes away only when the recipient's client confirms it. If the push is lost, the row is still there for the next retry or reconnect.
The trade-off is duplicates. A worker can push a message, crash before seeing the acknowledgement, and push it again. That's at-least-once delivery. The client fixes it by ignoring any message_id it has already shown. See CAP and consistency.
Fault tolerant#
Each part needs a plan for when it dies:
- A chat server crashes. Its connections drop. Clients reconnect through the load balancer to another server, which registers them and replays their inbox. Nothing is lost, because the inbox was written before the crash.
- A database node fails. Each shard has replicas in other zones, and one is promoted. Use synchronous replication to at least one replica, so an acknowledged message survives the failover. That adds a few milliseconds to each write.
- A worker crashes. The queue redelivers anything it hadn't committed, and another worker picks it up.
Multiple clients per user#
A user may be signed in on a phone and a laptop at once. If the inbox is keyed by user, the first device to acknowledge deletes the row and the other device never gets the message. So the inbox stores rows per client ID, not per user: inbox(client_id, message_id, timestamp). Each client receives and acknowledges the message on its own.
The trade-off is more rows: a message to a 100-person group where everyone has two devices writes 200 inbox rows. Cap the number of linked devices per user to keep that bounded.
Whiteboard sketch#
The sketch below is the design from steps 5 and 6. The user connects over a WebSocket through a network load balancer to a chat server, which stores chats and messages in Postgres and media in S3, then hands each message to a queue that a worker drains to deliver it to the participants.

Key takeaways#
- Four functional requirements: group chats up to 100 people, send and receive, offline delivery for 30 days, and media.
- Use WebSockets so the server can push messages. The client acknowledges each one, and that acknowledgement is what counts as delivered.
- The inbox holds one row per undelivered message. Reconnecting replays it, which is how offline delivery works.
- Store before acknowledging the sender, deliver through a durable queue partitioned by chat, and delete inbox rows only on the recipient's acknowledgement. Clients drop duplicates by
message_id. - A Redis connection registry tells workers which chat server holds each client.
- Shard messages by
chat_idand inboxes by recipient. Keep media in S3, uploaded with pre-signed URLs. - Key the inbox by client ID, not user ID, so every device gets every message.