Design a chat system

A chat system such as WhatsApp, Messenger or Slack lets people send messages to each other and see them almost instantly. The real interview questions go beyond "open a WebSocket and send text". How do messages stay in order? What if the receiver is offline? How do you know a message was delivered? What changes for a group of 5 compared with a channel of 500,000? The connection layer (WebSocket gateways, reconnect storms) is in the real-time lesson, so here we build the chat logic on top of it.

1. Requirements and Scope

Functional requirements:

  • One-to-one chat and group chat. Text, and media such as images.
  • Delivery status: sent, delivered, read.
  • Offline users receive their messages when they return, and get a push notification meanwhile.
  • The same account on several devices stays in sync.
  • Online status ("last seen") and typing indicators.
  • Message history, with scrolling back.

Non-functional requirements:

  • Low latency: under 200 ms to an online user.
  • Never lose a message, once the sender sees "sent".
  • Ordered: everyone in a conversation sees the same order.
  • Highly available and able to scale to hundreds of millions of users.

Out of scope: calls, search, bots and moderation.

2. Estimation

  • Messages: 100 million daily users send about 40 messages each: 4 billion messages a day. 4,000,000,000 ÷ 86,400 ≈ 46,300 per second on average, and 185,000 per second at peak (4 times).
  • Connections: assume 30 million users are connected at peak. At about 100,000 connections per gateway server, that is 300 servers. With 1.5 times headroom for zone loss: about 450.
  • Storage: a message with metadata is about 200 bytes. 4 billion × 200 B = 800 GB a day, about 290 TB a year, and 3 copies make about 880 TB. Older messages move to cheaper storage after a year.
  • Presence trap: if each of the 30 million connections sends a heartbeat every 30 seconds, that is 1 million heartbeats a second. Written to a database or fanned out to friends, they would drown the system. So heartbeats stay between the client and its gateway, and only connect and disconnect go further.

The takeaway: the load is many small messages and many open connections. The hard parts are ordering, delivery guarantees and the group and offline cases, not raw volume.

3. Interface

Chat uses two channels. A WebSocket carries everything that is small, urgent and may start from the server: sending, receiving, receipts and typing. Plain HTTP carries everything that is a normal request and answer: creating a group, loading history, syncing after being offline, and getting an upload link for media. HTTP calls are easy to retry, cache and balance, so we keep them off the WebSocket.

3.1 WebSocket Events

Direction Event and fields Purpose
Client to server send {conversationId, clientMsgId, body} Send a message
Server to client sent {clientMsgId, seq} "Saved." The first tick. It also tells the app the message's number
Server to client message {conversationId, seq, senderId, body, time} A new message for this user's device
Client to server ack {conversationId, seq, status} "Delivered" or "read", for every message up to seq
Server to client receipt {conversationId, seq, status} Tells the sender that the others have received or read it
Both typing {conversationId} Short-lived hint. Never stored

A message on the wire, as the sender sends it and as the receiver gets it:

// sender -> server
{ "type": "send", "conversationId": "c-91", "clientMsgId": "c-77", "body": "Hotel booked" }

// server -> every device of every member
{ "type": "message", "conversationId": "c-91", "seq": 1042, "senderId": "u-ria",
  "body": "Hotel booked", "time": "2026-11-02T05:40:12Z" }
  • clientMsgId is made by the sender's app (a random ID). It makes a retried send safe: the server sees the same ID and does not store a second message.
  • seq is a number that grows by 1 for each message in a conversation. The server assigns it, and it defines the order. The sender learns it from sent.
  • One ack covers many messages. "Read up to seq 1042" marks everything before it too. This is cheaper than one ack per message, and it is the position stored for the member (section 7).

3.2 HTTP Calls

  • POST /v1/conversations creates a group with a list of member IDs and returns the conversation ID.
  • GET /v1/conversations/{id}/messages?before=seq&limit=50 returns older messages for scrolling back. It uses a position (before=seq), not a page number, because new messages keep arriving.
  • POST /v1/sync with [{conversationId, lastSeq}, ...] returns every newer message, for users returning after being offline.
  • POST /v1/media/upload-url returns a temporary upload link for object storage. The app uploads the file there, then sends a normal send event that carries the media ID.

4. Data Model

messages            (conversation_id, seq, sender_id, client_msg_id, body, type, created_at)
                    -- partition key: conversation_id, clustering key: seq (newest first)
sent_message        (conversation_id, client_msg_id, seq)        -- finds a message by its client ID, for retries
conversation_member (conversation_id, user_id, last_delivered_seq, last_read_seq)
user_conversation   (user_id, conversation_id, last_seq, last_message_at)   -- the chat list

The main access pattern is "the latest N messages of a conversation, or the messages after seq X". A wide-column store such as Cassandra fits: all messages of a conversation sit together in one partition, in order (see the NoSQL lesson). A huge channel would make one partition too big, so very active conversations are split by time bucket, for example one partition per conversation per day. sent_message is a small lookup written with each message, so a retried send is recognised even after a failover. Media is uploaded to object storage, and the message holds only its ID and a thumbnail.

5. High-Level Design

5.1 The Flow

flowchart LR
  A["Sender app"] --> G1["WebSocket gateway 1"]
  G1 --> CS["Chat service, one owner node per conversation"]
  CS --> MS[("Message store, partitioned by conversation")]
  CS --> REG[("Session registry: user to gateway")]
  CS --> G2["WebSocket gateway 2"]
  G2 --> B["Receiver app"]
  G1 -.->|"connect, disconnect"| PS["Presence service"]
  G2 -.->|"register on connect"| REG
  CS -.->|"receiver offline"| PN["Push notification service"]
  A -.->|"media upload"| OS[("Object storage + CDN")]
  1. Connect: when an app starts, it opens a WebSocket with its login token. The gateway checks the token, writes "this user's device is on gateway 2" into the session registry, and reports the connection to the presence service. On disconnect it removes the entry. If a gateway crashes, its entries are ignored once the gateway's own lease (renewed every few seconds) expires.
  2. Send: the sender's app sends the message over its WebSocket. The gateway forwards it to the chat-service node that owns the conversation (section 6.1), which saves it and gives it a seq. Then it tells the sender "sent".
  3. Deliver: the chat service looks up the receiver's devices in the registry and asks their gateways to push the message. The receiver's app answers with a "delivered" ack.
  4. Offline receiver: the message stays in the store, and a push notification goes out (see the notification system lesson).
  5. Receipts: acks travel back the same way: app, gateway, chat service. The chat service updates the member's position and sends a receipt to the sender's devices.

5.2 Who Does What

Component Its job Keeps state?
WebSocket gateway Holds connections, checks the login token, forwards events. Makes no chat decisions Only open connections. Lost on restart, rebuilt when clients reconnect
Chat service Removes duplicates, assigns seq, saves, decides who gets the message, handles acks Each node owns a set of conversations and keeps their counters in memory, recovered from the store
Message store The truth: messages, member positions and the chat list Yes, replicated and durable
Session registry Answers "which gateway holds this user's devices?" Yes, but disposable: devices register again on reconnect
Presence service Online status and last seen, from connect and disconnect events Online flags and last-seen times, small and rebuilt from reconnects
Push notification service Wakes offline phones through the platform push services Device tokens only
Object storage and CDN Stores and serves images and video. Messages carry only the media ID Files

6. Sending a Message Reliably

public Ack send(SendRequest r) {
    // 1. A retry with the same clientMsgId returns the same result instead of a second message
    Message existing = store.findByClientMsgId(r.conversationId(), r.clientMsgId());   // uses sent_message
    if (existing != null) return Ack.sent(existing.seq());

    // 2. One chat-service node owns each conversation, so it can hand out 1, 2, 3, ... with no gaps or duplicates
    long seq = sequences.next(r.conversationId());          // counter in memory, loaded from the store on first use
    Message m = new Message(r.conversationId(), seq, r.senderId(), r.clientMsgId(), r.body(), Instant.now());
    store.save(m);                                            // durable BEFORE "sent"; fails if (conversationId, seq) exists

    // 3. Deliver to every device of every member, including the sender's other devices
    for (long member : members.of(r.conversationId())) {
        List<Device> devices = registry.devicesOf(member);
        for (Device d : devices) gateways.push(d.gatewayId(), d.id(), m);
        if (devices.isEmpty() && member != r.senderId()) notifications.pushPreview(member, m);
    }
    return Ack.sent(seq);
}
  • No lost messages: the message is saved before "sent" is shown. If the sender gets no "sent" within a few seconds, the app retries with the same clientMsgId, and step 1 prevents a duplicate.
  • Ordering: one owner per conversation numbers its messages, so the order is the same for everyone. Ordering across conversations does not matter. Section 6.1 shows how.
  • Delivery to the client is at-least-once: the client removes duplicates by (conversationId, seq). If it receives seq 12 after seq 10, it notices the gap and asks for the missing message with the sync call.

6.1 Who Numbers the Messages, and What If That Server Dies

How a conversation gets its owner:

  • The chat-service nodes sit on a hash ring (see the sharding lesson). The owner of a conversation is the node that hash(conversationId) lands on. The ring (the list of live nodes) is kept in a coordination store such as etcd or ZooKeeper, and every gateway keeps a copy.
  • A gateway that receives send computes the owner and forwards the message straight to it. So all messages of one conversation, from any sender on any gateway, reach the same node, which handles them one at a time.
  • The owner keeps each active conversation's counter in memory. It loads the counter once from the store (the last saved seq, one read) and then adds 1 in memory per message, with no database call to get a number.

When the owner dies:

  1. Detect: each node renews a short lease (a few seconds) in the coordination store. A dead node stops renewing, and its lease expires after about 5 to 10 seconds.
  2. Reassign: the ring is updated, and gateways receive the new version. The conversations of the dead node now hash to other nodes.
  3. Recover: on its first message for a conversation, the new owner reads the last saved seq (say 1042) and carries on from 1043. Everything saved is in the store, so nothing is lost or renumbered.
  4. In-flight messages: a message the dead node had not saved never got "sent", so the sender's app retries it with the same clientMsgId, and the new owner saves it once. A message that was saved but not acknowledged is found by clientMsgId, and the same seq is returned.

For those 5 to 10 seconds, sends in those conversations are retried. Nothing is lost or reordered.

The risky case is two owners. A node cut off by a network problem may not know it lost its conversations, and keep numbering. The store prevents damage: each save is "insert (conversationId, seq) only if it does not exist yet". When the old and new owner both try to write 1043, one of them fails. The failing node stops and refreshes the ring.

7. Groups and Large Channels

A message is stored once per conversation, not once per recipient. Each member has a small record with the last seq they have received and read. Unread count = latest seq minus last read.

Conversation Delivery Receipts
One-to-one Push to both users' devices Delivered and read, per message
Small group (up to a few hundred) Fan-out on write: push to every online member's devices, push notification to offline ones Aggregate. Show per-person status only when asked
Large channel (thousands to millions) Push only to members who have the channel open. Others see it when they open it. Notify only for mentions None, or a view count

The reason is cost. A message to a channel with 500,000 members would be 500,000 pushes, and most of those people are not looking. So we deliver to those who are watching, and everyone else pulls on demand. It is the same push-versus-pull trade-off as in the news feed lesson.

8. Offline Users and Several Devices

  • Offline: the message is already in the store. The chat service sends a push notification through the notification system. It carries a short preview.
  • Coming back: the app calls sync (section 3.2) with the last seq it has for each conversation. The server returns the newer messages in order. The store is the queue, so no separate offline queue exists.
  • Several devices: each device keeps its own last-seen seq and syncs independently. A message goes to all of a user's devices, including the sender's other ones, so all devices match. A read on one device moves the "last read" mark for all.
  • Chat list: a table keyed by user with each conversation's latest message time, sorted by recent activity, so opening the app is one query.

9. Presence and Typing

  • Online status: the gateway reports connect and disconnect to the presence service, which keeps the online flag and the last-seen time (the time of the last disconnect). If a gateway dies, the presence service uses the same gateway lease as the session registry to mark its users offline. Client heartbeats stay between the app and its gateway.
  • Do not broadcast to everyone. A user with 500 contacts going online would trigger 500 updates. Instead, a client asks for the status only of people it is showing on screen (open chat, visible list), and receives changes only for those.
  • Typing indicators are never stored. They are short-lived events, limited to a few per second, and dropped if the receiver is not connected.

Background note: end-to-end encryption

In an end-to-end encrypted chat (WhatsApp, Signal), only the devices hold the keys. The server stores and forwards ciphertext it cannot read. This protects users even if the servers are breached. The costs: the server cannot search or moderate message text, and groups and several devices need careful key management (the Signal protocol is the usual answer). The delivery design here does not change, because the server never needed to read the body.

10. Worked Example: A Message to the "Goa Trip" Group

The group has Ria, Sam, Tara and Uday. Ria's app sends "Hotel booked" with clientMsgId = c-77.

  1. The chat-service node that owns this conversation saves it as seq = 1042 and tells Ria's app "sent". One tick appears.
  2. Sam is online on two devices, and Tara on one. The service pushes to those three connections, and to Ria's own laptop.
  3. Uday is offline. The notification system sends him a push: "Ria: Hotel booked".
  4. Sam's and Tara's apps send "delivered". Ria sees two ticks only when all members have the message, so she still sees one. Tapping the message shows "delivered to 2 of 3".
  5. Ria's app lost its connection before seeing "sent", so it resends c-77. The service finds the saved message and answers seq = 1042. No duplicate.
  6. An hour later Uday opens the app. It says "I have seq 1041 for this conversation". The server returns 1042, and Uday's app confirms delivery.

11. Scaling and Failures

  • Gateways scale by connection count, are restarted by draining, and clients reconnect with jitter (see the real-time lesson). Losing a gateway loses no messages, because messages are in the store.
  • Chat service and store: if a node dies, others take over its conversations (section 6.1). The store is replicated across zones and partitioned by conversation.
  • Session registry in Redis maps users to gateways. If it is lost, devices register again when they reconnect, and delivery in between falls back to the offline path (store plus push), so nothing is lost.

12. Common Pitfalls

  • Saying "sent" before the message is stored. A crash then loses a message the user thinks went out.
  • No client message ID, so a retry creates duplicates.
  • Ordering by device clocks. Phones disagree on the time. Use a server-assigned number per conversation.
  • Storing one copy per recipient for big groups. Store once and track each member's position.
  • Pushing every message of a huge channel to every member.
  • Heartbeats that hit the database, or presence sent to all contacts.

13. Interview Questions

  1. How do you keep messages in order? One chat-service node owns each conversation and numbers its messages 1, 2, 3 in memory. The database only stores the number. Clients sort by it and detect gaps. Device clocks are not used.
  2. How do you avoid duplicates and lost messages? A client-made message ID makes sender retries safe. Messages are saved before "sent". Delivery to clients is at-least-once, and clients remove duplicates by conversation and number.
  3. What happens when the receiver is offline? The message is stored. A push notification is sent. When the user returns, the app sends its last number for each conversation and gets everything newer.
  4. How do you design group chat? Store a message once per conversation, with a read position per member. Fan out to online members. For huge channels, push only to members who have it open, and pull for the rest.
  5. How do you implement read receipts? The receiver's app sends "delivered" or "read" with the conversation and number. The server updates the member's position and tells the sender. In groups, aggregate them.
  6. How do you handle online status for millions of users? Keep heartbeats between client and gateway. Update the shared status only on connect and disconnect, and send changes only to people who are looking at that user.
  7. How do you support several devices? Deliver to all of a user's devices, including the sender's others. Each device syncs from its own last-seen number.