Case Study: Chat
Chat combines two hard problems: holding hundreds of thousands of long-lived connections, and delivering messages exactly once in order to devices that go offline. It is the standard question for real-time systems.
Requirements
Section titled “Requirements”Functional
- One-to-one and group conversations (up to ~500 members).
- Send and receive messages in near real time.
- Delivery to offline users when they reconnect.
- Read receipts, typing indicators, presence.
- Message history with pagination.
Non-functional
- Delivery latency < 200 ms p99 when both parties are online.
- No message loss. No duplicate display (duplicates may arrive; the client must not show them).
- Order must be consistent for all participants of a conversation.
- Horizontal scale to 50M concurrent connections.
- Availability over strict consistency; a brief ordering anomaly is better than a dropped message.
Estimation
Section titled “Estimation”Users: 100M DAU, 50M concurrent at peakMessages: 100M users × 40 messages/day = 4B/day ≈ 46,000/s, peak 3× ≈ 140,000/sFan-out: average group size 5 → ~700,000 deliveries/s at peakStorage: 4B × 300B = 1.2 TB/day ≈ 440 TB/yearConnections: 50M, at ~50k per node → 1,000 gateway nodesMemory/conn: ~10–50 KB of buffers and state per connectionPresence: 50M keys with a TTL, a few hundred bytes eachThe connection count, not the message rate, is what shapes the architecture.
Transport: WebSocket vs polling vs SSE
Section titled “Transport: WebSocket vs polling vs SSE”| Transport | Direction | Cost | Use |
|---|---|---|---|
| Short polling | client → server | A request per interval per client; wasteful, high latency | Legacy, fallback |
| Long polling | client → server, held open | Better latency, but a request per message and reconnects | Fallback when WS is blocked |
| SSE | server → client | One HTTP connection, text only, auto-reconnect built in | Notifications, one-way feeds |
| WebSocket | bidirectional | One TCP connection, framed messages, manual reconnect/heartbeat | Chat, collaboration |
WebSocket is the right primary transport. It is a single HTTP Upgrade handshake and then a
framed, full-duplex protocol over the same TCP connection. It has no built-in reconnection,
heartbeat or delivery semantics — you build all of that.
Practical notes:
- Keep a long-poll fallback. Corporate proxies and some mobile networks break WebSockets.
- Heartbeat. Ping every 30 s; close connections that miss two pings. Half-open TCP connections are invisible without it, and they are the main cause of “ghost online” users.
- Reconnect with backoff and jitter, then resync: fetch everything after the last known message id. The client must assume messages were missed while disconnected.
Connection layer
Section titled “Connection layer”client ──WSS──→ gateway node (holds the socket, ~50k connections) │ ├─ session registry: user_id → gateway node (Redis) └─ pub/sub: gateway nodes exchange messagesEach gateway node is stateful in exactly one way: it owns sockets. It must therefore:
- Register
user_id → node_idon connect, in a shared registry with a TTL. - Subscribe to a per-user or per-conversation channel.
- Publish outbound messages to the node that owns the recipient’s socket.
Scaling the layer:
- Sticky routing is not enough across nodes; you need a lookup. The registry is a Redis hash or a dedicated presence service.
- Pub/sub fan-out: a Redis/NATS cluster carrying every message. 700k messages/s is beyond a single Redis instance, so shard by conversation id.
- Load balancer must support WebSocket upgrade and long idle timeouts.
- Graceful drain: on deploy, stop accepting new connections, send a “reconnect” control frame, wait, then close. Otherwise every deploy is a thundering herd of reconnects.
Message ordering
Section titled “Message ordering”This is the deep-dive question. Requirements differ by scope:
- Per-conversation total order. Everyone in a conversation sees the same sequence.
- No global order. Ordering across conversations is meaningless.
Approach:
- The client sends with a client-generated id (
client_msg_id) and an optimistic local timestamp for display. - The server assigns the authoritative sequence: a per-conversation monotonic counter, or a Snowflake-style id that is time-ordered and unique.
- The server broadcasts the message with its assigned
seq. - Clients order by
seq, not by local time. Clock skew between devices makes timestamps unusable for ordering.
message: { id: "01HZX...", conversation_id: "c_42", seq: 8891, sender_id: 7, client_msg_id: "u-9f2", body: "...", sent_at: "..." }Per-conversation sequence generation needs care. A single counter per conversation serialises
writes for that conversation only, which is fine: a group chat does not need 10k messages/second.
Generate it in the storage layer (a counter row with UPDATE ... RETURNING, or a per-partition
sequence in the log store).
For one-to-one chats, a Snowflake id is enough — it is unique and roughly time-ordered, and two messages in the same millisecond can be tie-broken by sender id.
Storage
Section titled “Storage”Chat is a write-heavy, append-only, read-recently workload. That is exactly the shape of a wide-column store.
messages partition key: conversation_id clustering: seq DESC -- newest first within a conversation columns: message_id, sender_id, body, sent_at, type, attachments
conversations partition key: user_id clustering: last_message_at DESC columns: conversation_id, unread_count, mutedWhy it fits:
- All reads are “latest N messages in this conversation” — a single partition, contiguous range.
- All writes are appends to that partition; no updates, no joins.
- Time-ordered clustering gives pagination for free.
Practical limits: keep partitions bounded. A conversation with 5 million messages is a hot, huge partition; split by month or cap the retained history per conversation. Relational databases handle chat fine at small scale — do not reach for Cassandra for a 10,000-user product.
Media goes to object storage; the message holds a reference and, ideally, a signed URL with a short TTL.
Delivery guarantees
Section titled “Delivery guarantees”End-to-end exactly-once is impossible. The design is:
at-least-once delivery + client-side deduplication by message id = effectively onceConcretely:
- Persist before acknowledging. The server writes the message, then acks the sender. An ack before persistence loses messages on crash.
- Retry unacked messages. The sender retries with the same
client_msg_id; the server deduplicates by(sender_id, client_msg_id)so a retry does not create a second message. - Per-recipient delivery state. For groups, track a cursor per user per conversation
(
last_delivered_seq). On reconnect, the client sends its cursor and receives everything after it. - Client dedupe. Every rendered message is keyed by its id; duplicates are dropped. This is the cheapest and most reliable layer, because it survives server bugs.
- Offline queue. Push notification plus a “you have messages” signal; the actual history is pulled on open. Do not put message bodies in push payloads.
Read receipts are the same pattern at a different granularity: last_read_seq per user per
conversation, broadcast as a lightweight event, coalesced (do not send one event per message read).
Presence and typing
Section titled “Presence and typing”Presence is deceptively expensive: it is a heartbeat problem for 50M connections.
on connect / every 30s: SET presence:{user_id} = node_id EX 60on disconnect: DEL presence:{user_id}on query: MGET presence:{a,b,c} or a pub/sub subscription to changes- A TTL slightly longer than the heartbeat interval handles crashes without a cleanup job.
- Querying presence for every member of a 500-person group on open is 500 lookups. Cache the group’s online set and update it incrementally.
- Typing indicators are ephemeral: never persist them, never guarantee delivery, coalesce to at most one event per second. Losing one is invisible.
Broadcasting every presence change to every contact is a fan-out storm. Use a subscription model (only tell users who have the conversation open) and rate-limit updates.
Scaling and failure
Section titled “Scaling and failure”- Partition by conversation id for pub/sub and storage; that keeps ordering local.
- Shard the connection registry by user id; it is a hot path on every message.
- Multi-region: connections terminate in the nearest region; messages route to the conversation’s home region. Cross-region delivery adds one RTT, which is acceptable for chat.
- Backpressure: a slow consumer must not block a gateway node. Bound per-connection outbound buffers, drop typing events first, and close connections that cannot keep up.
- Failure of a gateway node disconnects ~50k users at once. They reconnect to other nodes; the registry entries expire; clients resync from their cursor. This is why the cursor, not the socket, is the source of truth for what a user has received.
Follow-up questions
Section titled “Follow-up questions”- How do you guarantee ordering when two clients send at the same instant?
- What does the client send on reconnect, and how does the server know what it missed?
- Why can you not just use sticky sessions instead of a presence registry?
- How would you support end-to-end encryption, and what breaks in your design?
- What happens to 50k users when a gateway node dies mid-deploy?
- How do you paginate message history backwards efficiently?
Common traps
Section titled “Common traps”- Acking before persisting. It is the fastest way to lose messages and it is invisible in testing.
- Assuming WebSocket delivers in order across reconnects. TCP orders bytes within one connection; a reconnect is a new connection and a new window.
- Using client timestamps for ordering. Clock skew across devices is minutes, not milliseconds.
- Storing messages by user. History queries become “merge N mailboxes”; partition by conversation.
- Persisting typing events. They are noise; store nothing and lose nothing.
- No dedupe layer. Retries plus at-least-once delivery guarantee duplicates in the UI.