A chat system like WhatsApp, Messenger, Slack or Discord delivers short messages between people in real time, keeps them in order, tells the sender when they were delivered and read, and catches up any device that was offline. Unlike most web systems, the server has to push data to clients, so the design revolves around hundreds of millions of long-lived connections, a way to find which server holds a given user's connection, and a message log with per-conversation ordering that devices can resume from after any failure.
Think of it like
A telephone exchange with a mailroom
When both people are at their desks, the operator patches a line straight through and a note arrives instantly. When the recipient is out, the note goes into a numbered pigeonhole and a pager buzzes in their pocket. When they return, they read every note after the last number they remember, in order, and initial each one so the sender knows it was seen. The operator's hardest job is the switchboard: knowing, at every moment, which desk each of 500 million people is sitting at.
1. Requirements
Functional
- One-to-one and group conversations (groups of up to ~1,000 members)
- Real-time delivery to online recipients
- Sent, delivered and read receipts
- Offline delivery: messages wait and arrive on reconnect, with push notifications
- Multiple devices per user (phone, desktop, web) kept in sync
- Online presence, last seen and typing indicators
- Media attachments (photos, voice notes, documents)
Non-functional
- Low latency: under ~200 ms end to end within a region for online users
- Durability: a message acknowledged to the sender is never lost
- Ordering: everyone sees a conversation's messages in the same order
- No visible duplicates despite retries on flaky mobile networks
- High availability; gateways can fail without losing messages
- Privacy: end-to-end encryption for one-to-one and group chats
- Battery and data friendly on mobile
| In scope | Out of scope (mention, then park) |
|---|---|
| Connections, routing and gateways | Voice and video calls (WebRTC; see Real-time Communication) |
| Message IDs, ordering, receipts | Stories, status updates and payments |
| Offline delivery, sync and push | Server-side full-text search of message history |
| Group fan-out and presence | Bots, integrations and moderation |
| End-to-end encryption (high level), storage | Spam and abuse detection models |
2. Back-of-the-envelope estimation
Assume 500 million daily active users, each sending about 40 messages per day, with up to 30% of them connected at the evening peak. A stored text message (IDs, sequence number, timestamps, ciphertext) is roughly 200 bytes. See Back-of-the-Envelope Estimation.
Messages
~230k /s
peaks near 700k/s
Open connections
~150M
30% of DAU at peak
Gateway servers
~300+
at ~500k sockets each
Stored history
~1.5 PB /yr
20B × 200 B × 365
3. API design
Chat uses two interfaces. A WebSocket carries real-time frames in both directions (send, ack, new message, receipt, typing). Plain HTTPS handles everything that is request/response: history, sync after reconnect, media upload, device registration. See Real-time Communication for why WebSockets beat polling here.
// client -> server: send (clientMsgId makes retries idempotent)
{ "type": "send", "clientMsgId": "a1f3-77c2", "conversationId": "c_829", "ciphertext": "Az9...", "sentAt": 1762420364000 }
// server -> sender: durably stored, here is the canonical ID and position (one tick)
{ "type": "ack", "clientMsgId": "a1f3-77c2", "messageId": "1790412261185372160", "seq": 1042 }
// server -> recipients (and the sender's other devices)
{ "type": "message", "conversationId": "c_829", "seq": 1042, "messageId": "1790412261185372160",
"senderId": "u_alice", "ciphertext": "Az9...", "serverTs": 1762420364117 }
// client -> server: cumulative receipts, one frame covers many messages
{ "type": "receipt", "conversationId": "c_829", "kind": "delivered", "upToSeq": 1042 }
{ "type": "receipt", "conversationId": "c_829", "kind": "read", "upToSeq": 1040 }
// ephemeral signals: never stored
{ "type": "typing", "conversationId": "c_829", "state": "start" }
{ "type": "ping" }# Catch up one conversation after reconnecting
GET /v1/conversations/c_829/messages?afterSeq=1040&limit=200
-> 200 { "messages": [ ... ], "hasMore": false }
# What changed while this device was away? (cursor per device)
GET /v1/sync?cursor=dev_7:88123
-> 200 { "conversations": [ { "id": "c_829", "maxSeq": 1042 }, ... ], "cursor": "dev_7:88190" }
# Register this device for push and for end-to-end encryption keys
POST /v1/devices
{ "platform": "ios", "pushToken": "f00d...", "identityKey": "BQx...", "signedPreKey": { ... }, "oneTimePreKeys": [ ... ] }
# Media goes to object storage; messages carry a reference and a decryption key
POST /v1/media -> 201 { "mediaId": "m_77", "uploadUrl": "https://upload.example.com/...signed..." }4. Data model and storage choice
| Data | Key | Store | Why |
|---|---|---|---|
| Messages | partition (conversation_id, bucket), cluster by seq desc | Wide-column (Cassandra, ScyllaDB, HBase) | Append-heavy writes, range reads of the latest N per conversation |
| Conversations and members | conversation_id; members with last_delivered_seq, last_read_seq | Sharded relational (MySQL, Postgres) | Small, relational, transactional updates (add member, change role) |
| User's conversation list | user_id → conversations by last activity | Wide-column or relational, cached | Renders the chat list screen |
| Sessions | user_id → [(device_id, gateway_id)] with TTL | Redis (in memory, replicated) | Looked up on every delivery; must be sub-millisecond |
| Devices | (user_id, device_id) → push token, public keys, sync cursor | Relational | Needed for push, encryption and multi-device sync |
| Media | media_id → encrypted blob | Object storage + CDN | Large blobs never belong in the message store. See Blob & Object Storage |
CREATE TABLE messages (
conversation_id bigint,
bucket int, -- e.g. days since epoch ÷ 10: caps partition size for busy groups
seq bigint, -- per-conversation position, assigned by the server
message_id bigint, -- Snowflake: globally unique
sender_id bigint,
client_msg_id text, -- sender-generated, for idempotent retries
ciphertext blob,
server_ts timestamp,
PRIMARY KEY ((conversation_id, bucket), seq)
) WITH CLUSTERING ORDER BY (seq DESC);
-- Newest page of a conversation: one partition, already sorted
SELECT * FROM messages WHERE conversation_id = ? AND bucket = ? AND seq > ? LIMIT 100;5. High-level architecture
Clients hold a WebSocket to a gateway. Gateways are deliberately thin and stateful: they terminate connections, authenticate, and forward frames. The stateless chat service does the real work: deduplicate, assign a sequence number, persist, then route to recipients using the session registry (which gateway holds which device). Recipients without a live connection get a push notification. Press play to follow a message.
6. Deep dive: connections and routing
A gateway holds hundreds of thousands of mostly idle sockets. Clients connect through an L4 load balancer (TCP passthrough or TLS termination) that spreads new connections across gateways; there is no need for sticky sessions because a WebSocket stays on the server it first reached. The hard question is the reverse direction: when a message for Bob arrives, which of 300 gateways has his socket? See Load Balancing.
Session registry + direct routing
- On connect, write
user → (device, gateway)to Redis with a TTL - Refresh the TTL with heartbeats; delete on clean disconnect
- Senders look up the gateway and RPC it directly
- One lookup per recipient; stale entries expire on their own
Pub/sub backplane
- Each gateway subscribes to a channel per connected user (
user:bob) - Senders publish without knowing where Bob is
- Simple to build with Redis Pub/Sub or NATS
- Millions of subscriptions; fire-and-forget delivery needs the store as backup
Deterministic placement
- Hash the user ID to a gateway with Consistent Hashing
- No lookup needed: everyone can compute the location
- The edge must steer each client to its assigned gateway
- Rebalancing on scale-out forces many reconnects
- 1
Connect and authenticate
The client opens
wss://chat.example.com, presents a token, and the gateway validates it once for the life of the socket. See Authentication & Security. - 2
Register the session
The gateway writes
session:{user}:{device} = gateway-7with a 60 s TTL and marks the user online. - 3
Heartbeat
Client and server exchange pings every ~30 s. They keep mobile NAT mappings alive, detect dead sockets (a phone that walked into a tunnel never sends a FIN) and refresh the registry TTL.
- 4
Reconnect with jittered backoff
On any drop the client retries after a random delay that grows exponentially (for example up to 30 s). Without jitter, a gateway crash makes 500k clients reconnect in the same second.
- 5
Resume, don't replay
After reconnecting the client syncs from its last stored
seqper conversation, so nothing sent while it was away is lost and nothing is shown twice. - 6
Drain for deploys
Before a gateway restarts it stops accepting new sockets and closes existing ones gradually over minutes, so the fleet absorbs reconnects smoothly.
7. Deep dive: message IDs and ordering
Wall clocks on phones are wrong and server clocks drift, so timestamps cannot order messages (see Time, Clocks & Ordering). Instead each message carries three identifiers with different jobs.
- clientMsgId
- Random ID created by the sender's device before the first attempt. Retries reuse it, so the server can recognize and drop duplicates. See Idempotency & Delivery Guarantees.
- messageId
- Globally unique, roughly time-ordered server ID (Snowflake style; see Unique ID Generation). Used for references: replies, reactions, edits, deletes.
- seq
- Per-conversation counter assigned by the server: 1, 2, 3... It defines the one true order everyone renders, and lets a client notice a gap (it has 1040 and receives 1043).
- Device cursor
- The highest
seqa device has stored per conversation (or one per-user inbox position). It is all a device needs to resume after any outage.
Single sequencer per conversation
- Route all writes for a conversation to one owner (partition by
conversation_id) - The owner assigns seq and appends in order
- Gap-free and strictly ordered
- Owner failover needs a lease or consensus. See Consensus: Raft & Paxos
Atomic counter (Redis INCR)
- Any stateless chat server can take the next number
- Simple and fast; ordering is decided at increment time
- A crash between
INCRand the write leaves a harmless gap - Counter must be replicated and survive failover without going backwards
Client timestamps
- Phones disagree by seconds or minutes
- Two members can see different orders
- Easy to forge
- Fine for display ('sent at 9:41'), never for ordering
8. Deep dive: delivery, receipts and offline sync
| State | Shown as | Triggered by | Meaning |
|---|---|---|---|
| Pending | clock icon | Message created on the device | Not yet acknowledged; the app retries with the same clientMsgId |
| Sent | one tick | Server ack after a durable write | The server has it; it will not be lost |
| Delivered | two ticks | Recipient device's delivered receipt | Stored on at least one recipient device |
| Read | two blue ticks | Recipient opens the chat (read receipt) | A human has (probably) seen it; can be disabled for privacy |
Delivery is at-least-once: a sender that loses its connection before the ack will resend, and the server may push a message to a device that already fetched it during sync. Both are harmless because the server deduplicates by clientMsgId and devices deduplicate by messageId and seq. Receipts are cumulative ('everything up to 1042'), which compresses thousands of messages into one frame and makes lost receipts self-healing: the next one covers them.
Offline delivery and multi-device sync
- Per-conversation cursors: on reconnect the device asks 'which conversations changed since my sync cursor?' and then fetches each one after its last
seq. Simple and natural with per-conversation storage. - Per-user inbox log: alternatively, every message for a user is also appended to that user's own ordered log, and each device keeps one position in it. Facebook described this model for Messenger's Iris system (2014): one ordered queue of updates per user, with a pointer per device.
- Push wakes the app: APNs or FCM notify offline devices; the notification is a hint, and the authoritative data always comes from sync.
- Retention: a Slack-style system keeps history forever. A WhatsApp-style system can delete each message from the server once every recipient device has acknowledged it, keeping undelivered messages only for a limited time (WhatsApp documents 30 days).
- New devices: a freshly linked device cannot decrypt old end-to-end encrypted history from the server, so history is transferred from an existing device or from an encrypted backup.
9. Deep dive: group chat fan-out
A group message is stored once in the conversation, then delivered to every member's devices. For small groups the chat service simply loops over members, looks up each session and routes. That breaks down for huge channels: a message in a 100,000-member community would mean 100,000 registry lookups and RPCs, most for people who are offline.
| Group size | Delivery strategy | Receipts |
|---|---|---|
| 2–256 (typical group) | Fan-out on write: route to each member's live devices, push to the rest | Per member: 'delivered to all' is the minimum over members |
| Up to ~1,000 | Same, with batched registry lookups and per-gateway batching (one RPC per gateway, not per member) | Aggregated counts ('read by 37') |
| Channels with 10k–1M members | Pub/sub per channel: gateways subscribe on behalf of their connected members; offline members just see unread counts | Usually none, or only for the sender's view |
10. Deep dive: presence and typing
Presence ('online', 'last seen 5 min ago') looks trivial but is one of the most expensive features, because every status change could be sent to every contact. A user with 500 contacts who reconnects ten times an hour on a shaky train generates thousands of updates.
- Derive it from heartbeats: a user is online while any device has a live session; mark them offline only after missing heartbeats for ~30–60 s so brief network blips do not flap. See Heartbeats & Gossip Protocols.
- Store last seen, not a stream: keep
last_active_atper user in Redis. Most screens only need it when opened. - Subscribe narrowly: push presence changes only to users who currently have that person's chat open (they subscribed when they opened it), and fetch everyone else's lazily.
- Skip it for big groups: large channels show a member count, not live presence for each member.
- Typing indicators are ephemeral: route them like messages but never persist or retry them, and expire them on the client after a few seconds.
11. Deep dive: end-to-end encryption (high level)
With end-to-end encryption (E2EE) only the participants' devices hold the keys; the server stores and routes ciphertext. WhatsApp completed its rollout of the Signal Protocol for all chats in 2016, and Messenger began making E2EE the default for personal chats in late 2023. The server's job changes in a few important ways.
- 1
Key directory
Each device generates an identity key pair and uploads its public identity key, a signed prekey and a batch of one-time prekeys. The server only distributes public keys.
- 2
Session setup (X3DH)
To message Bob for the first time, Alice fetches Bob's prekey bundle and derives a shared secret without Bob being online.
- 3
Double Ratchet
Every message advances the keys, giving forward secrecy (stealing today's keys does not decrypt yesterday's messages) and recovery after a compromise.
- 4
Multi-device
Each device has its own keys, so a message to Bob is encrypted separately for each of Bob's devices (and for Alice's other devices). Client-side fan-out grows with device count.
- 5
Groups
With Sender Keys, the sender distributes a group key to each member once (pairwise), then encrypts each group message once; the server fans out the same ciphertext.
12. Scaling, bottlenecks and failures
| Failure | Effect | Mitigation |
|---|---|---|
| Gateway crashes | Its 500k clients disconnect at once | Jittered reconnects to other gateways; registry TTLs expire; clients sync from cursors, so no message is lost |
| Chat service instance dies mid-send | Sender never gets an ack | Sender retries with the same clientMsgId; dedup returns the original ack if the write had succeeded |
| Message store partition slow | Sends to some conversations stall | Replication factor 3 with quorum writes; sends time out and retry rather than being acked early. See Quorums & Leaderless Replication |
| Registry node lost | Lookups miss, live delivery falls back to push and sync | Replicated Redis; registry is rebuilt from heartbeats within one TTL |
| Reconnect storm after a regional blip | Millions of TLS handshakes per second | Jittered backoff, connection admission limits, TLS session resumption. See Rate Limiting |
| Hot group or channel | One owner and one partition get hammered | Per-channel owner with in-memory recent history; bucketed partitions; pub/sub fan-out at the edge |
- Multi-region: home each user in a region; cross-region conversations route between regional chat services over a replicated log. See Database Replication.
- Gateways scale on connections, chat services on messages: keep them as separate fleets with separate autoscaling signals.
- Media uploads go straight to object storage, encrypted on the device; the message carries the object key and the decryption key. See Content Delivery Networks.
- Observability: track send-to-ack latency, delivery latency, reconnect rate and sync backlog per region. See Observability.
Implementation
The chat service's core handler. The idempotency claim makes sender retries safe, the per-conversation counter defines order, and the ack is returned only after the durable write. Live routing is best effort because devices also sync from the store.
import Redis from "ioredis";
interface SendFrame { clientMsgId: string; conversationId: string; ciphertext: string }
export interface StoredMessage {
conversationId: string;
seq: number;
messageId: string;
senderId: string;
clientMsgId: string;
ciphertext: string;
serverTs: number;
}
interface Deps {
redis: Redis;
insert(m: StoredMessage): Promise<void>; // quorum write to the message store
members(conversationId: string): Promise<string[]>;
deliverLive(userId: string, m: StoredMessage): Promise<boolean>; // false: no live session
notifyOffline(userId: string, m: StoredMessage): Promise<void>;
newMessageId(): string; // Snowflake
}
export class RetryLater extends Error {}
export async function handleSend(senderId: string, f: SendFrame, d: Deps) {
const members = await d.members(f.conversationId);
if (!members.includes(senderId)) throw new Error("not a member");
// 1. Idempotency: only the first attempt with this clientMsgId proceeds.
const dedupKey = `dedup:${senderId}:${f.clientMsgId}`;
const claimed = await d.redis.set(dedupKey, "pending", "EX", 86_400, "NX");
if (!claimed) {
const prior = await d.redis.get(dedupKey);
if (!prior || prior === "pending") throw new RetryLater(); // first attempt still running
return JSON.parse(prior) as { messageId: string; seq: number };
}
// 2. Order: next position in this conversation.
const seq = await d.redis.incr(`seq:${f.conversationId}`);
const msg: StoredMessage = {
conversationId: f.conversationId,
seq,
messageId: d.newMessageId(),
senderId,
clientMsgId: f.clientMsgId,
ciphertext: f.ciphertext,
serverTs: Date.now(),
};
// 3. Durable before ack.
try {
await d.insert(msg);
} catch (err) {
await d.redis.del(dedupKey); // let the client's retry start over
throw err;
}
const ack = { messageId: msg.messageId, seq };
await d.redis.set(dedupKey, JSON.stringify(ack), "EX", 86_400);
// 4. Route (in production, hand this to a queue so the ack is not delayed).
// The sender is included so their other devices stay in sync.
void Promise.allSettled(
members.map(async (userId) => {
if (!(await d.deliverLive(userId, msg)) && userId !== senderId) await d.notifyOffline(userId, msg);
}),
);
return ack; // becomes the "ack" frame: one tick
}Key takeaways
- Real-time chat needs server push: long-lived WebSockets to stateful gateways, plus a session registry that maps each device to its gateway.
- Persist before you acknowledge, and treat the message store as the source of truth; live routing and push are best-effort accelerators.
- Order per conversation with a server-assigned
seq; use a client-generatedclientMsgIdto make retries idempotent. - Receipts are cumulative messages flowing backwards: sent (server ack), delivered (device ack), read (user opened the chat).
- Devices resume from a cursor after any disconnect, which makes gateway crashes, push failures and multi-device sync the same problem.
- Small groups fan out on write; huge channels publish once and let gateways fan out in memory to connected members.
Common pitfalls
- Acknowledging a message to the sender before it is durably stored.
- Ordering by client timestamps, so members of the same group see different orders.
- Reconnecting all clients immediately after a gateway failure, creating a thundering herd; always add jitter.
- Broadcasting every presence change to every contact, which can exceed the message traffic itself.
- Treating a successful socket write as delivered instead of waiting for the device's receipt.
Interview tips
- Start by asking whether it is WhatsApp-style (E2EE, short server retention) or Slack-style (server history, search, huge channels).
- Estimate concurrent connections, not just messages per second: it sizes the gateway fleet and the heartbeat load.
- Walk one message through online delivery, offline delivery and a read receipt, naming the ID that makes each hop safe.
- Have an answer for 'what happens when a gateway dies?': clients reconnect with jitter and sync from their cursor; nothing is lost.
Real-world applications
- WhatsApp: built on Erlang (originally a modified ejabberd), reported over 2 million connections on a single server in 2012, and uses the Signal Protocol for end-to-end encryption.
- Messenger: Facebook described Iris (2014), an ordered per-user queue of updates with a pointer per device for mobile sync; message storage moved from HBase to MyRocks in later years.
- Slack: its engineering blog describes stateful channel servers placed by consistent hashing and gateway servers that subscribe to channels on behalf of connected clients.
- Discord: stores messages partitioned by channel and time bucket, migrating from Cassandra to ScyllaDB as volume grew into trillions of messages.
- Customer support chat, multiplayer game lobbies and collaborative apps reuse the same gateway, registry and cursor-sync building blocks.
Test yourself
Alice's phone loses connectivity right after sending a message and retries it 10 seconds later. What prevents a duplicate in the conversation?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.