Real-Time Multi-Server Channel Chat Service
Easy · System Design · Software Engineer · Technical Screen
Prompt
Architect the backend for a real-time chat platform organized around multi-channel community workspaces ("servers") alongside one-on-one and small-group direct conversations. Connected participants should see new posts appear almost instantaneously, while members joining a channel or returning from an offline period must be able to load complete, strictly ordered chat history.
Core Capabilities
- Workspaces, Channels, and Direct Chats: A single account can belong to many community servers, read and post inside permitted text channels within each server, and exchange direct messages.
- Live Delivery: Messages posted to a channel are pushed in real time to online members currently subscribed to that conversation.
- History & Catch-Up Sync: Opening a channel or reconnecting after a dropped connection lets the client fetch prior pages of messages as well as everything missed while offline.
- Total Per-Channel Sequence: Every channel defines one unambiguous, gap-free message order shared by live viewers and historical readers alike.
Operational & Scale Constraints
- Concurrency & Reach: Support millions of simultaneously connected clients distributed worldwide, including mobile devices on high-loss or intermittent cellular connections.
- Latency & Uptime: Deliver live chat events with low sub-second latency while keeping the messaging plane highly available.
- Durability First: Once the backend confirms a sent message to its author, that record must survive server crashes and zone failures without disappearing.
Sample Interaction Trace
Mayaposts"Deploy finished"to the#releaseschannel (ch_releases).- The backend authenticates
Maya's token, verifies her permission to post in#releases, and commits the sequenced message to durable storage before acknowledging the send. - All connected members watching
#releasesreceive the new message over their live push connections. - Teammate
Liam, whose phone was offline in a subway tunnel when"Deploy finished"was sent, regains connectivity minutes later and runs a cursor-based sync to fetch every#releasesmessage committed after his last seen sequence position.
Scope & Expectations
- Client-Server Protocols: Define the HTTP and persistent push interfaces for posting messages, paginating history, maintaining sessions, and catching up after disconnects.
- Schema & Partitioning Strategy: Propose storage models for workspace/channel membership metadata and high-volume append-only channel messages.
- End-to-End Routing & Fan-Out: Show how a sent message moves from permission validation and durable persistence to live subscriber delivery without overwhelming large community servers.
- Distributed Sequencing & Reconnect Guarantees: Explain how strict per-channel ordering, duplicate suppression on flaky networks, and efficient offline catch-up work together at scale.
Step-by-step walkthrough
Clarify requirements and core guarantees
Building a basic chat room on one machine is straightforward. Building a multi-server community chat platform for millions of concurrent users is challenging because four core promises pull directly against one another:
- Real-time low latency: online members see a new message within a fraction of a second.
- Strict per-channel ordering: every live viewer and every historical scroll-back sees the exact same message sequence in a channel, with no silent gaps.
- Durability first: once the sender receives a "message sent" confirmation, that message must never vanish—even if a server or an entire availability zone crashes a millisecond later.
- Resilient offline sync: mobile and global users on unstable networks drop connections constantly and must catch up cleanly without duplicate or missing messages.
Functional requirements
- Servers, channels, and DMs: users can join multiple servers (communities), access permitted text channels inside them, and send 1:1 or small-group direct messages (modeled as server-less channels).
- Real-time messaging: users send messages and active subscribers of that channel receive them live.
- Message history and synchronization: clients fetch older pages when scrolling up and fetch missed messages (
aftertheir last known position) upon joining or reconnecting. - Strict per-channel ordering: every channel defines one authoritative, total message order. (Ordering across two unrelated channels is neither needed nor meaningful.)
Non-functional requirements and assumptions
- Scale:
200Mregistered users,50Mdaily active users (DAU), and10Mconcurrent online sessions across servers ranging from5friends to500,000community members (50,000online at once). - Latency:
< 300 msp99 end-to-end delivery within the same continent;< 500 msacross continents. - Availability and durability:
99.99%uptime; acknowledged messages are replicated across3availability zones before returning HTTP201. - Payload scope: text up to
2,000characters (~300 Bwith metadata); images and files upload directly to object storage (S3/GCS) via pre-signed URLs, leaving only attachment keys inside the message record. Edits and deletes modify a message in place without changing its order position. Voice/video and full-text search are out of scope, though search can subscribe to our message event stream.
Back-of-the-envelope numbers
Let us size writes, live fan-out, persistent connections, and storage step by step:
1. Traffic & message write rate Daily active users (DAU) = 50,000,000 Messages sent per DAU / day = 40 -> 2,000,000,000 (2B) messages/day Average write throughput = 2,000,000,000 / 86,400 s = ~23,150 messages/s Peak write throughput (3x) = ~70,000 messages/s 2. Durable storage growth Average stored row size = ~300 B (text + message_id + seq + author_id + nonce + flags) Daily raw volume = 2B * 300 B = 600 GB/day Replicated across 3 zones = 600 GB * 3 = 1.8 TB/day -> ~660 TB/year (~280 TB compressed) 3. Real-time fan-out (push) rate Average online viewers/message = 30 (most channels are small; big community channels skew high) Outbound client pushes at peak = 70,000 messages/s * 30 = 2,100,000 (2.1M) pushes/s 4. Persistent WebSocket gateway fleet Peak concurrent connections = 10,000,000 (10M) open sockets Capacity per gateway server = 100,000 sockets (~20 KB RAM/socket for TLS + buffers = ~2 GB) Minimum gateways needed = 10M / 100k = 100 -> run 150 across 3 zones (survives 1 zone loss) Deliveries per gateway at peak = 2.1M pushes/s / 150 gateways = 14,000 pushes/s 2-minute session resume buffer = 14,000/s * 120 s * ~500 B = ~840 MB RAM per gateway 5. History reads & reconnect sync Channel opens / scroll-backs = 10M users * 1 fetch / 5 min = ~33,000 range reads/s (50 rows each) Reconnect channel-head summary = 15 servers * 30 channels * 16 B (channel_id + last_seq) = ~7.2 KBWhat the arithmetic tells us:
- Writes (
70k/s) are moderate, whereas live pushes (2.1M/s) and open sockets (10M) dominate compute. Inside our backend, we must route each message once per interested gateway (at most 150 copies), never once per individual user (up to 50,000 copies). - Writing to offline users' inboxes is impossible at large-community scale: one message in a
500,000-member server would trigger500,000inbox writes! Active sessions must get pushed events, while disconnected users pull history only for the channels they actually open.
- Writes (
API design: REST for writes/history and WebSockets for live push
A WebSocket is a long-lived, two-way TCP connection between client and server that stays open so the server can push new events instantly without waiting for the client to poll. We use HTTPS REST for stateless request/response actions (sending messages, loading history) and one WebSocket per client session for receiving live events:
HTTPS REST API (Authorization: Bearer <session_token>) 1. Send a message (idempotent via client-generated `nonce`) POST /v1/channels/{channel_id}/messages Body: {"content": "Deploy finished", "nonce": "client-uuid-7c41b9"} 201 Created -> { "channel_id": "ch_releases", "seq": 48213, "message_id": "117604928174000128", "created_at": "2026-11-30T17:20:01.104Z" } (403 no permission | 429 rate-limited with Retry-After | 503 shard moving, retry with same nonce) 2. Fetch channel history (catch-up forward or scroll-back backward) GET /v1/channels/{channel_id}/messages?after_seq=48100&limit=100 -> ascending (48101..48200) GET /v1/channels/{channel_id}/messages?before_seq=48213&limit=50 -> descending (48212..48163) 3. Server/DM management & read state GET /v1/users/@me/servers -> joined servers & channels POST /v1/users/@me/channels {"recipient_ids": ["u_42"]} -> create/open DM channel PUT /v1/channels/{channel_id}/read-state {"last_read_seq": 48213} -> update unread markerWebSocket Gateway Protocol (wss://gateway.chat.example/v1, zstd-compressed JSON/msgpack frames) Server -> Client HELLO {"heartbeat_interval_ms": 40000} Client -> Server IDENTIFY {"token": "..."} (fresh login/boot) Client -> Server RESUME {"token": "...", "session_id": "s_9", "last_event_no": 318} Server -> Client READY {"session_id": "s_9", "resume_url": "...", "channels": [{"channel_id": "ch_releases", "last_seq": 48213}], "read_states": [{"channel_id": "ch_releases", "last_read_seq": 48210}]} Client -> Server FOCUS {"channel_ids": ["ch_releases"]} (currently visible UI tab) Client -> Server HEARTBEAT {"last_event_no": 319} <--> Server -> Client HEARTBEAT_ACK Server -> Client EVENT {"event_no": 320, "type": "MESSAGE_CREATE", "data": {"channel_id": "ch_releases", "seq": 48213, "message_id": "117604928174000128", "author_id": "u_maya", "content": "Deploy finished", "nonce": "client-uuid-7c41b9"}} Server -> Client EVENT {"event_no": 321, "type": "CHANNEL_HEAD", "data": {"channel_id": "ch_99", "last_seq": 9104}}Three small API choices prevent whole classes of bugs:
nonce(idempotency key): a random ID generated by the client before sending. On a spotty cellular link, the HTTP response may drop after the server saved the message. RetryingPOSTwith the samenoncereturns the already-stored message (seq: 48213) instead of posting a duplicate!- Why sends use REST instead of the WebSocket: HTTP
POSTgives clear request timeouts, standard load-balancing, and independent scaling, leaving WebSocket gateways purely stateless push pipes that never touch the database. - Two distinct sequence numbers:
seq(1, 2, 3, ...) is per-channel and gap-free so clients can spot any missing message (48211 -> 48213means48212is missing!).event_no(318, 319, 320, ...) counts frames delivered on one specific WebSocket session soRESUMEcan replay missed frames after a brief Wi-Fi blip.
Data model: relational metadata and bucketed wide-column messages
1. Community and permission metadata (PostgreSQL, sharded by
server_id/user_id)Servers, channels, memberships, and role permissions change infrequently, fit easily in memory caches, and benefit from relational integrity:
users user_id PK (64-bit Snowflake), username, avatar_key, created_at servers server_id PK, name, owner_id, home_region, member_count channels channel_id PK, server_id (NULL for DMs), type (TEXT|DM|GROUP_DM), name members PK (server_id, user_id), role_ids[], joined_at user_servers PK (user_id, server_id) -- lookup table: "all servers I joined" roles PK (server_id, role_id), permissions_bitmask (64-bit integer) channel_overwrites PK (channel_id, target_id), allow_mask, deny_mask dm_members PK (channel_id, user_id) -- plus reverse table PK (user_id, channel_id)2. Durable message history (ScyllaDB or Apache Cassandra, Replication Factor = 3)
Messages are append-heavy (
2B/day) and almost always queried as "give me 50 consecutive messages inchannel_idbefore or afterseq". A wide-column store partitioned by(channel_id, bucket)and sorted byseqserves every history page from a single contiguous disk slice:messages PRIMARY KEY ((channel_id, bucket), seq) WITH CLUSTERING ORDER BY (seq DESC) channel_id 64-bit Snowflake ID bucket (seq - 1) // 50_000 -- caps each partition at 50,000 messages (~15 MB) seq 64-bit per-channel monotonic sequence (1, 2, 3, ...) head_seq STATIC bigint -- highest `seq` committed in this partition (for fencing) message_id 64-bit Snowflake ID -- global identity & cross-channel rough time sort author_id bigint content text nonce text attachment_keys list<text> edited_at timestamp, deleted boolean channel_latest_bucket PK (channel_id) -> latest_bucket -- updated only once every 50,000 messages read_states PK (user_id, channel_id) -> last_read_seq, mention_countWhy bucket by
(seq - 1) // 50_000instead of a 10-day time window? If you bucket by 10-day calendar windows, a quiet channel whose previous message was 8 months ago forces the server to probe24empty 10-day partitions backward just to fill one screen of history! Conversely, a viral channel can cram millions of messages into a single 10-day partition and create an oversized hot partition. Bucketing by(seq - 1) // 50_000means every partition holds at most~15 MBregardless of traffic speed, and jumping toafter_seq=48100computesbucket = 48099 // 50000 = 0inO(1)arithmetic with zero empty probes.Why keep BOTH
message_id(Snowflake) andseq? A Snowflake ID packs a timestamp, machine ID, and local counter into 64 bits:+-------------------------------------------+-----------------+------------------+ | 41 bits: milliseconds since custom epoch | 10 bits: worker | 12 bits: counter | +-------------------------------------------+-----------------+------------------+ (~69 years of timestamps) (1,024 nodes) (4,096 IDs / ms)message_idgives every message a globally unique permalink and sorts roughly by time across different channels (essential for a global@mentionsinbox or future search index), whileseqprovides strict, gap-free1, 2, 3, ...ordering inside one channel.High-level architecture and end-to-end workflow
[ Maya (Online) ] [ Liam (Offline -> Reconnects) ] | ^ | | 1. HTTPS POST /channels/ch_releases/messages | 4. WSS push | 5. WSS READY + v | (live) | GET ?after_seq [ Stateless API Tier ] [ WebSocket Gateways (150 nodes) ] - validate session token & cached role permissions ^ | - route by hash(channel_id) | +--> [ Redis Session Dir ] | | (user_id -> gateways) v | batched gRPC streams [ Stateful Channel Owners (4,096 shards via etcd leases) ] | - single writer per channel: assign `seq` + monotonic Snowflake | - keep last 200 msgs & 10m nonces in RAM | | [ Fan-out Workers ] | 2. Conditional quorum write (RF=3, LOCAL_QUORUM) - consume by server_id +------------------------------> [ ScyllaDB / - map server_id -> subscribed gateways | (reply HTTP 201 to Maya Cassandra ] ^ | ONLY after durable write!) ^ | | | [ Kafka ("channel-events") ] +--- 3. Publish persisted event -------|---------------> partitioned by server_id (decouples DB from push) | | | +--> [ Mobile Push Workers ] (History reads miss tail cache) -------+ (APNs / FCM for offline @mentions)Let us trace our
#releasesinteraction end to end through this architecture:- Maya posts
"Deploy finished"to#releases: Maya's client callsPOST /v1/channels/ch_releases/messagescarryingnonce="client-uuid-7c41b9". - Session authentication, role check, and durable quorum commit: an API worker validates Maya's bearer token, checks cached workspace/channel permission bitmasks for
SEND_MESSAGES, and routes the call toch_releases's channel owner. That owner assignsseq = 48213and a monotonic Snowflakemessage_id, commits the row across2 of 3availability zones (LOCAL_QUORUM) in ScyllaDB, and returns HTTP201only after durable persistence completes. - Decoupled live fan-out: the channel owner appends the committed record to Kafka (
channel-events, partitioned byserver_id). A fan-out worker resolves which WebSocket gateways hold active subscribers for that server, sends one copy per gateway, and each gateway pushesMESSAGE_CREATEto permitted sockets watching#releases. Placing Kafka between storage and push ensures slow sockets or restarting workers never stall database commits. - Offline Liam catches up on reconnect: when Liam exits the subway tunnel and reconnects, his
READYpayload lists"ch_releases": {"last_seq": 48213}. Comparing48213against his locally stored cursor48200, Liam's client requestsGET /v1/channels/ch_releases/messages?after_seq=48200and receives messages48201..48213in exact order.
- Maya posts
Deep dive 1: strict message ordering in a distributed environment
Why server timestamps—and even uncoordinated Snowflake IDs—fall short on their own
Relying on wall-clock timestamps fails immediately because two servers' clocks drift by several milliseconds (even with NTP synchronization), two messages in the same millisecond tie, and NTP adjustments can step a clock backward.
Switching to Snowflake IDs gives globally unique, roughly time-ordered 64-bit IDs without coordination. However, if multiple stateless API servers independently stamp Snowflake IDs and write directly to the database for the same channel, two subtle ordering bugs still occur:
Bug 1 (Clock skew): API Node 1 (clock +8 ms fast) stamps id = 1008 for Maya's post at real t = 1000 ms API Node 2 (clock accurate) stamps id = 1003 for Noah's reply at real t = 1003 ms Result: Noah's reply sorts BEFORE Maya's post! Bug 2 (Out-of-order visibility + silent cursor skip): API Node 1 stamps id = 500, starts slow DB write... API Node 2 stamps id = 505, fast DB write finishes first! Liam reconnects, asks "messages after 490" -> receives [505], advances local cursor to 505. 10 ms later, id = 500 finishes writing -> Liam NEVER queries <= 505 again; message 500 is silently lost!The solution: single channel owner + gap-free
seq+ fenced group commitWe hash all channels into
4,096shards, where each shard is owned by one stateful channel owner node holding a short lease (10 sTTL, renewed every3 s) in etcd (a strongly consistent coordination service). Because every write toch_releasespasses through that single owner: - It assigns a strictly gap-freeseq = 1, 2, 3, ...and clamps its Snowflake generator (message_id = max(next_snowflake(), last_message_id + 1)) so bothseqandmessage_idstrictly increase! - Group commit batches concurrent arrivals while the previous database round-trip is in flight: if 80 people post during one8 msScyllaDB write, all 80 messages commit in the next single-partition batch (80 / 0.008 s = 10,000 messages/sin a single channel!). - Storage-side zombie fencing: what if an old owner freezes in a garbage-collection pause for12 seconds, loses its etcd lease, and wakes up thinking it still ownsch_releases? To prevent two owners (split-brain) from overwriting the sameseq, every batch performs an atomic conditional write (compare-and-swap on the partition'sSTATIC head_seqcolumn):from collections import deque def process_channel_writes(channel, store, kafka_bus, snowflake_gen): """Single-owner write loop for one channel with nonce dedupe and group commit.""" while channel.is_lease_valid(): # Block for at least 1 send request, then drain up to 50 queued requests batch_requests = channel.inbox.take_batch(max_items=50) rows_to_insert = [] client_replies = [] for req in batch_requests: dedupe_key = (req.author_id, req.nonce) existing_row = channel.recent_nonces.get(dedupe_key) if existing_row is not None: # Client retried a send we already sequenced: reuse the original row client_replies.append((req, existing_row)) continue # Assign gap-free `seq` and strictly monotonic Snowflake `message_id` msg_id = max(snowflake_gen.next_id(), channel.last_message_id + 1) channel.last_message_id = msg_id row = channel.build_row(seq=channel.next_seq, message_id=msg_id, req=req) channel.next_seq += 1 channel.remember_nonce(dedupe_key, row) rows_to_insert.append(row) client_replies.append((req, row)) if rows_to_insert: expected_prev_seq = rows_to_insert[0].seq - 1 # Conditional batch: succeeds ONLY if `head_seq == expected_prev_seq` committed = store.write_batch_if_head_matches( channel_id=channel.id, rows=rows_to_insert, expected_head=expected_prev_seq, ) if not committed: # Another owner took over our shard! Abort and return 503 so clients retry channel.abort_and_return_503(batch_requests) return # Cache latest 200 rows in memory (bounded deque) & publish to Kafka channel.tail_cache.extend(rows_to_insert) kafka_bus.publish(partition_key=channel.server_id, events=rows_to_insert) for req, row in client_replies: req.reply_201(row)On the client side, gap-free
seqmakes rendering resilient even if network events arrive out of order or drop:def on_live_message(view_state, channel_id: str, msg) -> None: """Render strictly in `seq` order and fetch missing gaps automatically.""" last_seen = view_state.last_seq.get(channel_id, 0) if msg.seq <= last_seen: # Duplicate delivery (from session resume or worker replay): ignore return if msg.seq == last_seen + 1: # Exact next message in sequence: display immediately! view_state.render(msg) view_state.last_seq[channel_id] = msg.seq # Drain any future messages (`last_seen + 2`, ...) already waiting in buffer view_state.flush_contiguous_buffered(channel_id) return # Gap detected (e.g. jumped from 41 to 43): stash 43 and pull missing range > 41 view_state.buffer_out_of_order(channel_id, msg) view_state.schedule_gap_fetch(channel_id, after_seq=last_seen)Deep dive 2: real-time fan-out to millions of online users
Two-hop fan-out (copy per gateway, not per user)
If
50,000online members belong to a gaming server spread across150gateways, a new message should travel over the internal network 150 times (once to each gateway), not50,000times:[ Kafka partition (server_id = S) ] | v [ Fan-out Worker ] in-memory routing map: server S -> {gateway_1, gateway_2, ..., gateway_150} flushes batched events every 5 ms over 1 persistent gRPC stream per gateway | +---> [ Gateway 1 ] -> checks local permission map -> pushes to 340 local WebSockets +---> [ Gateway 2 ] -> checks local permission map -> pushes to 325 local WebSocketsRace-free subscription handshakes
When User U connects to
Gateway 1and needs events forServer Sfor the first time on that gateway, how do we avoid missing a message sent during the subscription setup?Gateway 1writes a tinySUBSCRIBE(server_id=S, gateway_id=1)control record into the exact same Kafka partition that carriesServer S's messages! The fan-out worker reads the partition sequentially: it recordsGateway 1at offsetK, immediately replies withServer S's currentlast_seqchannel heads as of offsetK, and streams every message after offsetKlive. Zero messages can fall between the snapshot and the live stream.Taming 500,000-member servers with
FOCUSsubscriptionsEven among online users,
49,000out of50,000online members of a huge server are looking at a different server or channel tab right now. Pushing every rawMESSAGE_CREATEto all50,000sockets wastes bandwidth and client CPU:- Small servers (
< 1,000members): push fullMESSAGE_CREATEevents for all permitted channels. - Large servers (
>= 1,000members): push fullMESSAGE_CREATEevents only to sessions that sentFOCUSfor that active channel (plus any@mentionor DM). All other online members receive a tiny coalescedCHANNEL_HEAD {"channel_id": "ch_99", "last_seq": 9104}at most once every2 secondsso their sidebar unread dot lights up cleanly! - Slow-client protection: every WebSocket session has a strict outbound memory cap (
2,000queued frames or1 MB). If a user enters an elevator and stops acknowledging TCP packets, the gateway closes that single socket rather than letting buffered frames exhaust server RAM, and the client cleanly resyncs when signal returns.
- Small servers (
Deep dive 3: offline synchronization and flaky networks
Combining live push for connected sessions with on-demand pull for disconnected clients handles every disconnect duration cleanly:
Disconnect duration Synchronization path on reconnect --------------------------- ------------------------------------------------------------------ Brief drop (< 2 minutes) Client sends `RESUME {session_id, last_event_no}` to `resume_url`. Gateway replays missed frames straight from its 2-minute RAM ring buffer -> zero database queries! Long offline (>= 2 minutes) Client sends `IDENTIFY`. Gateway returns `READY` containing or gateway node restarted `{channel_id, last_seq}` for the user's servers + `read_states`. 1. Client compares `last_seq > last_read_seq` locally to light up unread badges across all 450 channels instantly (zero DB reads!). 2. ONLY when the user clicks into a channel does the client call `GET /messages?after_seq=<cached_seq>` (1 single-partition read). App backgrounded on mobile WebSocket closes to save battery; Kafka `Mobile Push Workers` check Redis `user_sessions:{user_id}` -> if empty, send APNs/FCM push notifications ONLY for DMs and `@mentions`.Surviving reconnect storms ("thundering herds"): if a gateway node crashes,
100,000clients lose their socket simultaneously. If all100,000reconnected within50 ms, they would overwhelm TLS handshakes andIDENTIFYprocessing. Clients add random jitter (0–5 secondsuniform delay before the first reconnect, followed by exponential backoff with jitter), gateways rate-limitIDENTIFYhandshakes to2,000/sper node, andREADYchannel heads are served purely from gateway/fan-out worker memory caches rather than hitting ScyllaDB.Scaling, bottlenecks, and multi-region topology
- WebSocket gateways: horizontally scalable and durable-state-free; placed at edge regions worldwide behind GeoDNS/Anycast so TLS termination and mobile round-trip times stay local (
< 30 ms). - Channel owners:
4,096shards spread across ~64nodes (~64shards/node). Hot-channel reads hit the owner's200-messagein-memorytail_cache, shielding ScyllaDB when50,000members click an@everyoneannouncement at the exact same second! Hot-channel writes combine via group commit (~10,000 msgs/s), while user-level rate limits and optional channel "slow mode" (e.g., 1 message per user every 5 seconds) keep human chat readable. - ScyllaDB / Cassandra cluster: sized both for
~70,000conditional Paxos batches/second (LOCAL_SERIAL/LOCAL_QUORUM) and~280 TB/yearof LZ4-compressed storage (~90–120NVMe nodes in year 1, scaling linearly by adding nodes). - Multi-region layout: each server has a
home_region(chosen near its creator/community, e.g.,us-eastoreu-central) where its channel owner shard, primary ScyllaDB quorum (3 AZs), and primary Kafka partition live, with asynchronous cross-region replication to a backup region. A user in Tokyo posting to aus-eastserver pays one cross-Pacific hop (~150 ms) so the single owner can sequence the message cleanly, and regional Kafka mirroring streams the committed event out to gateways worldwide within< 300–450 ms.
- WebSocket gateways: horizontally scalable and durable-state-free; placed at edge regions worldwide behind GeoDNS/Anycast so TLS termination and mobile round-trip times stay local (
Failure handling and trade-off summary
Failure mode User-visible effect Automated recovery Gateway server crashes 100ksockets dropClients reconnect with 0–5 sjitter to surviving gateways and catch up viaIDENTIFY+ lazyafter_seqpulls.Stateless API node crashes In-flight POSTtimes outClient retries POSTwith the exact samenonce; channel owner returns the original stored row without duplicating it.Channel owner crashes Writes to 1/64of channels return503for<= 10 setcd lease expires; new owner reads head_seqand recent rows/nonces atLOCAL_SERIAL, resumes sequencing, and emitsCHANNEL_HEADin case the old owner crashed between DB commit and Kafka publish.Old owner freezes then wakes (zombie) Brief dual-owner race Storage-side conditional batch ( IF head_seq = expected) rejects the zombie's write; zombie sees lease lost and returns503.One ScyllaDB node or whole AZ fails Zero downtime LOCAL_QUORUM(2 of 3AZ replicas) continues reading and writing without interruption.Fan-out worker crashes Few seconds of push delay on its partitions Replacement consumer loads periodic subscription/head snapshot from Kafka compact topic, replays from last offset; clients ignore duplicate pushes via msg.seq <= last_seen.Core architectural trade-offs
- Persist at quorum before returning
201, then push via Kafka: guarantees an acknowledged message is never lost or shown live without existing in history, adding ~5–10 msto send latency. - Single channel owner + gap-free
seq+ monotonic Snowflakemessage_id: provides strict ordering, hole detection, and global IDs, at the cost of one cross-region hop for distant senders and a<= 10 sshard failover pause if an owner crashes. - Conditional Paxos batch writes vs. lease-only fencing: pays extra local round-trips per batch in ScyllaDB (amortized via group commit) to make zombie-owner overwrites mathematically impossible.
- Push to active/focused sockets, pull on demand for offline users: avoids
500,000wasted inbox writes per message in large communities while keeping active chats instantaneous.
- Persist at quorum before returning
Intuition & how it works
Picture a busy community hall with a permanent glass bulletin board for each room and radio announcers broadcasting live to members wearing headsets. Whenever someone posts a note in the #releases room, a single clerk at #releases's desk stamps it with the next sequential ticket number (#41, #42, #43), pins it behind the glass first, and only then gives the sender a thumbs-up. Next, the radio announcer reads #42 aloud once to everyone currently tuned in; anyone whose radio cut out in a tunnel simply looks at the board later, sees ticket #43 is the newest, and reads whatever tickets came after #40—the last number they remember.
Naive chat designs break down quickly at millions of users. Having 10 million clients poll an HTTP endpoint every second generates 10 million mostly empty database queries per second, while relying on wall-clock timestamps from many API servers scrambles message order whenever server clocks drift by a few milliseconds. Just as fatal, copying every new message into per-user "unread inboxes" (fan-out on write) turns a single message in a 500,000-member community server into 500,000 database writes—mostly for offline users who may never even open that channel.
Walk through five concrete events in #releases (channel_id = ch_releases) to see how the design keeps messages fast, durable, and strictly ordered:
- Maya posts
"Deploy finished": Maya sendsPOST /v1/channels/ch_releases/messageswith a random idempotency key (nonce = "client-uuid-7c41b9"—a client-generated token so retrying a timed-out request never creates a duplicate message). - Single-owner sequencing & durable quorum write: The stateless API checks permissions and routes
ch_releasesto its single stateful channel owner, which assigns both a globally unique Snowflake ID (a 64-bit integer packing timestamp, worker ID, and counter) and the next gap-free channel sequence numberseq = 42. It writesseq = 42to ScyllaDB/Cassandra at quorum (2 of 3availability-zone replicas) using a conditional write (IF head_seq = 41, an atomic compare-and-swap that blocks stale "zombie" owners), then replies HTTP201. - Decoupled Kafka publish: The channel owner appends
seq = 42to Kafka (an append-only distributed message log), separating database durability from live push delivery. - Two-hop WebSocket push: A fan-out worker sends one copy of
seq = 42to each WebSocket gateway (a server holding ~100,000persistent two-way client connections) that has subscribed members, and each gateway pushesseq = 42to online viewers in< 300 ms. - Offline Liam reconnects and pulls: Liam lost signal in a subway tunnel at
seq = 40. On reconnect, hisREADYsummary reportsch_releases's latest head is42, so when Liam opens#releases, his client pullsGET /messages?after_seq=40and receives41and42in exact order from a single database partition.
Key trade-offs
- Persist to quorum before replying vs. push before persisting. Waiting for
2 of 3database replicas before returning201and publishing to Kafka adds ~5–10 msto send latency, but guarantees durability first: a user never sees a message appear live and then vanish from history after a server crash. - Single channel owner + gap-free
seqvs. uncoordinated Snowflake IDs from any API node. Letting any stateless server stamp a Snowflake ID avoids shard leases, but clock skew between servers can invert conversation order and natural gaps between Snowflake timestamps prevent clients from knowing whether a WebSocket packet was dropped. Routing each channel through one owner (with group commit—batching concurrent arrivals into a single database round-trip) gives gap-free1, 2, 3, ...ordering and~10,000 messages/sper channel, at the cost of a<= 10 sshard failover pause on crash and one cross-region hop for distant senders. - Storage-side conditional writes (
IF head_seq = ...) vs. lease-only fencing. Relying solely on a timed lease fails when an old owner freezes in a long garbage-collection pause, loses its lease, and wakes up to write stale sequence numbers (split-brain). Conditional Paxos writes cost extra local round-trips per batch in ScyllaDB/Cassandra, but guarantee two owners can never overwrite the sameseq. - Bucketing partitions by
(seq - 1) // 50_000vs. calendar time buckets. Fixed50,000-message sequence buckets keep every database partition near a predictable~15 MBand let anyafter_seqcursor compute its exact bucket inO(1)math, whereas 10-day time buckets force quiet channels to scan dozens of empty buckets and let viral channels blow up partition sizes. - Push to active/focused online users, pull on read for offline users. Pushing live events over WebSockets (and coalescing background tabs in huge servers down to lightweight
CHANNEL_HEADbadge updates) keeps active chats instant while avoiding millions of wasted per-user inbox writes for offline members. - In-memory gateway resume buffers vs. replicated session logs. Keeping
2 minutesof recent frames (~840 MB) in each gateway's RAM lets brief Wi-Fi dropsRESUMEwith zero database load, accepting that a full gateway crash forces its100,000clients to do a jitteredIDENTIFY+READYresync rather than paying to replicate every session buffer across machines.
Common mistakes
- Sorting messages by client clocks or uncoordinated server timestamps: clocks drift across machines and jump backward during NTP syncs, causing replies to appear above the message they answered.
- Using Snowflake IDs across multiple writers without gap detection: if Writer A stamps ID
100(slow DB write) and Writer B stamps ID105(fast DB write), a reconnecting client queryingafter_id=95receives105, advances its cursor to105, and permanently misses100when it lands milliseconds later. - Sending messages without a client
nonce(idempotency key): mobile connections frequently drop HTTP responses after the server already stored the message, causing retries to post embarrassing duplicates. - Fan-out on write to every member of a 500k-member server: writing per-user inbox rows or pushing full message payloads to
49,000online users who are not even viewing that channel melts both storage and gateway bandwidth. - Unbounded outbound WebSocket queues: if one user on flaky train Wi-Fi stalls TCP acknowledgments and the gateway buffers forever, slow clients exhaust gateway memory; always cap per-session buffers and disconnect lagging sockets so they resync cleanly.
- Writing heartbeats to a database: persisting
10Mconnection heartbeats every40 secondscreates250,000pointless database writes/second instead of keeping liveness in gateway memory. - Ignoring the reconnect thundering herd: when one gateway crashes,
100,000clients reconnecting at millisecond zero will cascade-crash surviving gateways unless clients wait a random jitter window (0–5 s) andREADYsummaries read from memory caches.
Follow-up questions
- What breaks first when tens of thousands of members pile into one viral channel and post concurrently, and how do you keep writes and fan-out healthy? On the write path, a single channel owner serializes sequence numbers in RAM (nanoseconds) and uses group commit to pack up to
50–100concurrent sends into one conditional ScyllaDB batch every~8 ms, sustaining6,000–10,000 messages/s—far higher than human typing speed (2,000active senders posting once every5 secondsis400 messages/s)—while per-user rate limits and optional channel "slow mode" block bot floods. On the read and fan-out path, where400 messages/s × 25,000 viewers = 10M pushes/sis the real bottleneck, gateways coalesce outboundMESSAGE_CREATEevents for that hot channel into one batched WebSocket frame every100 msper viewer (10 frames/sinstead of400/s), non-focused server members receive only a2-secondcoalescedCHANNEL_HEADbadge update, andGET /messageshistory loads hit the channel owner's200-messagein-memory tail cache instead of hammering ScyllaDB replicas. - How would you add unread/read tracking and live online-status indicators without overwhelming storage or gateway bandwidth? Store read state as one compact cursor
(user_id, channel_id) -> last_read_seq, never one receipt row per message; clients debounce updates to once every few seconds (last_read_seq = max(old, new)), and live"Seen by X"indicators broadcast only in DMs and small group chats (<= 10members), while large servers only uselast_read_seqlocally to light up the user's own unread badges. For presence, run an in-memory presence service sharded byuser_idthat writes only on state transitions (online,idle,offline), never on routine heartbeats—each gateway sends a single lease heartbeat covering all100,000of its sessions so a dead gateway marks sessions offline in bulk. Finally, scope presence fan-out strictly to friends and the~50–100member rows currently scrolled into view on a user's sidebar (lazy member-list subscriptions), coalescing status changes into5-secondbatches. - Suppose product asks for end-to-end encrypted channels—what changes for multi-device history recovery, full-text search, and push notifications? With end-to-end encryption (E2EE)—where plaintext is encrypted on the sender's device so the server stores and routes only opaque ciphertext—routing envelopes (
channel_id,seq,message_id,author_id) stay unencrypted, so our sequencing, ScyllaDB bucketing, andafter_seqsynchronization continue working unchanged. However, message history becomes a cryptographic key-management problem: a newly logged-in phone or laptop can decrypt older messages only if past encryption keys are backed up in an encrypted key vault (unlocked via a user recovery passphrase/PIN) or synced device-to-device, and rotating group keys (via Sender Keys or the Messaging Layer Security / MLS protocol) whenever members join or leave is practical for DMs and small groups (<= 100–1,000users) rather than500,000-member public servers. Because the server never sees plaintext, server-side full-text search, link-preview scraping, and content-based spam filtering become impossible: search must run against a local encrypted SQLite/FTS index built on each client device over the history it has decrypted, and push notifications must either show generic"New message"text or wake a local mobile notification-service extension to decrypt the payload on the phone.
Follow-up questions
- What breaks first when tens of thousands of members pile into one viral channel and post concurrently, and how do you keep writes and fan-out healthy?
- How would you add unread/read tracking and live online-status indicators without overwhelming storage or gateway bandwidth?
- Suppose product asks for end-to-end encrypted channels—what changes for multi-device history recovery, full-text search, and push notifications?
Similar questions
- Count Valid Highway Trips
- Hardware Device Registry: Validation, Active Tallies, and Bulk Transitions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests