Design a Chat System: WebSockets, Ordering, Fan-out and Offline Delivery
At 21:00 on a festival evening, message volume on a chat app triples in eight minutes. One gateway node, holding 180,000 open WebSockets, runs out of memory and dies. Within two seconds 180,000 phones notice the dropped socket and reconnect at once. They hit the load balancer, get spread across the surviving gateways, and every one of them asks “what did I miss?” in the same second. The message store, already at peak, now also serves 180,000 catch-up queries. Latency on the send path climbs from 80 ms to 4 seconds, which makes more clients time out and reconnect.
Nothing in that story is exotic. A good design survives it without losing, duplicating or reordering a message. That is the bar for this capstone.
We will follow the system design framework: requirements, estimation, API, data model, high-level design, deep dives, then bottlenecks and what a staff-level answer adds.
Requirements
Functional
- 1:1 and group conversations. Groups up to 1,000 members as the main case; very large broadcast channels are a variant we will discuss.
- Send and receive in real time while the app is open, with messages in the same order for every participant.
- History: scroll back through a conversation, newest first, on any device.
- Multi-device: a user can be logged in on a phone, a laptop and a tablet at once; all stay in sync, including messages the user sent from another device.
- Offline delivery: messages sent while a device is offline arrive when it reconnects; a push notification tells the user something arrived.
- Delivery and read receipts: sent, delivered, read; per member in groups.
- Presence: online, or last seen; typing indicators.
- Media: images, voice notes, files (stored outside the message path).
Non-functional
- No lost messages once the sender sees “sent”. No duplicates shown to users.
- Per-conversation ordering: everyone sees the same order within a conversation. No global order across conversations is needed.
- Latency: p99 under 300 ms from send to delivery when both users are online in the same region.
- Availability: sending works during the loss of a node or an availability zone; degrade presence and receipts first.
- Privacy: end-to-end encryption for 1:1 and small groups, so the server cannot read message bodies.
Explicitly out of scope: voice and video calls, search over message bodies (impossible server-side with E2EE anyway), bots.
Estimation
Use the calculator to reproduce the numbers below: set DAU to 100M, writes per user to 40, object size to 0.5 KB, read ratio to 5, then watch peak QPS and storage.
The conclusions that drive the design: the write rate is high but evenly spread over millions of conversations, so storage must partition by conversation; the connection count, not the message rate, sizes the gateway fleet; and history storage grows by petabytes per year, so it must be a horizontally scalable store with cheap appends. The arithmetic habits behind this are in back-of-envelope estimation.
API
Real-time traffic goes over one long-lived WebSocket per device. Why WebSockets rather than SSE or polling is covered in real-time: polling, SSE, WebSockets and webhooks: chat needs low-latency traffic in both directions on one connection.
Frames, client to server and server to client:
// client -> server: send
{"type":"send","client_msg_id":"0193a8c2-7e41-7b2e-9f0a-1c2d3e4f5a6b",
"conversation_id":"c_5521","ciphertext":"...","media_ref":null}
// server -> client: ack for the sender
{"type":"ack","client_msg_id":"0193a8c2-...","message_id":"m_9f3b","seq":1042,
"server_ts":"2026-11-30T21:00:04.112Z"}
// server -> client: delivery to recipients and the sender's other devices
{"type":"msg","conversation_id":"c_5521","seq":1042,"message_id":"m_9f3b",
"sender":"u_17","ciphertext":"..."}
// client -> server: receipts (monotonic, per conversation)
{"type":"receipt","conversation_id":"c_5521","delivered_up_to":1042,"read_up_to":1040}
REST endpoints for everything that is not a live stream:
GET /v1/sync?cursor=<opaque> changes since this device's cursor
GET /v1/conversations/{id}/messages?before_seq=1042&limit=50
POST /v1/conversations create 1:1 or group
POST /v1/conversations/{id}/members
POST /v1/media/uploads returns a presigned upload URL
PUT /v1/devices/{id}/push-token
Three API decisions matter. client_msg_id is generated by the sender (a UUIDv7, see distributed ID generation) and makes send idempotent: a retried send after a lost ack returns the original seq. History pagination uses seq as a cursor, never offsets, as in pagination patterns. Media uploads go straight to object storage through a presigned URL, as in designing file uploads, and the message carries only a reference.
Data model
Messages are written once, read mostly as “the latest N in this conversation”, and grow without bound. That is the textbook case for a wide-column store such as Cassandra or ScyllaDB (LSM-based, so appends are cheap; see storage engines). DynamoDB with the same key design also works.
-- message history, partitioned by conversation and bucket
CREATE TABLE messages (
conversation_id text,
bucket int, -- seq / 50000
seq bigint,
message_id text,
client_msg_id uuid,
sender_id text,
ciphertext blob,
media_ref text,
server_ts timestamp,
PRIMARY KEY ((conversation_id, bucket), seq)
) WITH CLUSTERING ORDER BY (seq DESC);
-- per user list of conversations, newest activity first
CREATE TABLE user_conversations (
user_id text,
last_activity timestamp,
conversation_id text,
last_seq bigint,
PRIMARY KEY ((user_id), last_activity, conversation_id)
) WITH CLUSTERING ORDER BY (last_activity DESC, conversation_id ASC);
Membership, conversation metadata (name, type, next_seq) and device records are small, relational and need conditional updates, so they live in a sharded SQL store or DynamoDB, keyed by conversation id and user id respectively. Read receipts are a per-member “last read seq” on the membership row. Connection state lives in an in-memory registry (next section), not in any of these.
Why bucket the partition? Without it, a busy group’s partition grows forever, and Cassandra-style stores degrade when a single partition reaches hundreds of megabytes (compaction, repair and reads all work on whole partitions). Bucketing by seq / 50000 caps a partition at 50,000 messages, about 25 MB, and keeps the bucket computable from the seq alone, so reading backwards from seq 1,042 needs no lookup. Time buckets (one partition per conversation per 10 days, say) work too and are what Discord has described publicly for its ScyllaDB message store; seq buckets avoid empty partitions for quiet conversations. Partitioning principles are in sharding and partitioning.
High-level design
flowchart LR
D["Devices"] -->|"WebSocket over TLS"| LB["L4 load balancer"]
LB --> GW["Gateway nodes<br/>hold sockets"]
GW -->|"send"| CS["Chat service<br/>assigns seq"]
CS --> MS[("Message store<br/>Cassandra / ScyllaDB")]
CS --> META[("Conversations<br/>and members")]
CS --> LOG["Delivery log<br/>Kafka, key = conversation"]
LOG --> RT["Router / fan-out"]
RT --> REG[("Connection registry<br/>Valkey")]
RT -->|"to owning gateway"| GW
RT --> PN["Push service<br/>APNs / FCM"]
GW -->|"heartbeats"| PR["Presence service"]
style CS fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style MS fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style GW fill:#E1F5EE,stroke:#0F6E56,color:#085041
style LOG fill:#FAEEDA,stroke:#854F0B,color:#633806
style PN fill:#F1EFE8,stroke:#888780,color:#444441
The responsibilities are split so that each tier scales on its own dimension:
- Gateways are connection holders. They terminate WebSockets, authenticate the device, forward client frames to the chat service and push server frames down. They hold almost no business state, so a gateway can die and its clients reconnect anywhere.
- Chat service owns the write path: validate membership, dedupe on
client_msg_id, assign the conversation sequence number, persist, and emit a delivery event. It is stateless apart from the sequencing discussed below. - Delivery log (Kafka, keyed by conversation id) decouples persisting from delivering. A slow router or a burst of fan-out never slows the sender’s ack, and per-partition order preserves per-conversation order (see Kafka internals).
- Router consumes the log, looks up each recipient device in the connection registry, and sends the frame to the right gateway, or hands it to the push service when no device is online.
The send path, step by step
sequenceDiagram participant A as Alice phone participant G1 as Gateway 1 participant C as Chat service participant S as Message store participant K as Delivery log participant R as Router participant G2 as Gateway 7 participant B as Bob laptop A->>G1: send client_msg_id, c_5521 G1->>C: forward C->>C: check member, dedupe, seq = 1042 C->>S: write message C->>K: append delivery event C-->>G1: ack seq 1042 G1-->>A: ack, show sent K->>R: event c_5521 seq 1042 R->>R: registry lookup Bob devices R->>G2: deliver G2->>B: msg seq 1042 B-->>G2: delivered_up_to 1042
Alice sees “sent” only after the message is durable in the store, so an ack is a promise. The append to the delivery log happens after the store write; if the chat service crashes between them, the message is stored but undelivered. Two things cover that gap. The recipient’s next sync fetches it anyway, because sync reads the store. And if you want real-time delivery to be guaranteed too, write the delivery event through a transactional outbox or drive the log from the store’s CDC feed, rather than as a second independent write.
Deep dives
Connection layer: gateways and the registry
Each device holds one WebSocket to one gateway. The load balancer is L4 (TCP) or a WebSocket-aware L7 proxy with long idle timeouts; either way connections are sticky for their lifetime by nature. See load balancing for the trade-offs.
The router needs to know where each device is. The connection registry maps user_id to a set of (device_id, gateway_id, connected_at) entries, stored in an in-memory store such as Valkey or Redis, sharded by user id. A gateway writes the entry on connect, refreshes its TTL on heartbeat, and deletes it on clean disconnect. If the gateway dies, entries expire within one TTL (say 90 s); until then, deliveries to that gateway fail fast and fall back to push.
Routing a message to a gateway: each gateway exposes an internal RPC endpoint, or subscribes to its own channel gw:<id> on a pub/sub bus. The router publishes only to the gateways that hold recipients. The anti-pattern to avoid is every gateway subscribing to every user’s channel, or broadcasting every message to every gateway: with 250 gateways that multiplies internal traffic by 250.
Gateway capacity is about memory and file descriptors, not CPU: raise the open file limit well beyond the common default of 1,024, and drain gateways on deploy by asking clients to reconnect in batches.
Ordering: per-conversation sequence numbers
Timestamps cannot order messages: device clocks are wrong, server clocks drift by milliseconds, and two messages in the same millisecond are common in busy groups (why is covered in time, clocks and ordering). Instead, every message gets a sequence number that is dense and increasing within its conversation. Clients render by seq, and a gap (receiving 1,044 after 1,042) tells the client to fetch 1,043.
Who assigns the sequence? It must be one writer per conversation at a time. Options:
- Conditional increment in the metadata store.
UPDATE conversations SET next_seq = next_seq + 1 WHERE id = ? AND next_seq = ?(or DynamoDBUpdateItemwith a condition). Simple and correct; costs one strongly consistent write per message, which is fine because the 140,000 messages/s spread over millions of conversation rows. - Conversation ownership. Route each conversation to one chat-service instance with consistent hashing; the owner assigns seq in memory and persists it with the message. On ownership change the new owner reads the max seq from the store. This needs a lease and a fencing token so a paused old owner cannot assign duplicate numbers, the problem covered in leader election, leases and locks.
- Kafka partition offset. Tempting, but offsets are per partition, not per conversation, and they are not dense for one conversation. Avoid.
Option 1 is the right default in an interview; mention option 2 for very hot groups where the conditional write becomes contended. Message ids themselves can be Snowflake-style or UUIDv7 ids, globally unique and roughly time sortable; they identify a message, while seq orders it.
Delivery semantics and client dedup
The transport is at-least-once end to end, and the system is designed so that duplicates are harmless. This is the pattern from delivery semantics and exactly-once: at-least-once delivery plus idempotent handling gives an exactly-once effect.
- Sender to server. The client keeps unacked messages in a local outbox and resends after a timeout with exponential backoff and jitter (see timeouts, retries and backoff). The server dedupes on
(conversation_id, client_msg_id)and returns the original seq. - Server to device. The gateway pushes; the device acks with
delivered_up_to. Unacked frames are not retried by the gateway forever; the safety net is sync. - Sync. Each device stores, per conversation, the highest contiguous seq it has. On reconnect it calls
/v1/syncand receives every conversation whoselast_seqis higher, then pages the missing range. The device inserts messages keyed by(conversation_id, seq), so a message seen twice, once from the live push and once from sync, is stored once.
Because the device’s local database is keyed by seq, the user never sees duplicates, and because sync reads the durable store, the user never misses a message that the sender saw acked.
Offline delivery and push notifications
If the registry shows no online device for a recipient, the router hands the message to the push service, which sends through Apple Push Notification service (APNs) for iOS and Firebase Cloud Messaging (FCM) for Android and web. Both cap payloads at about 4 KB and both are best effort: they may delay, coalesce or drop notifications. So push is a hint, never the delivery mechanism; the message itself arrives through sync when the app opens.
Practical rules: use a collapse key per conversation so a busy group does not buzz 50 times, check mute settings before sending, and remove tokens the provider reports as invalid. With E2EE the server cannot write preview text, so it sends a data-only push that wakes the app to fetch and decrypt, or an encrypted payload that a notification extension decrypts on the device.
Group fan-out
Storage is always fan-out on read: a group message is written once to the conversation’s partition, never copied into each member’s inbox. What fans out is delivery and the small user_conversations update.
For a 1,000-member group with 30% online and 1.5 devices each, one message means 450 device deliveries and 1,000 user_conversations updates. At a busy 10 messages/s in that group, that is 4,500 deliveries/s and 10,000 small writes/s from one conversation. Manageable, but it shows why size limits exist.
| Group size | Delivery strategy | Notes |
|---|---|---|
| 2 to about 1,000 | Push each message to every online member device | Update each member’s conversation list |
| Thousands to millions (channels) | Push only to members viewing the channel; others get a badge update | Members pull history when they open it |
| Broadcast (one writer, many readers) | Treat like a feed | See design a news feed |
The router batches deliveries per gateway: if 40 recipients sit on gateway 7, it sends one frame batch to gateway 7, not 40 RPCs. With E2EE, very large groups become expensive for another reason (key distribution), covered below.
Presence and typing
Presence is the feature most likely to cost more than messaging. Each gateway reports heartbeats; the presence service keeps user_id -> (status, last_seen) with a TTL, so a user whose heartbeats stop for 60 to 90 s goes offline without needing a clean disconnect. This is the same heartbeat and timeout logic as gossip and failure detection, with the same trade-off: a shorter timeout detects faster but flaps more on bad mobile networks.
Typing indicators are even more ephemeral: send them only to the conversation’s online members via the gateways, throttle to one every 3 s per user, and drop them under load.
Read receipts
A read receipt is “member M has read conversation C up to seq S”. Because it only ever moves forward, store it as a monotonic maximum: read_up_to = max(current, new). Concurrent updates from two devices then merge correctly in any order, which is a grow-only register in the language of CRDTs and conflict resolution. In 1:1 chats, forward each receipt to the other participant. In groups, do not fan out every receipt; show “read by 12” by aggregating on request, or update a summary at most every few seconds.
End-to-end encryption, at intuition level
With E2EE the server stores and forwards ciphertext it cannot read. The widely used approach for 1:1 chats is the Signal Protocol, used by Signal and WhatsApp:
- Each device publishes public identity and one-time “prekeys” to the server. A sender fetches the recipient device’s prekeys and runs a key agreement offline, so the first message can be sent even if the recipient is offline. Signal has since added a post-quantum variant of this handshake (PQXDH).
- After that a double ratchet derives a fresh key for every message, which gives forward secrecy (stealing today’s key does not decrypt yesterday’s messages) and recovery after a compromise.
- Multi-device: every device has its own keys, so the sender encrypts each message once per recipient device, including the sender’s own other devices. A message to a user with 3 devices is 3 ciphertexts. That multiplies fan-out at the encryption layer.
- Groups: pairwise encryption to every member device is O(members x devices) per message. Sender-key schemes encrypt once with a group key that is distributed pairwise. The IETF Messaging Layer Security protocol (MLS, RFC 9420) uses a tree of keys so adding or removing a member costs O(log n) rather than O(n).
Design consequences: no server-side search or content moderation over bodies, push previews must be decrypted on device, backups must be encrypted with a user-held key, and the server still sees metadata (who talks to whom, when), which is its own privacy question. Key storage on the server side follows secrets management and encryption.
Multi-region
Users are spread across continents, and a cross-ocean round trip is 70 to 150 ms. The common design:
- Gateways in every region; devices connect to the nearest one.
- Each conversation has a home region, where its seq is assigned and its partition is the primary. A 1:1 between users in the same region is homed there; a cross-region conversation is homed where it was created, or where most members are.
- Sends from a remote member are forwarded to the home region, adding one cross-region hop (about 100 ms) to those sends only. Reads of history are served from a local replica.
- Message data is replicated asynchronously to other regions for local reads and disaster recovery. On a region loss, conversations fail over to another region and a new sequencer resumes from the highest replicated seq. Messages acked in the last seconds before the failure may not have replicated; clients still hold them in their local outbox and the idempotent resend fills the gap.
Active-active writes to the same conversation from two regions would need a consensus round across regions per message or would break the single-sequence ordering. That is the trade-off discussed in multi-region architecture.
Failure scenarios
| Failure | What happens | Mitigation |
|---|---|---|
| Gateway node dies | Its clients reconnect elsewhere; registry entries expire | Jittered reconnect, sync on connect, TTL on registry entries |
| Chat service crash after store write, before log append | Message stored, not pushed live | Outbox or CDC-driven delivery log; sync catches it regardless |
| Router or Kafka backlog | Live delivery slows, sends still ack | Alert on consumer lag; sends unaffected because ack precedes delivery |
| Message store partition slow | Sends to those conversations slow or time out | Client outbox retries idempotently; isolate hot conversations |
| Sequencer failover | Possible duplicate seq from a paused old owner | Conditional write on next_seq, or fencing tokens |
| Registry cluster loss | Router cannot find devices | Fall back to push for everyone; clients still sync. Degraded, not down |
| Push provider outage | Offline users not notified | Nothing lost; messages wait in the store |
| Region loss | Conversations homed there fail over | Async replica plus client resend; RPO of seconds |
Bottlenecks and trade-offs
- Fan-out vs group size. Delivery cost is linear in online member devices, and with E2EE, encryption cost is too. That is why products cap E2EE group size and treat huge channels as a different feature.
- Durable ack vs latency. Acking after the store write adds a few milliseconds of quorum write latency, but makes “sent” mean something. Acking before persistence is faster and loses messages on crashes.
- Per-conversation sequence vs throughput. A single sequencer per conversation bounds one conversation’s write rate (thousands per second with a conditional write), which is far above any human group. It also rules out multi-master writes to one conversation.
- Wide-column store vs SQL. Cassandra-style stores give cheap appends and linear scaling but no transactions across tables; that is why membership and sequence state live in a store with conditional updates. The general trade-off is in SQL vs NoSQL.
- Presence accuracy vs cost. Fewer heartbeats and subscription-based presence cut cost by orders of magnitude at the price of “last seen” being tens of seconds stale.
- E2EE vs features. You give up server-side search, moderation of content, and easy history on new devices. Decide early, because retrofitting E2EE changes the storage, push and multi-device design.
What a staff answer adds
A senior answer gets the architecture right. A staff answer also covers how it behaves on a bad day and how it evolves:
- Failure first. Opens deep dives with the reconnect storm and shows the arithmetic for jitter and sync rate limits, because that is the incident that actually happens.
- Exact guarantees. States them precisely: at-least-once transport, idempotent sends keyed by
client_msg_id, exactly-once display keyed by(conversation_id, seq), per-conversation total order, no global order. - Cost model. Notes that presence and receipts, not messages, dominate event volume, and designs them as lossy, subscription-based and sheddable first under load.
- Blast radius. Proposes cells: groups of gateways, chat service and store shards serving a slice of users, so one bad deploy or hot conversation affects a few percent of users. That pattern is in cell-based architecture.
- Operability. Names the metrics: send-to-deliver latency percentiles, delivery log consumer lag, sync and reconnect rates, push failure rate per provider.
- Product edges. Edits and deletes are new messages that reference the original seq; offline-composed messages get their seq on arrival; per-user send limits stop spam.
Interview questions
Q1: Bob has the app open on his laptop and phone. Alice sends him a message. Walk through delivery, and what happens if the phone is in a tunnel.
The chat service stores the message with seq 1,042 and appends a delivery event. The router looks up Bob in the connection registry and finds two devices on two gateways; it sends the frame to both. The laptop acks delivered_up_to 1042. The phone’s socket is half dead in the tunnel, so the frame is lost or unacked. Nothing retries it in real time; when the phone reconnects, it calls sync with its cursor (seq 1,041 for that conversation), receives 1,042 and acks. If the registry entry for the phone expired before the router ran, the router also sends a push hint. Bob sees the message once on each device because each device stores messages keyed by conversation and seq.
Q2: Why not store messages in each recipient’s inbox (fan-out on write)?
For 1:1 chats it doubles storage at best; for a 1,000-member group it multiplies storage and write rate by 1,000, and every edit or delete must touch 1,000 copies. Writing once per conversation and fanning out only delivery frames and a small conversation-list update keeps storage linear in messages. Per-user inboxes make sense for feeds where each user’s view is a ranked merge of many sources, which is a different problem (see the news feed capstone).
Q3: A group conversation gets 5,000 messages per second during a live event. What breaks first and what do you change?
The single conversation’s partition and its sequencer: all writes go to one partition key and one conditional-update row, and every message fans out to every online member. Changes: switch that conversation to an in-memory sequencer with lease-based ownership and batched persistence; increase bucket granularity so partitions stay small; stop pushing every message to every member and instead push to members who have the conversation open, with others getting a periodic badge update; apply per-user send limits. If it is really a broadcast, move it to a channel model with read-time fetch.
✅ Key takeaways
- Separate tiers by their scaling dimension: gateways scale with connections, the chat service with sends, the router with fan-out, storage with history.
- Order with a per-conversation sequence number from a single writer; render by seq and use gaps to trigger sync. Never order by timestamps.
- Transport is at-least-once; idempotent sends (
client_msg_id) plus seq-keyed client storage give exactly-once display. Sync from the durable store is the safety net for offline and multi-device. - Store messages once per conversation, partitioned by conversation and a bucket; fan out delivery, not storage.
- Presence, typing and receipts dominate event volume; make them subscription based, lossy and the first thing to shed.
- E2EE multiplies fan-out by devices, removes server-side search, and changes push; decide on it before designing storage.
🧠 Check your understanding
0 / 4-
1Two members send messages to the same group within the same millisecond. How should every member see a consistent order?
A single-writer sequence gives a dense total order per conversation that every client agrees on. Server timestamps (B) look reasonable but collide within a millisecond and differ across servers; device clocks are worse.
-
2Alice's phone sends a message, the server stores it, but the ack is lost and the phone resends. What prevents a duplicate?
An idempotency key generated by the sender makes the send safe to retry. Kafka transactions do not cover the client to server hop, and the resend may arrive on a different gateway after a reconnect.
-
3Why is push (APNs or FCM) not the mechanism that delivers messages to offline users?
Providers can delay, coalesce or drop notifications and cap payloads at about 4 KB, so push is a hint and sync is the delivery path. Push is usually fast, so A is not the reason.
-
430M users are online and each has 200 contacts. Which presence design is cheapest while still useful?
Subscription based presence cuts events by two orders of magnitude versus broadcasting to online contacts. Polling (D) looks simple but generates even more load: 200 contacts every 5 seconds per client.
Where to go next
- Design a news feed: the fan-out on write vs read trade-off where per-user timelines do make sense.
- Design ride hailing: another real-time system, with location streams and matching instead of messages.
- Multi-region architecture: homing, replication and failover in more depth.
- Cell-based architecture: limiting the blast radius of the gateway and store tiers.
Finished this lesson?
Mark it complete to track your progress across the roadmap.