The Problem#
A chat app such as WhatsApp, Messenger, Signal, Telegram or iMessage lets people send text, photos, voice notes and videos to one person or a group, and see them arrive instantly. When the recipient's phone is off, the message waits and arrives the moment the phone comes back. Two grey ticks say "delivered", blue ticks say "read", and a green dot or "last seen 5 minutes ago" tells you whether someone is around.
It looks like a simple product, but it combines several hard problems:
- Hundreds of millions of persistent connections. Unlike a website, a chat client keeps a socket open to the server for as long as the app is in use, so the server can push messages at any moment.
- Routing. The sender is connected to one server and the recipient to another, possibly in a different region. Every message must find the right connection within milliseconds.
- Durable delivery. A message must never be lost, even if a server crashes mid-delivery or the recipient is offline for days, and must not be shown twice.
- Ordering. Messages within a conversation must appear in a consistent order on every device.
- Mobile reality. Phones switch networks, sleep, lose signal in tunnels and are killed by the OS. The protocol must survive all of that and be kind to the battery.
- Multi-device and privacy. One user may have a phone, a laptop and a tablet. With end-to-end encryption, the server cannot even read the messages it routes.
A real-world analogy. Think of a postal service with a twist. Every resident has a personal mailbox at the post office (the inbox) and, while they are at home, a courier assigned to their street who can knock on their door at once (the persistent connection). When you send a letter, the post office first files a copy in the recipient's mailbox, so it can never be lost. Then it radios the courier for the recipient's street to deliver it immediately. If nobody is home, the letter waits in the mailbox, and a doorbell note (a push notification) says "you have mail". When the recipient signs for the letter (an acknowledgement), the post office throws away its copy. The hard parts are knowing which courier covers which street when millions of people move around all day, and making sure no letter is lost or delivered twice.
This case study designs a WhatsApp-scale messaging system: connection servers, message routing, storage, receipts, ordering, offline delivery and push, presence, multi-device support and a note on end-to-end encryption. It builds directly on Pattern: Pushing Realtime Updates and Polling, Long Polling, SSE, WebSockets and Webhooks.
Clarifying Questions#
| Question | Why it matters | Assumed answer |
|---|---|---|
| 1:1 only, or groups too? Maximum group size? | Group size drives fan-out and channel design | Both; groups up to a few hundred members (WhatsApp's limit has grown over time to 1,024) |
| How many users? How many online at once? | Connection count sizes the gateway fleet | 2B monthly users, about 500M connected at peak |
| How many messages per day? | Throughput of routing and storage | About 100B messages a day, mostly 1:1 |
| Is message history stored on the server forever? | Storage model differs completely | WhatsApp-style: server stores messages only until delivered (up to 30 days); history lives on devices. We also discuss the Slack and Messenger model of permanent server history |
| Media? | Large blobs need a separate path | Yes: images, video, voice, documents up to about 2 GB |
| Delivery and read receipts? Typing indicators? | Extra events, often more than messages | Yes, both |
| Presence (online, last seen)? | Can create huge write and fan-out load | Yes, with privacy settings |
| Multiple devices per user? | Changes inbox and encryption design | Yes: one phone plus a few linked devices |
| End-to-end encryption? | Server cannot read or index content | Yes, as a design constraint; details at a high level |
| Latency target? | Drives routing design | Under 500 ms end to end for online recipients, typically under 200 ms in-region |
| Out of scope? | Keep focus | Voice and video calls, business APIs, registration, spam systems (mentioned briefly) |
Requirements#
Functional#
- Users can create 1:1 chats and group chats (up to a few hundred participants) and add or remove members.
- Users can send and receive text messages in real time.
- Users receive messages sent while they were offline, for up to 30 days.
- Users can send and receive media (images, video, voice notes, files).
- Senders see delivery state: sent (stored on the server), delivered (reached the recipient's device) and read.
- Users can see whether a contact is online or when they were last seen, and see typing indicators.
- A user can use several devices at once, and every device receives every message.
- Offline users get push notifications for new messages.
Non-Functional#
- Low latency: under 500 ms end to end for online recipients; median well under 200 ms within a region.
- Guaranteed delivery: a message accepted by the server is eventually delivered to every recipient device (if it reconnects within 30 days), and shown exactly once.
- Ordering: messages in one chat appear in the same order on every device of every participant.
- Scale: billions of users, hundreds of millions of concurrent connections, millions of messages per second at peak.
- Minimal retention: store messages on central servers no longer than necessary (privacy and cost).
- Resilience: no single component failure (a connection server, a cache node, a whole availability zone) loses messages. Clients reconnect and resynchronise automatically.
- Mobile efficiency: small payloads, few wake-ups and efficient reconnects, to save battery and data.
- Privacy: end-to-end encryption, so the server routes ciphertext it cannot read.
Capacity Estimation#
The method is the usual one (see Back-of-the-Envelope Estimation): find which resource dominates. For chat, it is connections and event rate, not storage.
Users and connections
- 2B monthly users, about 1B daily active.
- Peak concurrently connected: about 500M sockets. That is about 25% of monthly users, counting phones in the foreground plus linked desktop and web clients.
- How many sockets per connection server? An idle persistent connection costs some kernel memory for the TCP socket and buffers, plus application state (TLS session, user id, device id, subscription handles). In a lean runtime, budget 10–50 KB per connection.
- With 64 GB of RAM, 500k–2M connections fit on one host. WhatsApp's engineers publicly described pushing a single FreeBSD server running their Erlang stack past 2 million concurrent TCP connections in 2012.
- In practice, operators run well below the maximum so that one host failure, and the reconnect storm it causes, stays small. Assume 200k–500k connections per host: 500M / 250k = 2,000 connection servers, spread over several regions.
Messages
- About 100B messages a day. WhatsApp itself has publicly cited figures of that order.
- Average: 100B / 86,400 ≈ 1.16M messages per second.
- Peak: 3–5× around New Year's Eve and major events, so plan for 5M per second.
- Most chats are 1:1. With groups, each message reaches about 2 recipient devices on average (more with multi-device). So about 2.5M device deliveries per second on average.
- Every delivered message generates a delivery receipt, and often a read receipt. Receipts plus typing indicators and presence events easily triple the event rate: plan for 5–10M small events per second average and 20M+ at peak.
Heartbeats
500M connections with a ping every 30 seconds is about 17M pings per second. Each is tiny (tens of bytes), but they still cost CPU and radio wake-ups on phones. This is why heartbeat intervals are tuned per network: carrier NAT boxes often drop idle TCP mappings after a few minutes, so intervals of 30 s to a few minutes are typical.
Storage (store-until-delivered model)
- An encrypted message envelope (ciphertext + sender, recipient device, chat id, message id, timestamps) is about 300 B–1 KB. Call it 500 B.
- Writes: 2.5M device deliveries per second × 500 B ≈ 1.25 GB per second written to inbox storage, about 108 TB a day.
- But most deliveries complete within seconds and are deleted at once. What remains is the backlog of offline devices. If 10% of deliveries wait longer than a minute and those wait one day on average, the standing inbox is about 10 TB. That is easy to hold in a distributed store with a 30-day TTL ceiling.
- Media dominates bytes. If 5% of messages carry media averaging 200 KB, that is 5B × 200 KB = 1 PB a day uploaded. Media blobs are kept up to 30 days (or until downloaded by all recipients), so the standing media store is a few PB to tens of PB. This must be object storage.
Storage (permanent-history model, like Messenger, Slack or Discord)
100B × 500 B ≈ 50 TB a day, about 18 PB a year before replication. The model changes everything: the message store becomes the biggest component, and it needs a design for time-bucketed partitions, compaction and hot channels. We cover both models.
Bandwidth
- Messaging traffic: 10M events per second × about 500 B ≈ 5 GB per second, about 40 Gbps, spread over thousands of servers.
- Media: 1 PB a day ≈ 12 GB per second ≈ 100 Gbps of uploads, plus downloads to every recipient. That goes direct to object storage and CDN edges, not through chat servers.
What these numbers tell us
- The design is dominated by connection count and small-event throughput. We need thousands of stateful connection servers and a very fast routing layer.
- Storage for text is modest if messages are deleted after delivery. The inbox is a queue, not an archive.
- Media must bypass the chat path entirely.
- Receipts, typing and presence are more frequent than messages, so they must be cheap and lossy where possible.
Core Entities#
- User: id (often derived from a phone number), profile, privacy settings.
- Device (Client): device id, user id, push token (APNs or FCM), public identity key (for encryption), last-connected time, status (active or unlinked). A user has one primary device and a few linked devices.
- Chat (Conversation): chat id, type (1:1 or group), name, created time, settings.
- ChatParticipant: chat id, user id, role (admin or member), joined time.
- Message: message id, chat id, sender user and device, server timestamp, per-chat sequence number, type (text, media, system), ciphertext payload, reply-to.
- Inbox entry: a pending delivery: recipient device id, message id, enqueued time. It is deleted when the device acknowledges.
- Receipt: message id, recipient, state (delivered or read), time.
- Attachment: attachment id, object key, size, content hash, encryption metadata, expiry.
- Presence / LastSeen: user id, online flag (ephemeral), last disconnect time (durable).
1:1 chats are simply groups with two participants, so we design for the general case.
API Design#
Chat traffic is high-frequency and bidirectional, so the main interface is commands over a persistent socket: a WebSocket over TLS, or a custom binary protocol over TLS on TCP. (Facebook Messenger's mobile apps used MQTT, and WhatsApp started from the XMPP protocol with a compact custom encoding.) A small REST API handles media upload and some account operations.
client -> server (socket) server -> client (socket)
------------------------- -------------------------
createChat { participants[], name } -> chatId chatUpdate { chatId, participants[] }
sendMessage { chatId, clientMsgId, newMessage { chatId, msgId, seq, sender,
ciphertext, attachments[] } serverTs, ciphertext }
-> { status, msgId, seq, serverTs } receipt { msgId, from, state }
ack { msgIds[] } (delivered) presence { userId, online | lastSeen }
markRead { chatId, upToSeq } typing { chatId, userId }
typing { chatId } ping { userSeq }
modifyParticipants { chatId, userId, ADD|REMOVE } syncRequired { fromSeq }
sync { lastUserSeq } -> batch of newMessage
pong { }
REST (HTTPS)
POST /v1/attachments -> { attachmentId, uploadUrl (pre-signed), expiresAt }
GET /v1/attachments/{id} -> 302 to pre-signed download URL
PUT /v1/devices/{deviceId} { pushToken, identityKey } (register or update a device)Design notes:
- Every server-to-client command that matters needs an ack.
newMessageis resent until the device acks it. That is what makes delivery guaranteed rather than best effort. The ack also clears the inbox entry and triggers the "delivered" receipt to the sender. clientMsgId(a random id chosen by the client) makessendMessageidempotent. If the client reconnects and resends, the server recognises the duplicate and returns the originalmsgId. See Idempotency and Safe Retries.seqis a per-chat sequence number assigned by the server. It gives a total order within a chat and lets clients detect gaps.markReaduses a high-water mark (upToSeq) instead of one receipt per message, so reading 50 messages sends one event.- The user and device come from the authenticated connection, established once at connect time with a device credential, not from each command.
- In an interview it is fine to list only the command names first and fill in fields as the design evolves.
High-Level Design#
We start with the simplest thing that works, a single server, and fix one limitation at a time. For infrastructure-heavy problems like this, getting the mechanics right on one node first makes the path to scale much clearer.
1) Creating chats#
A client connects (WebSocket over TLS) through a layer-4 load balancer to a Chat Server and sends createChat.
Why L4 and not L7? Many L7 load balancers support WebSockets. But their strengths, such as routing by path or header and spreading individual HTTP requests from one client across servers, do not help a long-lived socket. An L4 balancer forwards TCP connections with less overhead and keeps the connection pinned to one backend. See Load Balancing. Some systems still put a thin L7 edge in front for TLS termination and DDoS protection. That is fine, as long as it supports very long-lived connections.
The Chat Server:
- writes a
Chatrecord and oneChatParticipantrecord per member. For small groups this fits one transaction (DynamoDB transactions allow up to 100 items). Larger groups are written in batches. - returns the
chatId, - sends
chatUpdateto the other participants.
Tables.
Chatis looked up only by id: primary keychatId.ChatParticipantmust answer two queries: the members of a chat, and the chats of a user. Use a composite key with partition keychatIdand sort keyuserId, plus a global secondary index with partition keyuserIdand sort keychatId(DynamoDB keeps it in sync automatically). In Cassandra this is two tables written together.
2) Sending messages (one server)#
Assume, for now, a single Chat Server that every client connects to. It keeps an in-memory map userId → socket.
To send a message:
- The sender sends
sendMessage. - The server looks up the chat's participants.
- For each participant, it finds the socket in the map and writes
newMessageto it.
This works only if everyone is online and on the same server. That is two huge assumptions, but the mechanics are clear, so we keep going.
3) Offline delivery: the inbox#
If the recipient is offline, the message would vanish. So we make delivery durable first, real-time second:
- Every message is written to a Message table.
- For each recipient, the server creates an Inbox entry: "this device still needs this message".
- Only then does it acknowledge the sender (
SUCCESS, plusmsgIdandseq) and try to push the message to online recipients. - When a device receives the message, it sends
ack. The server deletes the inbox entry and sends a "delivered" receipt to the sender. - When an offline device connects later, the server reads its inbox, fetches the messages, pushes them, and deletes the entries as acks come back.
- Inbox and message rows get a TTL of 30 days. If a device never returns, its pending messages expire.
How much extra write load is that? With 200M active users sending 20 messages a day each, that is 4B messages a day, about 46k per second. Each 1:1 message is one Message write and one Inbox write, so with groups we are around 100k writes per second. That is comfortably within what DynamoDB or Cassandra handle when partitioned by user or device. At our full 100B a day, it is about 25× more, still a matter of more partitions and more nodes. Deletes on ack add the same again, which is why stores with cheap deletes or TTLs matter (deep dive 4).
4) Media#
Media is bandwidth- and storage-heavy, and should not flow through Chat Servers.
Bad: send media over the socket and store it in the database. Databases such as DynamoDB are not built for large blobs, and Chat Servers would spend their bandwidth shuttling bytes.
Good: the Chat Server accepts the upload and forwards it to blob storage with a 30-day TTL. Recipients download directly via pre-signed URLs. This is better, but Chat Servers still carry every byte once.
Great: upload directly to object storage with a pre-signed URL obtained from the media service (POST /v1/attachments). WhatsApp itself sends attachments through a separate HTTP service. The client:
- encrypts the file locally with a random key,
- uploads the ciphertext,
- sends a normal chat message containing the attachment id, the decryption key and a hash, all inside the end-to-end encrypted payload.
Recipients download the ciphertext with a pre-signed URL and decrypt it locally.
- Deduplication: a content hash (computed on the ciphertext, or on the plaintext only where encryption is not end to end) lets the service reuse a stored object when the same file is forwarded thousands of times. With per-message encryption keys, forwarding can reuse the already-encrypted blob and key.
- Expiry: ideally a blob is deleted once every recipient device has downloaded it. Tracking that needs a per-attachment download count, so most systems simply apply a TTL (for example 30 days).
- CDN: a CDN helps little for private 1:1 media (each blob is fetched by only a few devices), but helps for large groups and viral forwards. See Pattern: Handling Large Files and Blobs.
We now have real-time delivery, durable offline delivery and media, all on one server. Next: scale.
5) Many servers: the routing problem#
With 500M connections we need about 2,000 Chat Servers. Now the sender may be on server 1 and the recipient on server 2. Server 1 has no socket for the recipient. How does a message find the server holding the recipient's connection? This is the central design question, and deep dive 2 compares the options in detail. The design we choose:
- Chat Servers become connection servers (also called gateways): they hold sockets and do little else.
- A pub/sub layer (a sharded Redis Pub/Sub cluster, or a purpose-built router) carries messages between them. When a device connects, its server subscribes to a channel for that user (
user:{id}). To deliver to a user, any server publishes to that channel, and the subscribed server writes to the socket. - A Message Service behind the gateways handles the durable write (Message + Inbox) before publishing. Pub/sub is best-effort (at-most-once); durability comes from the inbox.
The full high-level design#
Components:
- L4 load balancer: spreads new TCP connections across connection servers, with health checks and connection draining.
- Connection servers (gateways): terminate TLS and WebSockets, authenticate the device once, run heartbeats, subscribe to the user's pub/sub channel, forward inbound commands to the Message Service and outbound events to sockets. They are stateful only in their sockets, so they can be restarted gracefully.
- Chat and Message Service: validates membership, allocates sequence numbers, writes messages and inbox entries durably, publishes to recipients, enqueues pushes for offline devices and processes acks and receipts. It is stateless and horizontally scaled.
- Stores: Chat and ChatParticipant metadata, Message, Inbox (per device), Devices, LastSeen. A distributed key-value or wide-column store (DynamoDB, Cassandra or ScyllaDB) partitioned by chat or device. See Apache Cassandra in Practice.
- Pub/Sub cluster: Redis Pub/Sub sharded by channel, carrying ephemeral delivery events between connection servers. See Redis in Practice.
- Sequence allocator: per-chat monotonic counters (for example Redis
INCR, or a conditional increment in the chat row). - Push workers: send notifications through Apple's APNs and Google's FCM for devices without a live socket. They are the notification system case study, specialised.
- Presence service: tracks online state from connection events and serves last-seen lookups.
- Session registry: which devices a user has and, optionally, which server each is connected to (used by the consistent-hashing alternative and for debugging).
- Key directory: public identity and pre-keys per device, for end-to-end encryption.
- Media service and object storage: encrypted blobs, pre-signed upload and download, TTL-based expiry.
Key Flows#
Flow 1: Sending a message to an online recipient#
- The sender's app shows the message immediately with a clock icon (optimistic UI). It sends
sendMessagewith aclientMsgIdit generated. - The Message Service checks that the sender is a member of the chat, and checks a short-lived dedupe cache for
clientMsgId. A resend after a reconnect returns the original result. - It allocates the next per-chat sequence number and stamps a server timestamp. This fixes the message's position in the chat.
- It writes the message and one inbox row per recipient device. Only after this durable write does it reply
SUCCESS, and the sender sees one tick ("sent"). - It publishes
newMessageto each recipient user's pub/sub channel. The gateway subscribed to that channel writes the message to every connected device of that user. - Each device acks. The service deletes that device's inbox row and sends a "delivered" receipt back to the sender over the same pub/sub path: two ticks.
- When the recipient opens the chat, the app sends
markRead { upToSeq }. A "read" receipt flows the same way: blue ticks (subject to the recipient's privacy settings).
Latency budget in-region: client to gateway 20–80 ms on mobile networks, durable write 5–15 ms, pub/sub hop 1–5 ms, gateway to recipient 20–80 ms. That is about 50–200 ms end to end, well under the 500 ms target. Cross-region adds one inter-region hop of 50–150 ms.
Flow 2: Reconnecting and syncing after being offline#
- While B is offline, messages accumulate in B's per-device inbox, and a push notification is sent through APNs or FCM. See deep dive 9 for what the push can contain under end-to-end encryption.
- When B's app wakes (the user taps the notification, or the OS grants background time), it connects and authenticates with its device credential.
- The gateway subscribes to B's channel first, then syncs. If it synced first, a message arriving between the sync and the subscription would be missed until the next sync. Subscribing first may produce duplicates instead, which the client drops by
msgId. - The Message Service pages through B's inbox, oldest first, in batches of, say, 100 messages, and sends them. B acks each batch, and the rows are deleted.
- The client stores messages locally (SQLite on the device), ordered per chat by
seq. History lives on the device, not on the server.
If B was offline for days with thousands of pending messages, the sync is paged and may run in the background. The client shows chats as they fill in, newest chats first.
Flow 3: Sending to a group#
For a group of N members, each with d devices:
- The Message Service writes the message once to the Message table, plus
N × dsmall inbox rows that reference it (or, in the permanent-history model, writes once and lets each device track a read cursor; see deep dive 4). - It publishes
newMessageto theN − 1recipients' user channels. For large groups, it publishes once to a group channel that member gateways subscribe to (deep dive 3). - Delivery receipts in groups are aggregated. The sender sees two ticks only when all members' devices have received the message, and blue ticks when all have read it. The server keeps a per-message counter of outstanding devices, or the sender's client aggregates individual receipts.
- Under end-to-end encryption, the sender does not encrypt the message
N × dtimes. With sender keys (see the encryption deep dive), it encrypts once with its current group sender key, and the server fans out the same ciphertext.
Data Model#
Store choice. The access patterns are simple key lookups and range scans at very high write rates: append messages, append and delete inbox rows, look up participants. That points to a horizontally scalable key-value or wide-column store: Cassandra or ScyllaDB (as Discord uses), DynamoDB, or HBase (which Facebook Messages used from 2010). A relational database is fine for chat and participant metadata at moderate scale, but the message and inbox volumes need sharding by key. See Choosing a Database: A Decision Guide and SQL vs NoSQL: How to Choose.
| Table | Partition key | Sort / clustering key | Main queries |
|---|---|---|---|
| chat | chat_id | get chat metadata, last_seq | |
| chat_participant | chat_id | user_id | members of a chat |
| user_chats (index) | user_id | chat_id | chats of a user |
| message | (chat_id, bucket) | seq DESC | recent messages of a chat, by range |
| inbox | device_id | msg_id | pending messages of a device, oldest first |
| device | user_id | device_id | devices of a user, push tokens |
| last_seen | user_id | last disconnect time | |
| attachment | attachment_id | metadata, expiry |
Keys and indexes
- Message partitions are bucketed by time (for example
bucket = 10 daysderived from the message id) in the permanent-history model. A busy group would otherwise grow one unbounded partition. Discord described exactly this scheme: messages keyed by(channel_id, bucket)with Snowflake message ids as the clustering key. - Inbox keyed by device id, sorted by message id. A sync is one partition range scan, and an ack is a point delete. Because deletes create tombstones in LSM stores like Cassandra, an inbox partition that churns heavily must be compacted regularly. Some designs keep the inbox in a log with a per-device cursor instead (deep dive 4).
- Message ids are 64-bit, time-ordered ids (Snowflake-style: timestamp, worker, sequence). They are unique without coordination, and a range of ids is a range of time.
- Per-chat
seqgives the authoritative order inside a chat. Thechat.last_seqfield, or a Redis counter backed by it, allocates the next value. - Device table per user: at most a handful of rows (one primary and, say, up to 4 linked devices).
Retention
- Store-until-delivered (WhatsApp model): inbox rows are deleted on ack. Message rows are deleted when no inbox row references them, or after a 30-day TTL. Attachments have a 30-day TTL. Optional encrypted cloud backups are the user's own (for example in their iCloud or Google Drive), outside the chat servers.
- Permanent history (Messenger, Slack and Discord models): messages are kept until the user or an admin deletes them, or a workspace retention policy expires them. Old buckets move to cheaper storage tiers.
- Receipts and presence are ephemeral: kept only as long as needed to deliver them, and last-seen is one row per user, overwritten.
- Metadata logs (who messaged whom, when) are minimised and retained only as long as abuse prevention and law require, since they are sensitive even when content is encrypted.
Deep Dives#
1) How do connection servers hold hundreds of millions of sockets?#
First, what is a WebSocket connection? A WebSocket starts life as an ordinary HTTPS request. The client sends GET /chat with the headers Upgrade: websocket and Connection: Upgrade plus a random Sec-WebSocket-Key. The server answers 101 Switching Protocols, with a hash of that key to prove it understood. From then on, the same TCP (and TLS) connection carries framed messages in both directions, with no HTTP headers per message. Each frame has a 2–14 byte header, an opcode (text, binary, ping, pong, close) and a payload. Frames from browser clients are masked, so that a malicious page cannot trick proxies into caching attacker-controlled bytes. The protocol has built-in ping and pong frames, but many apps add their own heartbeats so they can carry data such as sequence numbers. Because the connection is long-lived, every server-side cost is paid per open connection, not per request. That is what makes the connection tier different from a web tier.
Basic: One thread per connection, as in a classic blocking server. Each thread needs a stack (often 256 KB to 1 MB), so 100k connections take 25–100 GB of RAM in stacks alone, plus constant context switching. This does not scale past tens of thousands per host.
Better: Event-driven I/O. A few threads multiplex thousands of sockets each, using the kernel's readiness APIs (epoll on Linux, kqueue on BSD). A connection then costs only its socket buffers and a small state struct. Netty (Java), Go's runtime, Node.js, Rust's tokio and Erlang's BEAM VM all work this way. Erlang deserves a note: WhatsApp built its servers on Erlang, whose lightweight processes (a few hundred bytes to a few KB each) let every connection be its own isolated process with its own failure handling. That is a big part of how the company famously served huge loads with a very small engineering team.
Best: Tune the whole stack and design for operational safety:
- Kernel and memory tuning: raise file-descriptor limits (millions per process), shrink default TCP buffer sizes for mostly idle sockets, enable TCP keepalive as a backstop only, and use TLS session resumption to make reconnects cheap. Budget about 10–50 KB per connection, depending on TLS and buffer settings.
- Keep gateways thin. They authenticate, frame and unframe messages, run heartbeats and forward. Business logic lives in the stateless Message Service. A thin gateway can be restarted, upgraded or replaced without touching application code, and its crash affects only its sockets.
- Graceful draining for deploys. A gateway being upgraded stops accepting new connections and closes existing ones gradually, over 10–30 minutes, telling clients to reconnect elsewhere (a
reconnectcommand or a WebSocket close code). Closing 500k sockets at once would send 500k reconnects to the load balancer in a second: a self-inflicted thundering herd. - Client reconnect with jitter. Clients back off exponentially with random jitter (for example 1 s, 2 s, 4 s ±50%, capped at a few minutes), so a server crash spreads its reconnects over time. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.
- Capacity headroom: keep each host at 50–70% of its tested connection maximum, so the survivors can absorb a failed host's clients, or a failed availability zone's clients.
- Connection placement: with pub/sub routing, any gateway can serve any user, so the load balancer can use simple least-connections balancing. With consistent-hash routing (deep dive 2), the user must land on a specific gateway, which needs a lookup or redirect at connect time.
A rough sizing: 500M connections at 250k per gateway is 2,000 gateways. At 10M events per second, each gateway handles about 5k events per second: trivial for CPU. Memory and connection count, not CPU, size this fleet.
2) How do we route a message to the server holding the recipient's connection?#
Bad: naive horizontal scaling. Put many Chat Servers behind a load balancer and hope. A server that receives a message usually does not hold the recipients' sockets, so the message cannot be delivered in real time. It works only by accident.
Bad: a Kafka topic per user. Each user gets a topic, and the user's gateway consumes it. Kafka is not built for billions of topics. Each topic and partition carries metadata and file overhead (order of tens of KB). A billion users means tens of terabytes of overhead, plus controller metadata that no cluster can manage. "Super topics" per gateway (one topic per server holding its users' messages) fix the count, but then you are rebuilding a routing table: you must know which server holds which user, which is the actual problem. See Apache Kafka in Practice for where Kafka does fit (event streams, not per-user mailboxes).
Good: consistent hashing of users to servers. Assign every user to a specific Chat Server by hashing the user id onto a ring (see Consistent Hashing). A coordination service such as ZooKeeper or etcd holds the ring membership (see Leader Election and Coordination Services). At connect time the client is directed to the server that owns its user id. To deliver to user B, any server computes B's owner and calls it directly.
- Pros: direct server-to-server delivery with no extra broker, and the owner can keep per-user state (sequence counters, presence) in memory.
- Cons: every server needs connections to every other server, which pushes towards few, big servers. Scaling the ring moves users between servers. You must drain and reconnect them without a thundering herd, and during the move, send events to both the old and the new owner so nothing is dropped. Hot users (a large group admin) cannot be spread. All of this is solvable, and Slack's architecture uses consistent hashing for its channel servers, but it is a lot to get right.
Great: offload routing to pub/sub. Use a purpose-built message bus between gateways:
- When a device connects, its gateway subscribes to
user:{userId}on a pub/sub cluster. - To deliver, the Message Service publishes to
user:{recipientId}. Every gateway subscribed to that channel (one per connected device) receives the message and writes it to its sockets. - Redis Pub/Sub is a good fit. A channel is just an in-memory entry pointing at subscriber connections, with no storage and no offsets, so millions of channels are cheap. The cluster is sharded by channel name (hash of the user id), and each gateway connects to every shard, which is a manageable number of connections.
on device connect(user, device):
pubsub.subscribe("user:" + user, handler = forward_to_socket(device))
sync_inbox(device) # after subscribe, to avoid gaps
on sendMessage(msg):
store.write(msg); store.write_inbox_rows(msg) # durable first
reply_success(sender)
for r in recipients(msg.chat):
pubsub.publish("user:" + r, msg) # best effortThe crucial property: Redis Pub/Sub is at-most-once. If no gateway is subscribed, or a shard blips, the publish is lost. That is acceptable because the message is already durable in the inbox. The device receives it on its next sync, triggered by reconnects, heartbeats carrying sequence numbers or periodic polls (deep dive 7).
Costs. One extra hop of a few milliseconds, and gateway-to-shard connections. Throughput is rarely a concern: pub/sub is a very simple workload, and a single Redis node can forward hundreds of thousands of small messages per second. Canva, for example, published a benchmark of about 100,000 mouse-position updates per second on one Redis host at modest utilisation.
Alternatives worth naming:
- A session registry (user → gateway id in Redis) plus direct gateway-to-gateway RPC. This is a middle ground: a lookup, then a direct call.
- Purpose-built routers in large systems (WhatsApp's Erlang clusters route messages between processes natively).
- NATS or similar lightweight brokers in place of Redis.
3) Should pub/sub channels be per user or per chat, and what about large groups?#
Channels can be keyed by user (user:{id}) or by chat (chat:{id}). The right choice depends on how many chats each user has and how big they are.
Scenario 1: many small chats (each user in 250 chats, all 1:1).
- Per chat: each connected user's gateway must subscribe to 250 channels (one per chat), and a send publishes once.
- Per user: each connected user needs 1 subscription, and a send publishes once (to the single recipient).
Per user wins easily.
Scenario 2: one big chat (each user in 1 group of 100).
- Per chat: 1 subscription per user, and 1 publish per message.
- Per user: 1 subscription per user, but 99 publishes per message.
Per chat wins.
Basic: per-user channels only. This is right for WhatsApp-like traffic dominated by 1:1 chats and small groups, with a hard cap on group size.
Better: per-user channels plus batch publishing for groups. The service groups recipients by pub/sub shard and pipelines the publishes, which reduces the cost of a 100-member fan-out to a few round trips.
Best: adaptive partitioning. Large groups are the "celebrity problem" of chat: rare, but disproportionately expensive.
- Above a size threshold (say 25–50 members), a chat gets its own channel
chat:{id}. - When a device connects, its gateway subscribes to its user channel and to the channels of its large chats.
- Sends to large chats publish once to the chat channel. The gateway then forwards to the member devices it holds.
- When a chat crosses the threshold, there is a transition window: publish to both channel types for a short time, so gateways have time to subscribe before the user-level publishes stop.
For really huge audiences (broadcast channels, Telegram channels with millions of subscribers, Discord servers with hundreds of thousands of members), switch models entirely. Do not write per-device inbox rows. Store the message once in the channel's log, let each member keep a read cursor, and push only lightweight "channel has new messages" hints to online members, who then fetch. That is fan-out on read, exactly as in the news feed case study. Live-event comment streams take this further, as the live comments case study shows.
4) How should messages be stored?#
There are two very different products here, and the storage design follows the product.
Basic: one relational table messages(id, chat_id, sender, body, created_at) with an index on (chat_id, created_at). It is simple, and fine for millions of messages. At tens of billions of writes a day it needs sharding, and the index becomes the bottleneck.
Better (store-until-delivered): a durable per-device inbox. Write the message once, write one small inbox row per recipient device, delete the row on ack, and expire everything after 30 days. Storage stays small because the server is a relay, not an archive, and it matches the privacy requirement. The challenge is churn: every message is written and deleted within seconds. In LSM-tree stores (Cassandra, ScyllaDB, RocksDB), deletes are tombstones that must be compacted, and a range scan over a heavily churned partition can wade through thousands of tombstones. Mitigations:
- use time-window compaction with short
gc_graceon the inbox table, - keep inbox partitions per device (small and short-lived),
- or keep the inbox in memory with replication (talks by WhatsApp engineers described keeping offline messages in Erlang's Mnesia database, mostly in memory), with a durable log for recovery.
Best (permanent history, cursor model): for products that keep history on the server (Messenger, Slack, Discord, Teams), store each message once in a per-chat log and let each device track a cursor ("I have everything up to seq 9,481 in chat X") instead of writing inbox rows.
- Message log: partition key
(chat_id, time_bucket), clustering keyseq(or a Snowflake id), descending. Reading the latest page of a chat is a single-partition range read. Scrolling back walks buckets. - Per-device sync state: a small map
chat_id → last_acked_seq. To sync, the device sends its cursors (or the server keeps them), and the server returns messages withseq > cursorfor each chat that has newer messages. - Unread counts =
chat.last_seq − my_read_seq, so no counter needs updating per message per member. - Fan-out is then only a notification ("chat X advanced to seq 9,482"), not a copy of the message per recipient.
A real migration story. Discord publicly described its message storage evolution:
- from MongoDB to Cassandra in 2017, with messages partitioned by
(channel_id, bucket)and Snowflake ids, - then, in a migration completed in 2022 and described publicly in 2023, to ScyllaDB, with Rust-based data services in front.
The data services coalesce identical concurrent reads of hot channels (when thousands of users open the same popular channel at once, one database query serves them all) and route requests by channel for better cache locality. Their operational pain points are general lessons: hot partitions from very busy channels, compaction backlogs, garbage-collection pauses on the JVM, and the cost of tombstones from deletes.
Choosing. If the requirement is "store no longer than necessary", use the inbox model with TTLs. If the requirement is searchable, permanent, multi-device history (and the server can read it, which E2EE forbids), use the log-plus-cursor model. Hybrid products (WhatsApp with linked devices) use the inbox for delivery, plus device-to-device history transfer for new devices, so the server never holds a readable archive.
5) How do delivery and read receipts work?#
Receipts are what make users trust the system. They are also a big share of all traffic.
Basic: the server marks a message "delivered" as soon as it publishes it to the recipient's gateway. This is wrong: the socket may be dead, the app may crash before storing it, and the tick lies.
Better: end-to-end acks from the device. A message counts as delivered only when the recipient's app has written it to local storage and sent ack { msgIds }. The server then:
- deletes the inbox row,
- publishes a
receipt { msgId, state: delivered }to the sender's channel, - resends any
newMessagenot acked within a timeout (for example 2–5 s) while the socket is up. After repeated timeouts, it treats the socket as dead (deep dive 8).
The life of one message on one recipient device:
The three main states map to the familiar ticks:
- sent (one tick): the server durably stored it,
- delivered (two ticks): at least one (or, for groups, every) recipient device acked,
- read (blue ticks): the recipient opened the chat and the client sent
markRead.
Best: make receipts cheap and batched:
- High-water marks.
markRead { chatId, upToSeq }covers every earlier message in one event. Delivery acks are batched (ack { msgIds[] }) and sent with a small delay, say 100–500 ms, so a sync of 200 messages produces a handful of acks. - Coalesce receipts to the sender. If the sender is offline, keep only the latest receipt state per chat (not one per message) in their inbox, because "read up to 9,481" supersedes "delivered 9,470".
- Group receipts. Track outstanding devices per message for small groups, and show "delivered to all" or "read by all" with a per-member breakdown on request. For large groups, skip per-member read receipts entirely, or sample them, since they cost
Nevents per message. - Privacy settings. Users can disable read receipts. The client then simply does not send
markReadreceipts to others (it may still sync its own read state across its devices). - Receipts are idempotent and monotonic. Applying "read up to 9,481" twice, or after "read up to 9,490", changes nothing, which makes at-least-once delivery of receipts safe.
6) How do we keep messages in a consistent order?#
Ordering matters inside a chat, not across chats. Users must see the same order on every device, and replies must appear after what they reply to.
Basic: order by each sender's device clock. Phone clocks can be minutes off, and users can set them to anything, so messages jump around and different devices disagree.
Better: order by the server's receive timestamp. Servers synchronise clocks with NTP, which is typically accurate to within milliseconds within a data centre, though not perfectly. The Message Service stamps serverTs when it accepts a message, and clients sort by it. All clients then see the same order, even if messages arrive in a different order. Occasionally a message "pops in" above one that was sent slightly later, and users accept this. Real systems mostly choose this kind of approach: show new messages immediately rather than delay them to guarantee a perfect order. A perfect order would need a buffer that waits for late messages, like a stream processor's watermark, which adds latency for little user benefit. See Time, Clocks and Ordering.
Best: a per-chat sequence number assigned at a single point per chat:
- The Message Service atomically increments
chat:{id}:seq(RedisINCR, or a conditional update ofchat.last_seqin the database) and stamps the message with it. Within a chat,seqis a total order that every device agrees on, regardless of clocks. - Gap detection: a device that has seq 41 and receives seq 43 knows it missed 42 and asks for a sync.
- Causality for free: a reply is sent after its parent was received, so it necessarily gets a larger
seq. - Cost: one atomic increment per message on a per-chat key. 1:1 and small-group chats spread across millions of keys. A single extremely busy chat is limited to one counter's throughput (tens of thousands of increments per second for Redis), which is far above what a human conversation needs. To survive a counter-store failover without reusing numbers, combine the counter with an epoch (
(epoch, seq)), bumped on failover, or allocate from the durable chat row. - Client-side pending messages. The sender's own unsent messages are shown at the bottom in a pending state and placed at their final
seqwhen the server acks. If two people send at the same moment, both see the server's order after ack, which may swap their local order once. That is the same "pop-in", but now consistent everywhere.
Across chats there is no global order, and none is needed. A per-user sequence (one counter per recipient user, incremented for every message to them) is useful for a different purpose: detecting that a device missed any message in any chat (deep dive 7).
For multi-region chats, the sequence for a chat is allocated in the chat's home region. Messages sent from another region take one extra cross-region hop to get their seq, which is a deliberate trade of a little latency for a single, simple order.
7) What if the real-time path drops a message?#
Pub/sub is at-most-once. A publish can be lost if a Redis shard fails over, if the gateway's subscription lapsed for a moment, or if a gateway crashes between receiving and writing to the socket. The message is safe in the inbox, but a connected device would not see it until something triggers a sync. How do we close that gap quickly?
Good: periodic polling. Connected clients send sync every 30–60 seconds, and the server returns anything still in their inbox. It is simple and catches everything eventually, but costly: 500M connected devices polling every 30 s is about 17M queries per second against the inbox store, most of them returning nothing. Longer intervals cut load but raise the worst-case delay.
Good: per-chat sequence numbers with gap detection. Every message carries its chat's seq. If a device sees seq 43 after 41, it requests a resync of that chat. This detects a gap only when a later message in the same chat arrives. If the chat goes quiet after the lost message, nobody notices, so polling is still needed as a backstop.
Great: piggyback a per-user sequence on heartbeats.
- Keep a per-user delivery sequence: a counter incremented for every message destined for that user, in any chat. Store it with the inbox row.
- Every heartbeat the server sends (
ping { userSeq }) includes the user's current value. The gateway reads it from a cache, so this is cheap. - The client compares it with the highest
userSeqit has received. If it is behind, it immediately sendssync { lastUserSeq }.
A lost publish is now detected within one heartbeat interval (say 10–30 s), with no extra requests, because the heartbeat was being sent anyway. The cost is one atomic counter per user (Redis INCR) on the send path.
In practice, systems combine all three:
- heartbeats detect dead connections,
- sequence numbers (per chat for order, per user for completeness) detect missed messages,
- a slow periodic sync (every few minutes) is the final safety net against bugs in the other two.
This layered design is how "best-effort real-time plus durable inbox" gives an exactly-once experience:
- at-least-once delivery from the inbox and retries,
- deduplication on the device by
msgId, - ordering by
seq.
See Delivery Guarantees: At-Most, At-Least and Exactly-Once.
8) How do we detect dead connections and reconnect gracefully?#
Mobile connections often die silently. A phone enters a tunnel, a NAT box on the carrier network drops its mapping, or a Wi-Fi access point hands over. The socket looks open on both ends, but nothing gets through. TCP alone might not notice for many minutes.
Bad: rely on TCP timeouts. TCP keepalive defaults are measured in hours (two hours before the first probe on Linux), and retransmission timeouts take minutes. Meanwhile the app shows "connected" and misses messages, and the server keeps pushing into a black hole.
Good: ack timeouts. The server expects an ack for each newMessage within, say, 0.5–2 s, and retries a few times. After repeated failures it closes the socket, and the device is treated as offline: messages stay in its inbox, and a push notification may go out. This pairs naturally with the ack mechanism we already have, but it detects failures only while sending. A dead socket during a quiet period goes unnoticed.
Great: application-level heartbeats. The server (or the client) sends a small ping every 10–30 seconds, and the peer must answer pong within about 5 s. A missed pong closes the connection. Detection time is bounded: with a 10 s interval and a 5 s timeout, a dead connection is found within 15 s. At 500M connections and 10 s intervals that is 50M tiny messages per second, so mobile clients often use longer, adaptive intervals:
- start with a short interval,
- grow it while the connection stays healthy,
- shrink it after a failure, staying below the NAT timeout observed on that network.
See Heartbeats, Failure Detection and Gossip.
Reconnecting well:
- Exponential backoff with jitter so a regional outage does not produce a synchronised reconnect stampede.
- Fast resume. Use TLS session resumption (or 0-RTT with TLS 1.3 where safe) and a short-lived resume token that lets the gateway skip a full authentication round trip.
- Network changes. On a switch from Wi-Fi to cellular, the client proactively opens a new connection on the new interface before closing the old one, rather than waiting for a timeout. Protocols on QUIC can migrate a connection across networks natively.
- Sync after reconnect, in the order subscribe, then sync (Flow 2), with deduplication by
msgIdon the device. - Server-initiated moves. During deploys or rebalancing, a gateway sends
reconnectwith a hint, and clients spread over the next minutes.
9) How do offline devices learn about new messages (push)?#
When a device has no live socket, the system must wake it through the platform push services: APNs for iOS and FCM for Android (and web push for browsers). Apps cannot hold a socket open in the background on modern mobile operating systems, so push is the only way in.
Basic: send a push for every message to every offline device. It is simple, but a busy group generates hundreds of notifications, providers throttle senders that push too fast, and the battery suffers.
Better: push through a push queue and workers. When the Message Service finds no live socket for a recipient device, it enqueues a push job (device token, chat id, message id). Workers:
- collapse pushes per chat ("12 new messages in Family"), using collapse keys and thread identifiers so the OS shows one grouped notification,
- respect mute settings and do-not-disturb,
- rate-limit per device,
- handle provider responses: retry with backoff on throttling, and remove invalid tokens when the provider says the app was uninstalled.
The notification system case study covers this machinery.
Best: design push for end-to-end encryption and reliability:
- No plaintext in pushes. The server cannot read the message, so the push carries either a generic text ("New message") or an encrypted payload that the app decrypts in a notification service extension before showing the real preview. Alternatively, it sends a high-priority data message that wakes the app briefly to connect, sync and post a local notification itself.
- Pushes are hints, not delivery. A push can be delayed or dropped by the platform. The message itself is always fetched from the inbox when the app connects, so a lost push delays a notification but never loses a message.
- Priority classes. Use high priority for messages (they wake the device) and low priority or none for receipts and presence (they can wait until the next connect).
- Token hygiene. Tokens change on reinstall and restore. Update them on every connect (
PUT /v1/devices/{id}), and expire devices not seen in, say, 30–60 days, which also stops their inbox from filling.
10) How do presence ("online") and "last seen" work?#
Presence looks trivial but can become one of the most expensive features if done naively, because it is read and changed constantly.
Bad: write to the database on every heartbeat or action. Updating lastSeen on every heartbeat for 500M connected users at 10–30 s intervals is tens of millions of writes per second for a value that is stale the moment it is written. That is massive write amplification for little value.
Better: presence derived from connections. Two facts are already known for free:
- When a user connects, a gateway knows they are online.
- When they disconnect (cleanly, or by missed heartbeats), the gateway knows that too.
So store only the last disconnect time durably: one row per user in a LastSeen table, written once per disconnect. Use a conditional write ("only if newer than the stored value") so two gateways racing for the same user never overwrite a later time with an earlier one. "Online right now" is answered by the live connection itself, not by a table.
Best: on-demand presence queries over pub/sub, so nobody broadcasts presence to everyone:
client X -> getLastSeen { target: Y }
gateway of X, in parallel:
a) read LastSeen[Y] from the table -> publish updateLastSeen {Y, lastSeen: T} to user:X
b) publish getLastSeen {requester: X} to user:Y
gateway of Y (only if Y is connected):
publish updateLastSeen {Y, lastSeen: "ONLINE"} to user:X
client X merges: an ONLINE reply wins, otherwise show "last seen T"- Storage is one record per user, and durable writes happen only on disconnects.
- The client must handle two replies arriving a moment apart. Wait briefly, or update the UI smoothly from "last seen" to "online".
- If a gateway crashes, it cannot record disconnect times. Its users reconnect elsewhere within seconds, and writing LastSeen on connect as well limits the error.
- Subscriptions instead of polling for an open chat. While X has a chat with Y open, X's gateway can subscribe to a lightweight
presence:{Y}channel. Y's gateway publishes on connect and disconnect, and X sees the change live. When the chat closes, it unsubscribes. Presence then fans out only to people who are looking, never to every contact. - Debounce flapping. A phone that drops and reconnects every few seconds in poor coverage should not toggle the dot each time. Hold "online" for a grace period (say 10–30 s) after a disconnect before publishing "offline".
- Privacy. "Last seen" and "online" visibility settings (everyone, contacts, nobody) are checked before answering. Reciprocal rules, where you cannot see others' last seen if you hide yours, are enforced on the server.
- Typing indicators are pure ephemera. Publish
typingto the chat's participants with no storage at all, rate-limited to one every few seconds, and expire on the client after about 5 s without a refresh. Losing one is harmless.
Large-scale presence systems, such as those of social networks with presence for every friend, use the same principles: derive state from connections, store it in memory (sharded by user, replicated), push changes only to interested subscribers, and batch and debounce aggressively.
11) How do we support multiple devices per user?#
A user has a phone, a laptop and maybe a tablet. If the phone received a message while the laptop was asleep, the laptop must still get it when it wakes. The user-level inbox from the basic design can no longer track delivery, because "delivered" now differs per device.
Basic: treat the phone as the only real client and have other devices relay through it. That was WhatsApp Web's original design: the browser mirrored the phone, and the phone had to be online. It is simple for the server and keeps encryption simple, but the companion devices stop working when the phone's battery dies.
Better: make every device a first-class client:
- Devices table:
userId → [deviceId, pushToken, identityKey, lastConnected]. - Per-device inbox: inbox rows keyed by
deviceId, notuserId. A message to user B creates one row per B device. Acks clear only that device's row. - Resolve recipients to devices: the Message Service expands
participants → users → active devices. - Pub/sub is unchanged: gateways still subscribe to
user:{id}. Every gateway with a device of that user receives the publish and writes to its own sockets. - Sender's other devices also receive the message, so your laptop shows what you typed on your phone. Treat the sender's own other devices as recipients.
- Limits: cap devices per account (for example 1 primary and up to 4 linked), and deactivate devices not seen for 30+ days. This stops storage and fan-out from growing with abandoned devices.
Best: a multi-device design that also works with end-to-end encryption:
- Each device has its own identity key. Senders encrypt a copy of the message (or the message key) for each recipient device and each of their own other devices. This is client-side fan-out, which WhatsApp described when it launched multi-device support in 2021. The server cannot "copy" an encrypted message to a new device, because it cannot read it.
- Device lists must be trustworthy. If the server could silently add a device to your account, it could read your messages. So linked-device lists are signed by the primary device, and contacts' apps can show a security notice when a contact's device set changes.
- History for a new device: the server has no readable history. When you link a laptop, the phone sends an encrypted bundle of recent history directly to it (peer to peer through the server, end to end encrypted). Products with server-side history (Messenger, Slack) simply let the new device page through the server's log with cursors.
- Read-state sync: reading a chat on the laptop should clear its unread badge on the phone. The laptop sends a
markRead, the server relays it to the user's other devices as a self-receipt, and they update locally. - Primary device loss: re-registration re-establishes identity. Peers see a "security code changed" notice, which is the visible cost of strong end-to-end guarantees.
12) How do we run this across regions and survive large failures?#
Basic: one region. Users far away pay 150–300 ms extra per hop, and a regional outage takes the whole service down.
Better: regional gateways, central core. Put connection servers in many regions (close to users, where most of the latency matters: TLS handshakes and mobile round trips), and connect them over a private backbone to message services and stores in a few core regions. This improves connection latency and resilience to edge failures, but cross-region traffic is still on the critical path for every message.
Best: a multi-region, cell-based design:
- Home region per user. Each user (and each chat) has a home region where its inbox, sequence counter and metadata live, usually the region closest to where they usually connect. Stores replicate asynchronously to a standby region for disaster recovery. See Multi-Region and Global Data.
- Cross-region delivery. If A (home EU) messages B (home US), A's EU service writes the message durably in EU and forwards it over a reliable inter-region queue to B's home region. B's region writes B's inbox and publishes to B's gateway. Every hop is at-least-once with idempotent writes keyed by
msgId.
- Chat home region. For groups spanning regions, the group's
seqis allocated in the group's home region (deep dive 6), and members elsewhere receive the messages via replication. - Cells. Within a region, split the system into independent cells: full stacks of gateways, services, pub/sub and stores, each serving a slice of users (for example 10–50M). A bad deploy, a poisoned message or an overloaded pub/sub shard then affects one cell, not the whole region. A thin routing layer maps users to cells. Cells also make capacity planning linear: add a cell for each new slice of users.
- Failover. If a region fails, users' clients reconnect (with jitter) to another region. Their home is promoted from the standby replica, possibly losing the last few seconds of not-yet-replicated inbox writes. Clients still hold their own messages, and senders' clients resend any message that was not acked, so the loss is bounded and mostly self-healing. See Disaster Recovery and Backups.
- Load shedding order during overload: drop typing indicators first, then presence updates, then read receipts, then delay pushes. Never drop accepted messages. Rate-limit abusive senders at the gateway. See Rate Limiting and Throttling.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Connection server crash | 250k devices disconnect at once; reconnect storm | Clients reconnect with jittered backoff; headroom on other gateways; inbox sync on reconnect, so no loss |
| Deploys closing sockets | Self-inflicted thundering herd | Gradual drain over 10–30 min with reconnect hints; rolling deploys per cell |
| Pub/sub shard failure | Real-time deliveries lost for some users | Durable inbox first; per-user seq on heartbeats triggers sync; replicas and fast failover |
| Silent dead sockets on mobile | Messages pushed into a black hole | App-level heartbeats, ack timeouts, close and mark offline, push notification |
| Inbox tombstone build-up | Slow syncs, compaction pressure | Per-device partitions, time-window compaction, short gc grace, or a cursor model |
| Hot group or channel | One partition and one channel overloaded | Per-chat channels above a threshold; cursor model for huge groups; request coalescing on reads |
| Sequence counter failover | Duplicate or reused seq numbers | Epoch plus seq, or allocation from the durable chat row; dedupe by msgId |
| Presence write amplification | Millions of useless writes per second | Durable write only on disconnect; on-demand queries; debounced subscriptions |
| Push provider throttling or token churn | Delayed or missing notifications | Collapse per chat, per-device rate limits, invalid-token cleanup; pushes are hints only |
| Duplicate sends after reconnect | Same message shown twice | clientMsgId dedupe on server, msgId dedupe on devices |
| Region outage | Users cut off; recent writes at risk | Multi-region homes with async standby, client resend of unacked messages, cell isolation |
| Spam and abuse at scale | Floods of unwanted messages, degraded service | Gateway rate limits, reputation for new accounts, metadata-based detection, user reports |
What Interviewers Expect#
Mid-level#
- Pick WebSockets (or another persistent connection) and explain why plain HTTP polling is wasteful for chat.
- Define the command-style API with acks, and a working high-level design: chat and participant tables, a message store, an inbox for offline users, media in object storage via pre-signed URLs.
- Recognise that one server does not scale and that users on different servers need routing, even if the scaling solution has rough edges.
Senior#
- Move quickly through the basics and spend time on scale and robustness.
- Compare routing options (consistent hashing vs pub/sub) and explain why per-user Kafka topics fail.
- Make durable-write-then-best-effort-publish explicit, and close the gaps with heartbeats, sequence numbers and sync.
- Discuss channel partitioning by user versus by chat, with numbers.
- Handle multi-device with per-device inboxes, receipts with batched acks and high-water marks, ordering with per-chat sequence numbers, presence without write amplification, and push notifications for offline devices.
Staff+#
- Go two or three levels deeper on failure modes:
- reconnect storms and draining,
- tombstones and compaction in the inbox store,
- sequence-counter failover,
- lost pub/sub messages,
- push being only a hint.
- Design for multiple regions and cells: home regions, cross-region delivery, failover semantics and what can be lost.
- Explain how end-to-end encryption reshapes the system: client-side fan-out, sender keys for groups, signed device lists, no server-side history or search, and encrypted push previews.
- Choose between the store-until-delivered and permanent-history storage models based on product and privacy requirements, and know real examples (WhatsApp, Discord, Slack).
- Bring operational judgement: connection-count capacity planning, heartbeat tuning per network, overload shedding order and abuse controls with metadata only.
Deep Dive: End-to-end encryption and what it changesShow
With end-to-end encryption (E2EE), only the sender's and recipients' devices hold the keys. The servers route and store ciphertext they cannot read. WhatsApp completed its rollout of end-to-end encryption for all messages in 2016, based on the Signal Protocol. Signal uses the same protocol, and Messenger moved to default E2EE for personal chats in late 2023. Here is a high-level view: enough to design around, not to implement.
The building blocks (Signal Protocol).
- Identity keys. Each device has a long-term public/private key pair. Its public key is published in the server's key directory.
- Pre-keys. Each device also uploads a signed pre-key and a batch of one-time pre-keys. They let someone start an encrypted session with you while you are offline, which chat requires.
- X3DH key agreement ("Extended Triple Diffie-Hellman", specified by Moxie Marlinspike and Trevor Perrin, 2016). The sender fetches your identity key, signed pre-key and one one-time pre-key, and combines several Diffie-Hellman computations into a shared secret. Nobody else can compute it, and you derive it when you receive the first message.
- Double Ratchet (Perrin and Marlinspike, 2016). Every message is encrypted with a fresh key. A symmetric "hash ratchet" moves forward on every message, and a Diffie-Hellman ratchet mixes in new key material whenever the conversation turns around. This gives:
- forward secrecy: stealing today's keys does not decrypt past messages,
- post-compromise security: after a compromise, security heals once new DH material is exchanged.
- Sender keys for groups. Encrypting every group message separately for each of 200 members' devices would be expensive. Instead, each member distributes a sender key to every other member once (over the pairwise encrypted sessions). Afterwards the sender encrypts each group message once, and the server fans out the same ciphertext. When someone leaves the group, senders rotate their sender keys so the departed member cannot read new messages.
What E2EE changes in the system design.
| Area | Without E2EE | With E2EE |
|---|---|---|
| Fan-out | Server copies one plaintext message | Client encrypts per device (1:1) or once with a sender key (groups); server fans out ciphertext |
| Multi-device | Server syncs history to new devices | Each device has its own keys; history is transferred device to device |
| Search | Server-side full-text index | Search runs only on the device's local database |
| Push previews | Server puts text in the notification | Generic text, or an encrypted payload decrypted on the device |
| Spam and abuse | Content scanning on server | Metadata signals, rate limits, user reports (the reporter's device forwards the messages) |
| Backups | Server already has history | Optional client-encrypted backups (WhatsApp added end-to-end encrypted backups in 2021) |
| Link previews | Server fetches URLs | Sender's device fetches the preview and sends it encrypted |
| Media | Server can transcode | Client encrypts the file; the server stores an opaque blob and cannot transcode or scan it |
What the server still sees: metadata. Who talks to whom, when, from which IP, message sizes and group membership are all visible unless more is done. Techniques to reduce this exist, such as Signal's "sealed sender", which hides the sender's identity from the server for delivery. Data minimisation (not logging what is not needed) is the main defence in a WhatsApp-like design.
Trusting the key directory. The weak point of E2EE is the key directory. If the server handed you the wrong public key for a contact, it could sit in the middle. Defences:
- Safety numbers and QR codes that users can compare in person.
- "Security code changed" notices when a contact's keys change.
- Key transparency: an append-only, auditable log of key directory changes, so a malicious change would be publicly detectable. WhatsApp announced a key transparency deployment in 2023.
Post-quantum. Messaging protocols are adding post-quantum key agreement to protect today's traffic against future quantum computers ("harvest now, decrypt later"). Signal introduced PQXDH in 2023, and Apple announced PQ3 for iMessage in 2024. For the system design, the main effect is larger key material and pre-key bundles, which affects key-directory storage and first-message size, but not the routing architecture.
Interview framing. You are rarely asked to design the cryptography. You are expected to know that E2EE moves encryption and fan-out decisions to clients, removes server-side history and search, changes push and backups, and leaves metadata as the privacy frontier. Mention it early, because it constrains the storage model.
Deep Dive: The maths of a chat systemShow
1. Connection memory. Suppose each idle connection costs:
- 4 KB of kernel socket state,
- 2 × 4 KB of minimum TCP buffers (receive and send, after tuning down from larger defaults),
- 5–20 KB of TLS and application state,
for a total of about 20–30 KB. A 64 GB host with 48 GB available for connections holds about 48 GB / 25 KB ≈ 1.9M connections. That is the same order as the 2M-connection milestone WhatsApp reported in 2012. Operating at 250k connections per host leaves room for bursts of traffic, larger buffers on active sockets and the reconnect storm from a failed neighbour. A useful rule: size by memory and failure blast radius, not CPU.
2. The blast radius of one host. If a host with C connections dies and clients reconnect with jittered exponential backoff averaging T seconds, the load balancer and auth service see about C / T new connections per second. With C = 250k and T = 10 s, that is 25k connections per second, each with a TLS handshake (a few ms of CPU each without resumption). Spread over 50 neighbouring gateways, that is 500 handshakes per second each: fine. With C = 2M and no jitter, the same failure is 2M handshakes within a second or two, which can cascade. Smaller hosts and jitter trade a little efficiency for much better failure behaviour.
3. Heartbeat cost and detection time. With interval I and timeout τ, the worst-case detection time is I + τ, and the ping rate is connections / I.
| Interval I | Pings per second (500M conns) | Worst-case detection (τ = 5 s) |
|---|---|---|
| 10 s | 50M | 15 s |
| 30 s | 16.7M | 35 s |
| 120 s | 4.2M | 125 s |
On the server side, pings are cheap. On phones, every wake-up of the cellular radio costs battery (the radio stays in a high-power state for several seconds after each transfer). So mobile clients prefer longer intervals, with the server detecting failures through ack timeouts while messages are flowing.
4. Inbox backlog (Little's law). The number of inbox rows waiting is L = λ × W, where λ is the delivery rate and W the average time until ack. Most deliveries are acked within a second, but offline devices wait hours. Suppose:
- 2.5M device deliveries per second,
- 90% acked within 1 s,
- 10% waiting an average of 8 hours (28,800 s).
Then L ≈ 2.5M × (0.9 × 1 + 0.1 × 28,800) ≈ 7.2 billion pending rows. At 500 B each, that is about 3.6 TB, replicated three times: about 11 TB. The 30-day TTL bounds the worst case, and the long tail of devices that never come back is cut by expiring dead devices.
5. Group fan-out. For a group of N members with d devices each, one message costs:
- 1 message write,
N × dinbox rows (or 1 log append plus cursor updates in the cursor model),N − 1publishes (or 1 with a chat channel),- up to
N × ddelivery acks, Nread receipts.
With N = 200 and d = 2, one message creates about 400 inbox rows and up to 400 acks. A group that sends 10 messages a minute adds about 130 operations per second for one group. That is why per-member receipts are dropped or summarised for large groups, and why huge groups switch to the cursor model.
6. Sequence counters. A per-chat counter in Redis handles roughly 100k increments per second per shard. Spread across millions of chats, the total of 1–5M increments per second needs a few dozen shards. No single human chat comes close to a counter's limit. The only hotspots are bots or huge broadcast channels, which are handled by the cursor model with ids from a time-ordered generator instead of a strict counter.
7. End-to-end latency budget. End-to-end p99 is roughly the sum of each hop's p99 only if the slow cases coincide. In practice it is dominated by the slowest hop, usually the recipient's mobile last mile. For a 500 ms p99 target with mobile hops at 80–150 ms p99 each, the server side (write + publish + gateway) must stay under about 100 ms at p99. That rules out synchronous cross-region calls on the hot path for in-region conversations.
Deep Dive: How real messaging systems are builtShow
These summaries stick to what the companies have described publicly.
WhatsApp.
- Built on Erlang/OTP, originally starting from the open-source ejabberd XMPP server and heavily customised, with a compact binary protocol instead of verbose XML.
- Ran on FreeBSD for years. Its engineers described tuning a single server past 2M concurrent connections in 2012.
- Uses Erlang's lightweight processes (one per connection or session) and its message passing for routing inside clusters, with Mnesia (Erlang's built-in distributed database) used for parts of the state, such as offline messages.
- Is famous for serving hundreds of millions of users with a very small engineering team. Erlang's fault isolation ("let it crash" supervision trees) and hot code loading reduced operational work.
- Uses the store-until-delivered model, with media sent through a separate HTTP service and a 30-day window for undelivered content.
- Is end-to-end encrypted with the Signal Protocol. Multi-device support (2021) uses per-device keys and client-side fan-out.
Discord.
- Stores trillions of messages. It moved from MongoDB to Cassandra around 2017, with messages partitioned by
(channel_id, bucket)and Snowflake ids, then to ScyllaDB in a migration completed in 2022. - Placed Rust data services between the API and the database. They coalesce identical concurrent queries (a burst of users opening the same hot channel triggers one database read) and route requests consistently by channel.
- Has servers with very large member counts, where messages are stored once per channel and members fetch them, rather than per-member inboxes.
- Its real-time gateway is written in Elixir, which runs on the Erlang VM: the same lightweight-process model as WhatsApp.
Slack. Slack's engineering blog describes its real-time messaging architecture with distinct server roles:
- Gateway servers, deployed in many regions, hold WebSocket connections and subscriptions.
- Channel servers are stateful, in-memory servers that own channels, assigned by consistent hashing. They receive messages and fan them out to the gateways subscribed to each channel.
- Admin and presence servers handle the other duties.
Messages are persisted through Slack's web application and database tier (MySQL sharded with Vitess) before being broadcast. Workspaces keep permanent, searchable history, which is the permanent-history model.
Facebook Messenger.
- Its mobile apps used MQTT, a lightweight publish/subscribe protocol designed for unreliable networks, to keep a persistent connection with low battery and data cost.
- Facebook Messages stored messages in HBase from 2010. Facebook later wrote about migrating Messenger storage to MyRocks (MySQL on RocksDB).
- Meta rolled out default end-to-end encryption for personal Messenger chats in late 2023. That required new storage for encrypted history across devices.
Common lessons.
- Thin, massively concurrent connection tiers (BEAM VM, epoll-based runtimes).
- Durable storage separate from real-time routing.
- Per-chat ordering with time-ordered ids.
- Request coalescing for hot reads.
- Storage designed for append-heavy, time-bucketed data with deletes.
Deep Dive: Message features beyond text (edits, deletes, reactions, replies, disappearing messages)Show
Modern chat apps add many features on top of "send a message". Each one is easiest to design as another kind of message in the same ordered stream, not as a mutation of stored state.
Model every change as an event in the chat. A reaction, an edit or a delete is a small message with its own msgId and seq, carrying a reference to its target (targetMsgId). It flows through the same pipeline: durable inbox, pub/sub, acks, multi-device and E2EE. Each device applies events to its local database in seq order. This has big advantages:
- Ordering and delivery guarantees come for free.
- Offline devices catch up correctly: they receive the original, then the edit, in order.
- With E2EE the server never needs to understand the change. It cannot read the original anyway.
Edits. edit { targetMsgId, newCiphertext }. Devices replace the displayed text and show "edited". Limit edits to a time window (WhatsApp allows edits within 15 minutes) to keep semantics simple. If the target has not arrived yet (out-of-order delivery after a resync), the device holds the edit until the target arrives, which is easy because seq tells it what is missing.
Delete for everyone. revoke { targetMsgId }. Devices replace the message with "This message was deleted". The server also deletes any undelivered inbox copies of the original and its media blob if possible, so offline devices may never see it at all. A time limit applies. Deleting "for me" is purely local and never touches the server.
Reactions. reaction { targetMsgId, emoji }, where a newer reaction from the same user replaces the older one. Reactions are frequent and low value. Do not send push notifications for them by default, and coalesce them in inboxes (only the latest reaction per user per message matters).
Replies and quotes. A reply carries replyToMsgId plus a small quoted snippet, encrypted with the message, so the recipient can show context even if they never received or already deleted the original.
Disappearing messages. A chat setting (for example 24 hours, 7 days or 90 days) stored as a system message in the chat. Each device deletes messages locally after the timer. The server's inbox and media TTLs are already short. This is enforced on clients and is best effort against a recipient who takes screenshots, and the UI should say so.
Forwarding and virality limits. Forwarded messages carry a "forwarded" flag and a forward count. WhatsApp limits how many chats a highly forwarded message can be forwarded to at once, to slow the spread of misinformation. This is enforced on the client, because the server cannot read content, and counted via metadata in the encrypted envelope.
Polls, locations and live location. A poll is a message with options. Votes are reaction-like events, and the client tallies them. Live location sends periodic position updates as ephemeral messages for the duration of the sharing (for example every 30–60 seconds), with a TTL. These updates are shed first under overload.
Message search. Without E2EE, add an indexer that consumes the message log and writes to a search cluster partitioned by user or workspace, with access checks at query time (see Elasticsearch and Search Systems). With E2EE, search runs on the device's local database (for example SQLite full-text search). The server cannot help.
Stars, pins and archives. These are per-user state and synced across the user's devices as self-addressed events, not shared with other participants. Pinned messages in a group are shared events like edits.
The design principle: one ordered, replayable stream per chat, with idempotent events applied in order on every device. It is the same principle as event sourcing, and it is what makes multi-device sync and E2EE tractable.
Deep Dive: Variants (team chat, customer support, gaming and broadcast channels)Show
Team chat (Slack, Microsoft Teams, Discord servers). The differences from WhatsApp:
- Permanent, searchable history owned by an organisation, with retention and legal-hold policies. Use the cursor model, with time-bucketed per-channel partitions and a search index per workspace.
- Large channels of thousands of members, in many of which most members are idle. Push "channel advanced" hints only to members currently viewing or with notifications enabled. Badges come from
last_seq − read_seq. - Threads, mentions and notification rules: a mention generates a push even when the channel is muted, so notification evaluation is per member, per message, which is handled asynchronously by a notification pipeline.
- Integrations and bots post via APIs and webhooks at machine speed. They need per-app rate limits and isolation so a runaway bot cannot flood a workspace.
- Usually no E2EE, because server-side search, compliance export and data-loss prevention require plaintext access. That is a product trade-off to state explicitly.
- Tenant isolation: shard by workspace. Very large enterprises get dedicated shards or cells.
Customer support chat (an in-app or website chat widget).
- Conversations are between a customer and an agent pool, so routing involves an assignment service (queue, skills, load) rather than a fixed recipient.
- The customer's browser often uses SSE or long polling for compatibility, and agents' consoles use WebSockets.
- History is kept permanently for quality and compliance, transcripts are searchable, and bots answer first.
In-game chat. Very low latency matters more than durability. Messages are scoped to a match or a lobby that lives for minutes. Use in-memory rooms on the game's realtime servers with no inbox. Moderation (profanity filtering, mute and report) runs inline, since content is not end-to-end encrypted.
Broadcast channels (Telegram channels, WhatsApp Channels). These are one-to-many with millions of followers. They are not chats at all, but feeds:
- store once,
- fan out on read,
- push only to subscribers who opted in to notifications, through the notification pipeline,
- cache aggressively at the edge for public channels.
The news feed case study is the right mental model. The live comments case study covers the related problem of very high write rates into one shared stream.
Chat with an AI assistant. The "other participant" is a model service that streams tokens back. Server-sent events or WebSockets carry the stream, and conversation history is stored server-side so the model has context. The ChatGPT case study covers the streaming and inference side.
Federated and decentralised messaging. Matrix, and email-like federation, connect servers run by different organisations. Each user's home server stores their rooms, and servers replicate room events to each other with signatures and conflict resolution. This trades simplicity and latency for no single operator. The Bluesky case study explores decentralisation for social networks.
Deep Dive: Designing the wire protocol for mobile networksShow
The protocol between app and server matters more in chat than in most systems, because it runs constantly, on battery and on poor networks.
Framing. WebSocket gives message framing over one TCP connection, with a small header (2–14 bytes per frame). Inside each frame, use a compact binary encoding such as Protocol Buffers, or a custom token-based format like WhatsApp's binary XMPP variant, which replaces common strings with one-byte tokens. A typical text message envelope then fits in a few hundred bytes instead of a kilobyte or more of JSON or XML. At billions of events a day, that saves bandwidth for users on metered plans and CPU on both ends.
Request ids and multiplexing. Every client command carries a small request id, and the server's reply echoes it. Many commands can be in flight on one socket at once (send three messages, mark a chat read, fetch a profile), with replies matched by id, not by order. Server pushes (newMessage, receipt) carry their own ids so the client can ack them.
Compression. Per-message compression (the WebSocket permessage-deflate extension, or application-level compression of batches) helps for sync batches and large group metadata. It does nothing for ciphertext, which is incompressible, so E2EE messages are kept small by design instead. Compression contexts also cost memory per connection, so they are often enabled only for large frames.
Versioning. Clients in the field are years old. The connect handshake declares the client's protocol version and capabilities. The server speaks the newest common dialect and can refuse truly obsolete clients with an "update required" response. New message types are ignored safely by old clients ("unknown type: show 'update the app to see this message'").
Batching and radio efficiency. Mobile radios have expensive state transitions: sending one byte can keep the cellular radio in a high-power state for several seconds. So the client and server:
- batch acks and receipts with a short delay,
- piggyback them on outgoing messages when possible,
- align heartbeats with other traffic, skipping the ping if anything else was sent recently,
- defer low-priority work (presence, profile refreshes) until the radio is already awake.
Resumable sync. Sync responses are paged with cursors, so a sync interrupted by a dropped connection resumes where it stopped instead of restarting. Large media downloads use HTTP range requests for the same reason.
Alternatives.
- MQTT is a publish/subscribe protocol designed for constrained devices. It has small headers, configurable delivery levels (QoS 0, 1, 2) and keepalives, and Facebook Messenger used it on mobile.
- XMPP is an open, extensible chat protocol, but it is verbose in its standard XML form.
- HTTP/2 or HTTP/3 server push of events via SSE works for one-way streams, but chat needs frequent sends too, so a bidirectional socket remains simpler.
- QUIC (HTTP/3's transport) adds connection migration across network changes and avoids TCP head-of-line blocking, which is attractive for mobile chat. Some large apps run custom protocols over QUIC.
See HTTP, HTTP/2, HTTP/3 and HTTPS and Client, Mobile and Frontend Considerations.
Deep Dive: Making consistent-hash routing workShow
Pub/sub is the simpler answer, but some systems route with consistent hashing instead, because it removes a hop and lets the owning server keep per-user or per-channel state in memory. Slack's channel servers are one example. If you choose it, the interviewer will expect you to handle the hard parts.
The ring. Hash each user id (or channel id) onto a ring of virtual nodes, typically 100–200 per physical server so load is even. Ring membership lives in etcd or ZooKeeper, and every server and router watches it. A change produces a new ring version. See Consistent Hashing.
Connecting. A client connecting to any edge is either redirected to its owner (the edge returns the owner's address, and the client reconnects) or proxied by the edge to the owner. Proxying keeps a stable public endpoint and lets the edge terminate TLS, at the cost of an internal hop for every byte.
Delivering. To deliver to user B, a service computes owner(B) with its cached ring and calls the owner directly. Each server keeps a pool of connections to the others. With 2,000 servers, a full mesh is 2,000 × 2,000 = 4M connections across the fleet. That is why this approach favours fewer, larger servers, or a two-tier design where only a smaller routing tier holds the mesh.
Adding or removing a server. About 1/N of users move to a new owner. The safe sequence:
- Publish the new ring version, marking the moving ranges as "in transition".
- During the transition, senders deliver to both the old and new owner. Duplicates are fine because devices dedupe by
msgId. - The old owner tells its affected clients to reconnect (to the new owner), spread over a few minutes with jitter, to avoid a herd.
- When the old owner holds no more sockets for the moved ranges, the transition is closed and double delivery stops.
Failures. When an owner crashes, its ranges move to ring neighbours. The moved users reconnect, and their state (sequence counters, presence) is rebuilt from durable storage. Messages sent during the gap are not lost, because the inbox is durable. They are delivered on reconnect sync, exactly as with pub/sub.
Hot keys. One owner per key means a single very hot channel cannot be spread. Mitigations are the same as elsewhere: split the channel's fan-out across helper servers, or move huge channels to the cursor model.
Choosing.
| Concern | Pub/sub routing | Consistent-hash routing |
|---|---|---|
| Hops per delivery | Publisher → broker → gateway | Sender → owner directly |
| Gateway placement | Any gateway for any user | User must reach its owner |
| Scaling events | Trivial: subscribe on connect | Ring changes need choreography |
| In-memory per-key state | Elsewhere (Redis) | Naturally on the owner |
| Operational complexity | Lower | Higher |
For most interviews, pub/sub is the stronger default. Mentioning how consistent hashing would be made safe shows depth.
Deep Dive: Walking through the failure cases, one crash at a timeShow
A strong way to show that a messaging design is correct is to crash each component at the worst possible moment and follow what happens to a single message. Assume A sends message M to B, who has a phone and a laptop.
1. A's connection drops before the server receives M. A's app still shows M with a clock icon. On reconnect, it resends M with the same clientMsgId. The server sees a new id and processes it normally. Nothing is lost, and nothing is duplicated.
2. The server stores M, but A's connection drops before the SUCCESS reply arrives. A does not know whether M was stored, so it resends with the same clientMsgId. The Message Service finds that id in its dedupe cache (or a unique index on (senderDevice, clientMsgId)) and returns the original msgId and seq without writing again. A shows one tick. B receives M once. This is why the dedupe key must be checked before the write, and kept at least as long as clients may retry (hours, not seconds).
3. The Message Service crashes after the durable write but before publishing. M is in the Message table and in both of B's inbox rows, but no gateway was told. B's devices learn about M through one of three paths:
- the next heartbeat carries B's
userSeq, which is now ahead of the devices' values, so they sync, - the next message in the chat reveals a gap in the per-chat
seq, - the periodic sync backstop runs.
M arrives within one heartbeat interval. A still sees one tick until B acks, which is accurate.
4. Pub/sub loses the publish. This is the same as case 3. Durability lives in the inbox, so losing the real-time hop only adds delay.
5. B's gateway receives M but crashes before writing it to the socket. B's devices are disconnected. They reconnect elsewhere with jitter, subscribe, then sync. Their inbox rows for M still exist, because no ack arrived, so M is delivered on sync.
6. B's phone receives M, but the app is killed before storing it. No ack was sent (acks are sent only after local persistence), so the inbox row remains. On the next connect, M is delivered again. The app stores it and acks. If the app did store M but died before acking, the redelivery is a duplicate, which the app drops by msgId and acks again.
7. B's phone acks, but the laptop is offline for a week. The phone's inbox row is deleted. The laptop's row remains (per-device inboxes). A sees "delivered" because at least one device of B received it, the usual product rule for multi-device. When the laptop wakes, it syncs M. If the laptop stays away for more than 30 days, its row expires. The laptop then shows a gap notice or fetches history from the phone, depending on product design.
8. The inbox store loses a replica. With replication factor 3 and quorum writes (2 of 3), the write that acknowledged A survives one replica loss. A second simultaneous loss in the same replica set could lose recent rows. That is the residual risk, bounded by placing replicas in different availability zones. See Quorums and Leaderless Replication.
9. The sequence counter fails over and repeats a number. Suppose the Redis counter for the chat loses its last few increments on failover, and M2 gets the same seq as M. The (epoch, seq) scheme prevents this: a new epoch is bumped on failover, so the new numbers sort after the old ones. Without epochs, the durable write uses a conditional insert on (chat_id, seq). A collision fails the write, and the service retries with a fresh number.
10. A whole region fails mid-flight. A message accepted in region EU but not yet replicated to the standby may be lost from the server side. A's phone, though, still holds M in its local database with the state "sent". A robust client resends any message whose delivery has not been confirmed within a long window, after failover, using the same clientMsgId. The new home region dedupes against what did replicate. The visible effect is a delay, not a loss, except in the rare case where the sender's device is also gone.
11. A push notification is dropped by the platform. B's phone is never woken, so M waits in the inbox until B opens the app (or until the OS schedules a background fetch). The message is not lost, only late. This is why pushes are treated as hints, and why apps also sync on every foreground.
12. A malicious client floods the system. The gateway's per-connection and per-account rate limits reject excess sends with a "slow down" error before they reach the Message Service. Group sends count once per recipient for limiting purposes, so a spammer cannot multiply their reach through large groups.
The pattern across all twelve cases: the durable inbox and idempotent ids make every other component allowed to fail. Gateways, pub/sub, push and even counters can lose state, and the system converges because every device eventually syncs, and every resend is recognised.
Deep Dive: Evolving the design, and operating itShow
Stage 1: one server (a prototype or a small community). A single WebSocket server with an in-memory userId → socket map, a relational database for chats and messages, and polling as a fallback. This handles tens of thousands of concurrent users on one machine. It has a single point of failure, but it is fully correct if messages are written before they are pushed.
Stage 2: durable inbox and acks (first real product). Add the inbox table, device acks, clientMsgId dedupe and push notifications. Move media to object storage. This is the step that makes delivery guaranteed, and it should come before scale work.
Stage 3: many gateways plus pub/sub (millions of users). Split thin connection servers from a stateless Message Service. Add Redis Pub/Sub for routing, heartbeats and per-user sequences for gap detection. Shard the message and inbox stores by key.
Stage 4: multi-device and E2EE (product maturity). Per-device inboxes, device lists, key directory, client-side fan-out and sender keys. This changes the client more than the server, but the server must store per-device state and treat content as opaque.
Stage 5: regions and cells (hundreds of millions). Home regions, cross-region delivery queues, cell-based isolation, graceful draining, and overload shedding by event class.
At each stage, the trigger should be a measurement: connections per host, p99 delivery latency, inbox backlog, reconnect storm size or cost.
Key metrics and SLOs. See Observability: Logs, Metrics and Traces.
- End-to-end delivery latency (send accepted → recipient ack), measured with synthetic "canary" conversations between test devices in every region, every few seconds. This single metric catches routing, pub/sub and gateway problems that component metrics miss.
- Message loss probes: canary senders number their messages, and receivers alarm on any gap that lasts longer than the sync interval.
- Connections: connected devices per gateway, connect and disconnect rates, reconnect causes (client network change, heartbeat timeout, server drain) and handshake failures.
- Inbox health: pending rows by age bucket, sync durations, tombstones per read.
- Push: send rate, provider error codes, invalid-token rate and time from enqueue to provider acceptance.
- Pub/sub: publish rate, subscription counts, shard CPU and failover events.
Testing.
- Connection-scale load tests with millions of simulated clients (lightweight bots holding real sockets), including realistic idle periods, mobile-like disconnects and mass reconnects. See Capacity Planning and Load Testing.
- Chaos drills: kill gateways, fail over pub/sub shards, partition a region. Verify: no message loss (canary gaps), bounded reconnect storms and sync catch-up time.
- Protocol fuzzing and compatibility tests: old clients live for years, so the server must accept many protocol versions. Feature flags and version negotiation happen at connect time.
- Gradual rollouts by cell, with automatic rollback on delivery-latency regression. See CI/CD and Deployment Strategies.
Security and abuse. See Security Fundamentals for System Design and Authentication and Authorization.
- Device authentication: register with a phone number verified by SMS or a call, then use a long-lived device credential (key pair) to authenticate each connection. Offer two-step verification with a PIN to stop SIM-swap takeovers.
- Authorisation on every command: a user can send only to chats they belong to. Membership is checked in the Message Service (cached), not trusted from the client.
- Rate limits on messages per second, new chats per hour and group creations, tighter for new accounts. Detect bulk messaging and contact scraping from metadata patterns.
- Transport security with TLS everywhere, in addition to E2EE, so metadata and protocol frames are protected in transit.
- Abuse reporting under E2EE: when a user reports a chat, their device sends the recent messages to the trust and safety team. This is the only way content leaves the encrypted envelope.
Production reference. WeChat's layered chat architecture (store, notify, fetch; quorum storage; regional data centers) is in More Company Architectures, and Discord's message storage and gateway at trillions of messages in Discord's engineering lessons.
Key Takeaways#
- Durable first, real-time second. Write the message and per-device inbox entries before acknowledging the sender, then publish best effort. Every gap in the real-time path is closed by inbox sync.
- Thin connection servers, stateless message services. Gateways hold sockets and heartbeats; business logic lives behind them. Size gateways by memory and failure blast radius, and drain them gradually. See Pattern: Pushing Realtime Updates.
- Route with pub/sub on per-user channels. Redis Pub/Sub channels are cheap and at-most-once, which is fine because durability lives elsewhere. Use per-chat channels above a size threshold, and the cursor model for huge groups and broadcast channels. See Pub/Sub and Event Streaming.
- Acks make receipts honest. "Delivered" means the device acked. Batch acks, use read high-water marks and keep receipts idempotent and monotonic.
- Order per chat with a sequence number assigned at one point per chat. Detect gaps with per-chat sequences, and missed messages with per-user sequences piggybacked on heartbeats. See Time, Clocks and Ordering.
- Presence without write amplification: derive it from connections, persist only disconnect times, answer on demand and push only to interested viewers. Debounce flapping.
- Multi-device means per-device inboxes, keys and receipts. With E2EE, senders fan out per device or use sender keys, and history moves device to device.
- Push is a hint, not delivery. Collapse notifications, respect mutes and keep content encrypted.
- Pick the storage model from the product: store-until-delivered with TTLs (WhatsApp) or a permanent, time-bucketed per-chat log with cursors (Slack, Discord). See Apache Cassandra in Practice and Partitioning and Sharding.
- Plan for failure at scale: jittered reconnects, cells, home regions and an explicit overload shedding order (typing, presence, receipts, pushes, never messages). See Mobile System Design.