Design: chat system
Clients keep a WebSocket to a gateway; the chat service gives each message a per-conversation sequence, stores it, then delivers to online recipients or via push; clients dedup and resync from their last-seen sequence.
Fundamentals you'll use
How it works
- Clients hold a WebSocket to a gateway; a session registry maps each user to their gateway.
- Order per conversation, not globally: the conversation's owner stamps a sequence number before storing.
- Delivery is at-least-once; dedup on
client_msg_idmakes retried sends look exactly-once. - Messages are partitioned by conversation and time bucket; clients sync everything after their last sequence.
- Offline members get a push via APNs or FCM; the message itself is fetched on reconnect.
Check yourself
Answer to mark it learned; your answers aren't scored.
Users say messages in group chats sometimes appear in a different order on different phones. Each of your 40 chat servers stamps messages with its own receive time, and clients sort by that timestamp. What's the best change?
Go deeper
Full explanation
Requirements
Functional: 1:1 and group chats (assume up to ~1,000 members), real-time send and receive, history on every device, delivered and read receipts, presence, and a push when offline. Non-functional: delivery under ~500 ms when both users are online (assumed); no lost messages; the same order for every member of a conversation; retries never duplicate.
Scale (assumed): 100M DAU × 50 messages/day ≈ 58k msg/s average; ~1 TB of messages per day; ~30M concurrent connections.
Questions I'd ask:
- Max group size? 1,000 members and 1M-member channels need different fan-out.
- End-to-end encrypted? Then the server stores ciphertext and can't search or moderate.
- How long is history kept, and on how many devices per user?
API and data model
Over a WebSocket (Real-time delivery: polling, SSE, WebSockets): send {conv_id, client_msg_id, body} → ack {client_msg_id, seq}; the server pushes msg {conv_id, seq, …}; on reconnect the client calls sync {conv_id, after_seq}. messages is partitioned by (conv_id, time_bucket) and clustered by seq, so reading history is one partition scan; members(conv_id, user_id, last_read_seq) holds receipts.
Architecture
Gateways hold WebSocket connections and nothing else of value; a session registry maps user → gateway. The chat service owns each conversation through Consistent hashing on conv_id: it dedups on client_msg_id, assigns the next seq, persists, acks, then routes to recipients' gateways. Offline members get a push from the notification service (Design: notification system); the message itself is fetched on reconnect.
The hard parts
- Order and delivery: a per-conversation sequence, at-least-once delivery, dedup on both ends.
- Group fan-out and connections: subscription-based fan-out for big channels, and reconnect storms.
Code Idempotent send with per-conversation sequence, and client gap detection
async def handle_send(user_id: str, frame: dict, db, router, notify) -> dict:
"""Runs on the single owner of frame['conv_id'] (consistent hashing),
so sequence numbers per conversation are assigned one at a time."""
conv, cmid = frame["conv_id"], frame["client_msg_id"]
if not await db.is_member(conv, user_id):
return {"type": "error", "client_msg_id": cmid, "code": "forbidden"}
# A retry of a message we already stored: same seq back, nothing new
seq = await db.seq_for_client_id(conv, cmid)
if seq is not None:
return {"type": "ack", "client_msg_id": cmid, "seq": seq}
seq = await db.next_seq(conv) # gap-free per conversation
await db.insert_message(conv, seq, user_id, cmid, frame["body"]) # persist first
# Small groups: route per member. Big channels fan out via gateway subscriptions.
for member in await db.members(conv):
if member == user_id:
continue
gateway = await router.gateway_of(member) # None when offline
if gateway:
await gateway.push(member, {"type": "msg", "conv_id": conv, "seq": seq})
else:
await notify.enqueue(member, conv, seq) # push via APNs / FCM
return {"type": "ack", "client_msg_id": cmid, "seq": seq}
def on_message(last_seq: dict, msg: dict, sync):
"""Client: drop duplicates, detect gaps, resync from the last contiguous seq."""
last = last_seq.get(msg["conv_id"], 0)
if msg["seq"] <= last:
return # duplicate delivery
if msg["seq"] > last + 1:
sync(msg["conv_id"], after_seq=last) # missed some: fetch them
return
last_seq[msg["conv_id"]] = msg["seq"]
render(msg)Real example
Discord stores messages with the primary key ((channel_id, bucket), message_id): Snowflake, time-sortable IDs, with buckets of ~10 days so partitions stay under 100 MB. In May 2022 it moved that data from 177 Cassandra nodes to 72 ScyllaDB nodes; p99 history reads fell from 40–125 ms to 15 ms, and inserts held a steady 5 ms p99. Rust data services in front, routed by channel ID with consistent hashing, query the database once when many users request the same row at the same time.
Trade-offs +3 · −3
+ You gain
- Per-conversation order needs no global coordination, so conversations shard cleanly.
- Client message IDs plus sync-from-sequence make retries, reconnects and multiple devices routine.
- Gateways hold only connections, so they can be drained and replaced without losing messages.
− You pay
- Millions of long-lived connections turn deploys and failovers into reconnect storms.
- A single owner per conversation becomes a hot spot for very large channels.
- Push providers are best-effort: APNs may reorder, so the app must resync when it opens.
Use it when
Real-time conversations where order within a thread matters and users switch devices: messaging, support chat, game lobbies, comments in collaboration tools.
Avoid it when
One-way broadcast with no replies (live scores, tickers): use pub/sub or server-sent events. At very low volume, polling an API is simpler than running gateways.
Numbers to know 5
- Traffic: 100M DAU × 50 messages/day (assumed) = 5B/day ≈ 58k msg/s average, ~120k at a 2× peak.
- Storage: 5B × ~200 B ≈ 1 TB/day, ~365 TB/year before replication.
- Connections: ~30M concurrent ÷ ~100k per gateway (both assumed) ≈ 300 gateways.
- Discord (2023): 177 Cassandra → 72 ScyllaDB nodes; p99 history reads 40–125 ms → 15 ms.
- Discord (2017): ~10-day buckets per channel keep each partition under 100 MB.
Common pitfalls 4
- Ordering by each server's receive time: clock skew reorders messages. Use a per-conversation sequence.
- Treating the WebSocket as reliable: in-flight messages vanish on disconnect. Ack, persist and resync from the last sequence.
- Broadcasting every presence change to every group member: presence traffic dwarfs messages.
- A read flag per member per message: a 1,000-member group writes 1,000 rows per message. Keep one
last_read_seqper member.
Interview questions 3
Answer out loud first, then reveal.
How do you guarantee message order in a group chat?Show answer
I only promise order within a conversation; that's what users see. Each conv_id is owned by one chat-service instance via consistent hashing, and the owner assigns a gap-free sequence before persisting. Clients render by seq, so every member sees the same order whatever the arrival order, and a gap triggers a sync. The trade-off: a hot owner for a huge channel, and on failover the new owner must read the last seq from storage before accepting writes.
A phone was offline for 3 days. What happens when it reconnects?Show answer
It opens a WebSocket, authenticates and sends its last seen seq per conversation, or one per-user inbox cursor. The server answers with the conversations that have newer messages and their unread counts; the client fetches recent messages for what's on screen and pages older history lazily. The pushes sent meanwhile were only hints: APNs is best-effort and may reorder, so the app never treats them as the message log.
How do you scale a channel with 1M members?Show answer
Per-member fan-out breaks: each message would mean 1M routing lookups and sends. I fan out to gateways instead: each gateway subscribes once to the channel for its online members, so a message costs one send per gateway with listeners, and the gateway delivers locally. Offline members get no push; they read history on open. I'd also rate-limit posting, drop per-member read receipts and make presence lazy.
Deep dive 3
Ordering and delivery guarantees
Nobody needs a global order, only a per-conversation one. Single owner: route each conv_id to one chat-service instance by consistent hashing; it assigns a gap-free seq, and gaps tell clients they missed something. Slack maps channels to its channel servers this way. Time-sortable IDs (Snowflake, as Discord uses): no owner to fail over, but only approximate order and no gap detection. Delivery is at-least-once: the client retries with the same client_msg_id, the server dedups on (conv_id, client_msg_id) and returns the original seq, and receivers drop sequences they already have. Read receipts are one last_read_seq per member, not a flag per message.
Group fan-out and presence
Small groups: look up each member's gateway and push. Big channels: each gateway subscribes once per channel on behalf of its connected members, so the chat service sends one message per gateway, not per member, and the gateway fans out locally. Slack's gateway servers hold user WebSocket subscriptions and run in several regions, close to users. Presence is the hidden cost: broadcasting every online and offline change to every group member can outweigh message traffic. Use heartbeats with TTL keys, and send presence only for contacts on screen.
Connections and reconnect storms
Assume ~30M concurrent connections; at ~100k per gateway (assumed), that is ~300 gateways. Load balancers drop idle TCP connections, so clients send WebSocket ping/pong heartbeats (RFC 6455). A gateway deploy or crash disconnects all its users at once: drain gradually, make clients reconnect with jittered backoff (Retries, backoff & circuit breakers), and keep reconnects cheap: the client sends its last seq per active conversation and fetches only what is newer. Never replay full history on reconnect.