Design the backend of a chat system (like WhatsApp)
Design the backend of a chat system like WhatsApp or Messenger: one-on-one and group conversations, real-time delivery, delivery and read receipts, online presence, and message history across devices.
A typical framing: "500 million daily active users, each sending about 40 messages a day. Messages must arrive instantly when the recipient is online, and be waiting for them when they come back. Groups have up to 500 members. Users have a phone and a laptop."
TL;DR
Clients keep a persistent WebSocket connection to a fleet of chat gateway servers. A session registry (in Redis) maps each user's devices to the gateway holding their connection, so a message can be routed to the right server. Every message is persisted first (in a store partitioned by conversation, like Cassandra), assigned a per-conversation sequence number for ordering, then pushed to online devices; offline devices get a push notification and sync missed messages by sequence number when they reconnect.
Delivery is at least once with acks from the device, and client-generated message ids make retries idempotent. Small groups fan out on write to each member's devices; receipts and presence are lightweight events, throttled and only sent to people who are looking. End-to-end encryption (Signal protocol) means the server stores and routes ciphertext only.
1. Requirements and estimates
Functional
- 1:1 and group chats (up to 500 members), text and media.
- Real-time delivery; offline messages delivered later.
- Sent, delivered and read receipts; typing indicators; online / last seen.
- History synced across a user's devices.
Non-functional
- Low latency (under ~200 ms end to end within a region).
- No lost messages; correct order within a conversation; no duplicates shown.
- Highly available; end-to-end encrypted.
Estimates
- 500M × 40 = 20B messages / day ≈ 230,000 messages per second, peaks ~1M.
- Concurrent connections: maybe 200M at peak; at ~100k connections per gateway server that's ~2,000 gateway servers.
- Storage: 20B × ~200 bytes ≈ 4 TB per day of message data (media stored separately in object storage).
2. API
Over the WebSocket (JSON or a compact binary format like protobuf):
{ "type": "send", "clientMsgId": "c-8f3a", "conversationId": "cv_12", "body": "<ciphertext>" }
{ "type": "ack", "clientMsgId": "c-8f3a", "seq": 1042, "serverTime": "2026-11-27T10:00:00Z" }
{ "type": "message", "conversationId": "cv_12", "seq": 1042, "from": "u_7", "body": "<ciphertext>" }
{ "type": "receipt", "conversationId": "cv_12", "upToSeq": 1042, "status": "read" }Over HTTP: GET /v1/conversations/{id}/messages?afterSeq=1000 for sync and history, POST /v1/media for uploads (returns a URL to send in the message).
3. Data model
messages partition key: conversation_id, clustering key: seq
(conversation_id, seq, message_id, sender_id, body, created_at)
conversations (id, type, member_ids, last_seq)
user_inbox (user_id, conversation_id, last_read_seq, last_delivered_seq)
sessions Redis: user_id -> { device_id: gateway_id }Partitioning messages by conversation keeps a chat's history together and makes "messages after seq N" a single range read.
4. High-level architecture
- The sender's gateway forwards the message to the chat service.
- The chat service dedupes by
clientMsgId, assigns the nextseqfor the conversation, persists it, and acks the sender (one check mark). - It looks up the recipients' devices in the session registry and publishes to their gateways (via a bus or direct RPC).
- Gateways push to the devices; devices ack (two check marks). Offline devices get a push notification.
5. Deep dives and scaling
Ordering
Global ordering is unnecessary and expensive; users only need order within a conversation. A per-conversation counter (an atomic increment in Redis, or the database partition's own counter) gives a gap-free seq. Clients display by seq, not by their own clock, and detect gaps ("I have 1040, got 1042, fetch 1041").
Reliability
- Persist before ack: the sender's "sent" check means the server has it durably.
- Retries: clients resend unacked messages; the server dedupes by
clientMsgId, so retries don't create duplicates. - Sync on reconnect: each device remembers its last
seqper conversation and fetches what's newer. This handles every missed push, so the real-time path can be best effort.
Connections at scale
- Gateways hold connections only; they're stateless otherwise, so they scale horizontally behind a load balancer (sticky per connection).
- When a gateway dies, clients reconnect to another one and sync; the session registry entry expires via TTL heartbeats.
- Deploys drain connections gradually to avoid a reconnect storm.
Groups
For groups up to a few hundred members, fan out on write: one stored message, delivered to each member's online devices. The message is stored once per conversation, not per member. For very large channels (thousands of members), switch to pull: members fetch new messages when they open the channel.
Receipts, typing and presence
- Receipts are stored as "read up to seq N" per user per conversation, not per message, which cuts writes dramatically.
- Typing indicators are ephemeral: routed but never stored.
- Presence is driven by heartbeats with a TTL. Broadcasting every status change to all contacts is too expensive, so subscribe only to the presence of conversations currently open on screen.
Multi-device and encryption
Each device is a separate recipient with its own session. With end-to-end encryption, the sender encrypts for each recipient device (the Signal protocol); the server never sees plaintext, so server-side search isn't possible and history sync is device to device or via encrypted backups.
Storage lifecycle
Hot recent messages on fast storage; older history in cheaper tiers. WhatsApp historically deleted messages from servers once delivered; whether you keep server history is a product and privacy decision.
Common follow-ups
- "Why WebSocket and not polling or SSE?" Chat is truly two-way and latency-sensitive; one long-lived connection carries both directions with minimal overhead. Long polling remains a fallback on networks that block WebSockets.
- "How do you route between 2,000 gateways?" The session registry gives
userId → gatewayId; publish to that gateway's channel on a pub/sub bus (Redis pub/sub, Kafka partition, or direct gRPC). - "What happens if the recipient has been offline for a week?" Messages wait in the store; on reconnect the device syncs by sequence number in pages. A push notification is sent once (collapsed), not per message.
What interviewers look for
- Persistent connections with a session registry for routing.
- Persist-then-deliver, acks, client message ids for idempotency, and sync by sequence number.
- Per-conversation ordering instead of global ordering.
- Sensible handling of groups, receipts, typing and presence without flooding the system.
- Scaling numbers for connections and storage, and awareness of end-to-end encryption implications.