Design a Real-Time Workspace Chat Service
Easy · System Design · Software Engineer · Onsite
Prompt
Architect the backend for a real-time enterprise messaging service where organization members collaborate across persistent open channels, invite-only private channels, and direct two-person conversations.
Your architecture must satisfy the following product, reliability, and scale targets:
- Core capabilities:
- Real-time messaging: Exchange text messages instantly across open channels, invite-only private channels, and direct 1-to-1 chats.
- Conversation history: Load paginated message history smoothly when opening a channel or scrolling backward through older threads.
- Chronological ordering & idempotency: Present every conversation's messages in deterministic time/sequence order and prevent duplicate entries across client retries or network hiccups.
- Presence & unread state: Surface live user status (
online,away,offline) alongside unread channel indicators and read cursors.
- Reliability & latency targets:
- Sub-200 ms delivery: Deliver new messages to connected recipients in under
200 msend-to-end. - 99.99% availability: Keep message ingestion and delivery running through transient hardware or network faults without losing messages.
- Strict durability: Never lose a message once its send request has been acknowledged to the caller.
- Sub-200 ms delivery: Deliver new messages to connected recipients in under
- Operating scale:
10 milliondaily active users (DAU).50,000messages sent per second at peak.50joined channels per user on average, with broadcast public channels scaling up to100,000members.- At least
5 yearsof durable message retention.
Scope & Expectations
- Client-server protocols & APIs: Define endpoints and persistent connection frames (such as HTTP and WebSockets) for sending messages, paginating history, syncing state, and streaming live events.
- Storage engines & sharding: Justify SQL vs. NoSQL choices, write out core schemas, and choose partition keys for messages, memberships, and 5-year archival storage.
- Connection routing & fan-out: Explain how live messages fan out efficiently across both 2-person direct chats and 100,000-member channels within the
200 mslatency budget. - Sequencing & deduplication: Detail how per-conversation sequence numbers, idempotent sends, and client-side gap recovery guarantee ordered, duplicate-free views.
Step-by-step walkthrough
Clarify requirements, guarantees, and scale
What makes a workspace chat platform architecturally interesting is the tension between strict bank-grade durability and ordering on the write side (every acknowledged message must survive crashes and appear in one agreed sequence) and massive sub-200 ms fan-out on the delivery side (a single message in an all-hands channel may need to notify up to 100,000 members).
Functional requirements (in scope)
- Real-time messaging: Send and receive text messages across open workspace channels, invite-only private channels, and direct 1-to-1 chats (small group DMs behave identically to private channels).
- Paginated history: Fetch older pages smoothly when opening a channel or scrolling upward, and catch up on missed messages after offline periods.
- Strict per-conversation ordering and idempotency: Every device displays messages in the exact same chronological sequence within a channel, and retrying a timed-out send never creates duplicate messages (idempotency — repeating the same request produces the exact same stored state as sending it once).
- Presence and unread indicators: Show
online,away, orofflinestatus, plus per-channel unread highlights and@mentionbadge counts.
(Explicitly out of scope for core v1: full-text search indexing, emoji reactions, rich threads beyond a
thread_root_seqfield, and file attachments — which we address in the follow-ups.)Non-functional requirements and explicit planning assumptions
- Latency: Under 200 ms end-to-end delivery for connected users in the same region.
- Availability: 99.99% uptime for sending and receiving (~52.6 minutes of allowed downtime per year), surviving single-server or full availability-zone (AZ) outages.
- Durability & retention: Zero lost messages once acknowledged; retain searchable history for at least 5 years.
- Scale given & derived: 10M Daily Active Users (DAU), 50,000 peak messages/s, average 50 channels per user, public channels up to 100,000 members. Assuming 100 messages/day per DAU (including automated build/alert bots) yields 1B messages/day (~11,600 msg/s average, so 50,000 msg/s peak is ~4.3x average). At peak, 60% of DAU are online across 1.3 devices each (~7.8M concurrent connections), with ~500 bytes stored per message.
Estimate throughput, connections, fan-out, and 5-year storage
1. Message write & storage volume Average send rate: 1,000,000,000 / 86,400 s = ~11,600 msg/s Peak send rate (given): = 50,000 msg/s Daily logical data: 1B msgs x 500 bytes = 500 GB/day Hot tier (recent 13 mos): 500 GB x 395 days = ~200 TB logical 5-year retention: 500 GB x 365 x 5 = ~912 TB logical (~2.7 PB raw at 3x replication) SQL write shards needed: 50,000 txns/s / ~800 txns/s per shard = ~63 -> 64 shards (~3.1 TB hot/shard) 2. Persistent connections (WebSockets) Peak concurrent sockets: 10M DAU x 60% online x 1.3 devices = 7.8M WebSockets Gateway sizing: At 50,000 sockets/node -> 156 nodes minimum. Deploy 240 nodes (80 per AZ across 3 AZs) so losing an entire AZ leaves 160 x 50,000 = 8.0M capacity with zero dropped service! Heartbeats (every 30 s): 7.8M / 30 s = ~260,000 pings/s (terminated locally on gateways) Reconnect churn: 10M users x 10 reconnects/day = ~1,200/s avg (~12,000/s morning wave) 3. Real-time fan-out math Typical channel (~20 online sockets): 50,000 msg/s x 20 = ~1,000,000 socket frames/s (~1 GB/s egress) 100k-member channel (30% online x 1.3): ~39,000 online sockets for ONE message! 10 msgs/s in that channel = 390,000 socket writes/s! 4. History & sync reads Channel opens: 10M users x 30 opens/day = ~3,500/s avg (~14,000/s peak), 50 msgs/pageWhat the numbers reveal: Storing 50,000 messages/s splits cleanly across 64 conversation shards, and 5 years of history fits comfortably if we tier older data to dense archive storage. The three hard problems are gap-free per-channel ordering, fanning out to 39,000 sockets in a 100k-member channel without melting databases or networks, and managing 7.8M stateful connections + presence without broadcast storms.
Design the HTTP and WebSocket APIs
We send mutations and paginated reads over stateless HTTPS (giving standard load balancing, HTTP status codes, and retries) while pushing live events over one persistent WebSocket (a long-lived, two-way TCP connection that lets servers push frames instantly without client polling) per device.
HTTPS Endpoints (Stateless API Tier) POST /v1/conversations/{conv_id}/messages Body: { "client_msg_id": "c4b8e110-...", "text": "Release v2.4 is live", "thread_root_seq": null } 201 OK: { "conversation_id": 410, "seq": 8201, "client_msg_id": "c4b8e110-...", "created_at": "2026-11-30T10:15:02.113Z" } 200 OK: (identical payload returned if client_msg_id was already committed on an earlier try) GET /v1/conversations/{conv_id}/messages?before_seq=8201&limit=50 (scroll up: older page) GET /v1/conversations/{conv_id}/messages?after_seq=8150&limit=200 (reconnect gap-fill) GET /v1/sync (returns {conv_id, last_seq, last_read_seq, mentions}[]) POST /v1/conversations/{conv_id}/read { "seq": 8201 } (advances user's read marker) POST /v1/rt/connect -> { "wss_url": "wss://gw-117.chat.internal/ws", "ticket": "one-time-30s-token" } WebSocket Frames (wss://gw-117...) Client -> Server: auth { "ticket": "..." } (sent in first frame so tokens never leak in URL logs) focus { "conversation_id": 410 } (marks which channel is currently open on screen) presence_sub { "user_ids": [44, 91, ...] } (subscribes only to visible teammates, max 500) ping {} Server -> Client: message { "conversation_id": 410, "seq": 8201, "client_msg_id": "c4b8...", "sender": {"id": 12, "name": "Maya", "avatar": "..."}, "text": "Release v2.4 is live" } activity { "conversation_id": 999, "last_seq": 55210 } (lightweight unread hint for huge channels) read_marker { "conversation_id": 410, "seq": 8201 } (clears unread badge on my other devices) presence { "user_id": 44, "status": "online" } reconnect { "jitter_ms": 15000 } (graceful drain before gateway deploy)Two fields anchor ordering and reliability across the entire stack:
client_msg_id: A UUID generated by the sender's device before the first network attempt and reused across retries, guaranteeing idempotent sends.seq: A monotonic sequence number (1, 2, 3, ..., increasing by exactly 1 with zero gaps inside eachconversation_id) assigned by the server, which every client uses to sort messages and spot missing events.
Data model, storage engines, and sharding strategy
Why sharded SQL for hot messages + a wide-column store for the 5-year archive?
On every message send, we must atomically: verify membership, check
client_msg_iddeduplication, incrementlast_seqby 1 without holes, and insert the message. A sharded relational database (such as PostgreSQL with Citus or MySQL with Vitess, partitioned byconversation_id) executes all four operations in a fast single-shard ACID transaction. By contrast, a wide-column store (a NoSQL engine like Cassandra or ScyllaDB built for massive partitioned appends) lacks cheap multi-table transactions; keepinglast_seq, deduplication, and message rows strictly consistent in Cassandra requires a lightweight transaction (a multi-round-trip Paxos consensus write that degrades sharply on hot channels). However, once messages are > 13 months old, they become immutable range reads — making a dense wide-column cluster ideal for the remaining 4 years of our 5-year retention!-- ========================================================================= -- CONVERSATION SHARDS (64 SQL shards, directory-mapped by conversation_id) -- ========================================================================= CREATE TABLE conversations ( conversation_id BIGINT PRIMARY KEY, workspace_id BIGINT NOT NULL, kind VARCHAR(16) NOT NULL, -- 'public', 'private', 'dm', 'group_dm' last_seq BIGINT NOT NULL DEFAULT 0, -- authoritative monotonic counter archived_below_seq BIGINT NOT NULL DEFAULT 0, -- rows <= this seq live in the archive store member_count INT NOT NULL DEFAULT 0 ); CREATE TABLE conversation_members ( conversation_id BIGINT NOT NULL, user_id BIGINT NOT NULL, role VARCHAR(16) NOT NULL, PRIMARY KEY (conversation_id, user_id) ); CREATE TABLE messages ( conversation_id BIGINT NOT NULL, seq BIGINT NOT NULL, sender_id BIGINT NOT NULL, client_msg_id UUID NOT NULL, body TEXT NOT NULL, thread_root_seq BIGINT, version INT NOT NULL DEFAULT 1, -- incremented on message edit or soft-delete created_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (conversation_id, seq) -- clusters channel history contiguously on disk! ); CREATE TABLE send_dedup ( -- TTL-purged after 48 hours conversation_id BIGINT NOT NULL, client_msg_id UUID NOT NULL, seq BIGINT NOT NULL, created_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (conversation_id, client_msg_id) ); CREATE TABLE outbox ( -- transactional outbox for crash-safe Kafka publish conversation_id BIGINT NOT NULL, seq BIGINT NOT NULL, payload BYTEA NOT NULL, created_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (conversation_id, seq) ); -- ========================================================================= -- USER SHARDS (SQL shards partitioned by user_id) -- ========================================================================= CREATE TABLE user_conversations ( user_id BIGINT NOT NULL, conversation_id BIGINT NOT NULL, last_read_seq BIGINT NOT NULL DEFAULT 0, muted BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (user_id, conversation_id) ); CREATE TABLE user_mentions ( user_id BIGINT NOT NULL, conversation_id BIGINT NOT NULL, seq BIGINT NOT NULL, PRIMARY KEY (user_id, conversation_id, seq) -- natural PK makes mention counting idempotent );Three critical partitioning choices:
- Shard by
conversation_id, NOTworkspace_id: Sharding by customer workspace would cram a 200,000-employee enterprise onto a single overloaded database node. Sharding byconversation_idspreads a giant company's thousands of channels evenly across all 64 shards while keeping any single channel'sGET ?before_seq=...page a fast single-shard index range scan. - Directory-based mapping instead of static
hash(id) % 64: A cached lookup table (conversation_id -> shard_id) lets us isolate an unusually noisy channel onto its own dedicated shard without reshuffling terabytes of neighbors. - Dual-indexed membership:
conversation_members(sharded byconversation_id) lets the send transaction check posting permissions locally in 0 extra network hops, whileuser_conversations(sharded byuser_id) powers fast sidebar loading on login.
- Shard by
High-level architecture: separating durable writes from real-time push
By decoupling the write and push paths, durable persistence (Stateless Message Service + SQL Conversation Shards) operates independently from best-effort real-time delivery (Kafka + Fan-out Workers + Redis Subscription Router + Stateful WebSocket Gateways). Even if a push notification drops during a gateway restart, zero data is lost because clients detect
seqgaps and fetch from durable storage.Sender / Reader Clients (Web, Desktop, Mobile) │ │ │ HTTPS (POST message, GET history, /sync) │ Persistent WebSocket (1 per online device) ▼ ▼ ┌─────────────────────────┐ ┌───────────────────────────────────┐ │ Stateless Message API │ │ WebSocket Gateway Fleet (240 pods)│ └────┬───────────────┬────┘ │ In-RAM map: conv_id -> [sockets] │ │ 1. ACID txn │ 2. Direct publish └───▲───────────────────┬───────────┘ ▼ ▼ │ 5. Batched gRPC │ Subscribe (0->1) / ┌──────────┐ ┌────────────────────────┐ │ push frames │ Unsubscribe (1->0) │ 64 Conv │ │ Kafka: conv-events │ │ ▼ │ SQL │ │ (partitioned by conv) │ │ ┌────────────────────────────┐ │ Shards │ └───────────┬────────────┘ │ │ Subscription Router (Redis)│ └────┬─────┘ ▼ │ │ sub:{conv_id} -> {gw_ids} │ │ ┌────────────────────────┐ │ └────────────────────────────┘ Outbox Relay ─►│ Fan-out Workers ├─────┘ (fallback if │ - order by seq ├──► Redis last_seq cache (for /sync) API crashes) │ - lookup sub:{conv_id} │──► Async consumers: @mentions, APNs/FCM push │ └────────────────────────┘ ▼ Monthly Tiering Job (>13 mos) ──► Read-Only Wide-Column Archive (5-year retention)Deep dive 1: Gap-free per-conversation ordering and idempotent sends
Why not sort messages by client or server timestamps? Device clocks drift by seconds, and even NTP-synchronized backend servers disagree by several milliseconds — meaning two rapid replies could flip order after a page refresh! Instead, each conversation assigns a gap-free integer
seq = 1, 2, 3, ...inside aREAD COMMITTEDtransaction on its owning SQL shard:BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED; -- 1. Lock ONLY this conversation's header row (serializes concurrent sends in this one channel) SELECT last_seq FROM conversations WHERE conversation_id = :c FOR UPDATE; -- 2. Idempotency check AFTER acquiring the lock: if an earlier retry just committed, -- READ COMMITTED immediately sees its row here and returns the original seq with zero side effects! SELECT seq FROM send_dedup WHERE conversation_id = :c AND client_msg_id = :k; -- (If found -> COMMIT immediately and return 200 OK with the existing seq!) -- 3. Authoritative membership check on the exact same shard SELECT 1 FROM conversation_members WHERE conversation_id = :c AND user_id = :u; -- 4. Advance monotonic counter (:next_seq = last_seq + 1) and persist message + dedup + outbox UPDATE conversations SET last_seq = :next_seq WHERE conversation_id = :c; INSERT INTO messages (conversation_id, seq, sender_id, client_msg_id, body, created_at) VALUES (:c, :next_seq, :u, :k, :body, now()); INSERT INTO send_dedup (conversation_id, client_msg_id, seq, created_at) VALUES (:c, :k, :next_seq, now()); INSERT INTO outbox (conversation_id, seq, payload, created_at) VALUES (:c, :next_seq, :event_bytes, now()); COMMIT;Why every durability and latency requirement holds here:
- Zero holes in
seq: Because the counter update andmessagesinsert commit or roll back together,seqnever skips numbers. When a client seesseq = 10followed byseq = 12, it knows with 100% certainty thatseq = 11exists and must be fetched. - 99.99% durable acknowledgement: Each SQL shard uses semi-synchronous replication (the primary waits ~2–3 ms for at least one standby replica in a different availability zone to write the transaction log before returning
COMMIT). Once the client receives201 Created, even an entire datacenter power loss cannot lose that message. - Throughput per channel vs. latency budget: Holding the row lock for ~3–5 ms caps a single conversation at ~200–300 messages/s (far faster than humans can read in one channel; if a bot firehose ever needs more, the shard batches
Nqueued sends into a single lock acquisition allocatinglast_seq + 1 .. last_seq + N). End-to-end p95 latency stays right around ~80 ms against our 200 ms budget:
Sender -> Edge -> Message API: ~30 ms Single-shard SQL txn + cross-AZ ack: ~5 ms Kafka publish (acks=all) + Worker read: ~10 ms Redis router lookup + Gateway gRPC: ~3 ms Gateway WebSocket -> Recipient device: ~30 ms ---------------------------------------------- Total end-to-end delivery latency: ~78 ms (leaves >120 ms headroom under 200 ms SLO!)- Zero holes in
Deep dive 2: Real-time fan-out from 1-on-1 DMs to 100,000-member channels
Why naive "fan-out on write" fails at enterprise chat scale
In small consumer apps, fan-out on write copies every new message into a personal inbox table for each recipient. In a 100,000-member company announcement channel, one
"All-hands starts in 5 minutes"post would trigger 100,000 database writes; 10 messages/s would trigger 1,000,000 writes/s from a single channel! Instead, we store each message once per conversation and use two-tier pub/sub fan-out (a publish/subscribe routing layer where workers send at most one copy per interested gateway server, and each gateway fans out in memory to local sockets):- Workspace-aware gateway placement:
POST /v1/rt/connectuses consistent hashing (mappingworkspace_idonto a bounded slice of gateways with overflow spillover) so colleagues at a 50-person startup land on just 2–3 gateways instead of all 240. - Gateway-level reference counting: When Maya connects to
gw-17and belongs to 50 channels,gw-17increments its in-memory subscriber count for each channel. Only when a channel's local count ongw-17transitions0 -> 1doesgw-17runSADD sub:{conv_id} gw-17in the Redis Subscription Router (andSREMon1 -> 0). - Two-hop message push: A Fan-out Worker consumes
(conv_id=410, seq=8201)from Kafka, updateslast_seqin Redis, readsSMEMBERS sub:410->[gw-17, gw-42], and sends at most 240 batched gRPC messages even if 39,000 sockets are online in a 100,000-member channel! Each gateway then loops over its ~160 local sockets in microseconds.
Large-channel "focus vs. activity hint" mode (> 10,000 members)
Even in memory, pushing 1 KB JSON payloads to 39,000 sockets for a channel 95% of users do not even have open wastes bandwidth and triggers client CPU spikes. For channels with > 10,000 members:
- Sockets currently viewing that channel (
focusframe active) receive the fullmessageframe immediately. - The other ~95% of online sockets receive a tiny coalesced
activityhint ({"conversation_id": 999, "last_seq": 55210}) at most once every 2 seconds, which simply bolds#announcementsin their sidebar; the client pulls the messages viaGET /messagesonly if the user clicks the channel!
Closing the reconnect race: always subscribe BEFORE
/syncA classic distributed-systems bug happens during login if a client fetches
/syncfirst and subscribes to live pushes second. Look at the timeline difference:BROKEN ORDER (Sync -> Subscribe): t1: Client calls GET /sync -> sees last_seq = 100 t2: Teammate sends seq = 101 -> Router sees 0 gateways subscribed -> push not sent to us! t3: Gateway registers sub:{conv} -> seq = 101 fell into the crack and is invisible until reopen! SAFE ORDER (Subscribe -> Sync, paired with Worker updating last_seq cache BEFORE reading Router): t1: Gateway registers SADD sub:{conv} gw-17 t2: Teammate sends seq = 101 (Worker sets cache last_seq=101, then reads sub:{conv} -> pushes 101!) t3: Client calls GET /sync -> sees last_seq = 101 AND receives push 101 -> deduplicates by seq!- Workspace-aware gateway placement:
Deep dive 3: Client deduplication, gap recovery, and unread badges
Client-side state machine (
contiguous_seq)Because network pushes are at-least-once and out-of-order edge cases can occur during failovers, every client maintains
contiguous_seq— the highestseqin each open conversation for which it has every message1 .. contiguous_seqwith zero holes:Initial client state in channel #releases: contiguous_seq = 20 1. Receives push seq = 21: 21 == contiguous_seq + 1 -> render immediately; contiguous_seq = 21. 2. Receives push seq = 21: 21 <= contiguous_seq -> duplicate retry! Silently drop. 3. Receives push seq = 23: 23 > contiguous_seq + 1 -> gap (missing 22)! Buffer 23 in memory, start a 300 ms timer in case 22 is merely delayed in transit. 4. Timer fires at +300 ms: Client calls GET /messages?after_seq=21 (routed to SQL PRIMARY so replica lag cannot hide seq 22!) -> receives [22, 23] -> renders 22, flushes buffered 23, advances contiguous_seq = 23!For the sender's own message, the UI immediately renders an optimistic grey row keyed by
client_msg_id, upgrading it in place toseq = 8201as soon as either the201HTTP response or the WebSocket echo arrives.Unread indicators and monotonic read markers
- Forward-only read cursor: When a user views messages up to
8201, the client debounces updates (waiting ~2 seconds so fast scrolling sends one request instead of fifty) and callsPOST /read {seq: 8201}, which runsUPDATE user_conversations SET last_read_seq = GREATEST(last_read_seq, 8201). UsingGREATESTguarantees an out-of-order mobile retry never moves a read marker backward and resurrects already-read notifications. - Sidebar badges:
/synccompares each channel's cachedlast_seqagainstlast_read_seq: iflast_seq > last_read_seq, the channel name renders bold, and the red badge count equalsCOUNT(*) FROM user_mentions WHERE seq > last_read_seq. Per-user "Seen by X" receipts are enabled only in 1-on-1 DMs and groups <= 10 members, avoiding O(N^2) read-receipt storms in large channels.
- Forward-only read cursor: When a user views messages up to
Deep dive 4: Scalable user presence without broadcast storms
Why is presence surprisingly dangerous at 10M DAU? If one user joining a 100,000-member channel broadcast
"user 44 is online"to all 39,000 online channel-mates, morning login churn would generate hundreds of millions of presence frames per second, dwarfing actual chat traffic! We tame presence with three rules:- Absorb heartbeats at the edge: Clients ping their gateway every 30 seconds (~260,000 pings/s total). Gateways absorb pings in memory and only notify the Presence Service (in-memory shards partitioned by
user_id) on actual state transitions (offline -> online,online -> awayafter 10 minutes idle, oronline -> offlineafter a 60-second disconnect grace window so brief elevator/Wi-Fi handoffs do not flicker green dots). Each gateway also sends one node-level heartbeat every 10 seconds so a dead gateway's users time out cleanly after 30 seconds. - Viewport-scoped subscriptions (
presence_sub): Clients never subscribe to 100,000 channel members. Instead, the UI subscribes only to the ~20–50 avatars currently visible on screen (DM sidebar + visible viewport rows, capped at 500 user IDs). - Gateway aggregation & coalescing: Gateways merge local viewport subscriptions and push updates coalesced to at most 1 transition/user/second. Total load drops to ~2,300 transitions/s x ~20 interested viewers = ~46,000 frames/s (< 5% of chat message traffic, completely independent of channel size!).
- Absorb heartbeats at the edge: Clients ping their gateway every 30 seconds (~260,000 pings/s total). Gateways absorb pings in memory and only notify the Presence Service (in-memory shards partitioned by
Bottlenecks, failure recovery, and summary of trade-offs
Component failure matrix (achieving 99.99% availability)
Failure Event Impact & Automatic Recovery ---------------------------------- ------------------------------------------------------------------ API crashes after SQL COMMIT Outbox relay worker scans outbox rows > 2 s old and publishes to Kafka; duplicate pushes are dropped by clients via seq <= contiguous_seq. SQL shard primary node dies Orchestrator promotes the cross-AZ semi-sync standby within ~10 s; zero acknowledged messages lost; clients auto-retry queued sends using the same client_msg_id. Gateway pod crashes (~32k sockets) Clients reconnect using exponential backoff with random jitter (spreading 32k reconnects evenly across 0-30 s = ~1,100/s instead of a spike), re-subscribe, and fill missed messages via /sync. Redis Subscription Router failover Gateways detect router epoch change and replay their in-memory local subscription sets (rate-limited); missed pushes heal via /sync. Entire Availability Zone outage Remaining 2 AZs hold Kafka quorum, semi-sync SQL replicas, and 160 gateways (8.0M socket slots > 7.8M peak demand).Summary of core trade-offs
- Sharded SQL (hot 13 mos) + Wide-Column Archive (years 2–5): Gives single-shard ACID transactions for gap-free
seqand deduplication on recent chats while keeping 5-year storage dense and cheap. - Per-conversation row lock + cross-AZ semi-sync ack: Adds ~3–5 ms to sends and caps one channel at a few hundred msgs/s, buying strict zero-loss durability and hole-free ordering without clock-skew bugs.
- Gateway-level pub/sub + unfocused
activityhints vs. per-user inbox writes: Turns a 100,000-member message into <= 240 gateway RPCs instead of 100,000 database writes, at the tiny cost of one HTTP fetch when an unfocused user clicks a bolded channel. - Viewport-scoped presence vs. global broadcast: Keeps presence bandwidth tiny and constant regardless of channel size, showing live green dots strictly for teammates currently on screen.
- Sharded SQL (hot 13 mos) + Wide-Column Archive (years 2–5): Gives single-shard ACID transactions for gap-free
Intuition & how it works
Think of a real-time workspace chat service as a court stenographer paired with a building PA intercom: inside every room (channel or DM), one official stenographer stamps every spoken line onto a permanent paper roll with a strictly sequential line number (1, 2, 3, ...) before nodding to the speaker (201 Created). Separately, an intercom operator broadcasts each stamped line once to whichever hallway speakers (WebSocket gateway servers) currently have listeners in that room — and if someone walks through a dead Wi-Fi tunnel and misses an announcement, their app immediately notices "I jumped from line 20 to line 22!" and reads line 21 straight off the stenographer's permanent roll.
Why do naive chat designs collapse at scale? Sorting messages by timestamps fails because phones and servers have slightly different clocks, causing rapid replies to scramble out of order. Copying every message into a personal database inbox for every member (fan-out on write) means a single post in a 100,000-person company channel triggers 100,000 database writes — melting storage at just a few messages per second. And treating in-memory pub/sub (publish/subscribe broadcast) as the only delivery path silently drops messages whenever a server restarts or a mobile connection switches from Wi-Fi to 5G.
Let's trace a concrete 4-step example when Maya posts "Release v2.4 is live" to #releases while Liam is watching and Priya briefly loses Wi-Fi:
1. Idempotent, gap-free write (Stateless API -> SQL Conversation Shard #9):
Maya sends POST /conversations/410/messages {client_msg_id: "c4b8-...", text: "Release v2.4 is live"}.
Shard #9 locks conversation 410, sees "c4b8-..." is new, increments last_seq 20 -> 21, writes
messages(410, seq=21) + send_dedup + outbox, waits ~3 ms for a cross-zone replica ack, and
returns 201 Created (seq=21). (If Maya's phone retries "c4b8-...", send_dedup returns seq=21!)
2. Two-tier gateway pub/sub fan-out (Kafka -> Fan-out Worker -> Gateways):
Worker reads (conv=410, seq=21), updates Redis last_seq=21, checks Redis sub:410 -> [gw-3, gw-8].
Even if 5,000 teammates are online across gw-3 and gw-8, the worker sends just TWO batched gRPC
calls (one to gw-3, one to gw-8), and each gateway pushes seq=21 over local WebSockets in ~30 ms.
3. Live render for Liam (total end-to-end latency ~80 ms, well under 200 ms):
Liam's app holds contiguous_seq = 20 -> receives seq = 21 (20 + 1) -> renders immediately!
4. Automatic gap healing for Priya (dropped Wi-Fi during seq=21, reconnects when seq=22 arrives):
Priya's app holds contiguous_seq = 20 -> receives seq = 22 -> spots missing seq = 21!
Calls GET /conversations/410/messages?after_seq=20 -> fetches [21, 22] from Shard #9 primary ->
renders 21 then 22 in exact order with zero lost or duplicated messages.
Key trade-offs
- Sharded SQL for recent messages (13 months) + wide-column store for cold archive (years 2–5). A single-shard SQL transaction atomically checks membership, enforces
client_msg_ididempotency (preventing duplicates on retry), incrementslast_seq, and stores the message. A wide-column store (like Cassandra/ScyllaDB) scales raw disk capacity effortlessly for our 5-year (~0.9 PB logical) archive, whereas using it on the live send path would require expensive Paxos lightweight transactions on every message to prevent sequence holes. - Per-conversation monotonic
seq(1, 2, 3, ...) vs. global Snowflake IDs or timestamps. A gap-free per-channel counter makes missing-message detection trivial (12 > 10 + 1) and completely immune to clock skew. The trade-off is a row lock per channel (~3–5 ms hold time), capping one channel at a few hundred messages/s — plenty for human chat, with batch sequence allocation available for bot firehoses. - Cross-AZ semi-synchronous commit before
201ack vs. asynchronous replication. Waiting ~2–3 ms for a standby replica in a second availability zone to log the commit before acknowledging guarantees zero lost acknowledged messages even if an entire datacenter goes dark, well within our 200 ms latency budget (~80 ms typical end-to-end). - Best-effort push +
seqcatch-up vs. heavy per-user durable queues. Tracking per-device broker acknowledgements across 7.8M WebSockets (persistent two-way TCP connections) at 1M frames/s is brittle and expensive. Keeping the push layer stateless and repairing drops viacontiguous_seq+/syncmakes gateway crashes harmless. - Gateway-level pub/sub + unfocused
activityhints vs. fan-out on write. Sending one RPC per gateway (<= 240 nodes) and sending coalesced 2-secondactivityhints to members not actively viewing a 100,000-person channel slashes database writes from 100,000 to 1 and cuts edge bandwidth by ~95%, trading one fast cached HTTP read when a user clicks the channel. - Viewport-scoped presence vs. channel-wide presence broadcast. Subscribing only to the <= 500 teammates visible on screen keeps presence traffic around ~46,000 frames/s instead of hundreds of millions of frames/s when large channels churn.
Common mistakes
- Sorting or paginating chat history by timestamps, causing out-of-order messages across devices with skewed clocks and skipping messages that share the exact same millisecond.
- Generating
seqin Redis or memory outside the database transaction, which permanently leaves sequence numbers with holes whenever a subsequent database insert fails or rolls back (making clients stall waiting for a message that never existed). - Returning
201to the sender as soon as an event hits an in-memory pub/sub broker or an unreplicated primary, violating the zero-data-loss durability requirement on node failure. - Writing one row per channel member (
fan-out on write) for large channels, turning 10 messages/s in a 100,000-member channel into 1,000,000 database writes/s. - Partitioning messages by
workspace_idinstead ofconversation_id, turning the largest enterprise customer into an unscalable single-shard bottleneck. - Calling
/syncbefore registering WebSocket channel subscriptions on reconnect, opening a race window where messages sent between/syncandsubscribeare missed by both paths. - Serving gap-fill (
?after_seq=...) queries from lagging read replicas, causing a client that just saw a push forseq = 12to get an empty response when asking a 500 ms-lagging replica forseq = 11. - Reconnecting all 32,000+ clients of a crashed gateway immediately without random jitter, creating a thundering herd (simultaneous request stampede) that knocks over
/rt/connectand/sync.
Follow-up questions
- How do you prevent a stampede on gateways and databases when a 100,000-person announcement channel experiences a sudden burst of posts? On the write and push paths, per-channel posting rules/rate limits bound ingress while gateway-level pub/sub sends at most 240 batched gRPC calls per message; critically, the ~95% of online members who do not have that channel open on screen receive at most one coalesced
activityhint every 2 seconds instead of every message frame. To protect backend databases when thousands of curious users click the bolded channel at once, push payloads inline sender display names and avatar URLs (preventing 30,000 profile lookups), Redis caches the newest 50 messages of hot channels using request coalescing / singleflight (collapsing 5,000 simultaneous cache misses on the same key into a single SQL read), clients add 0–2 seconds of random jitter before background fetches, and client read-marker updates (POST /read) are debounced and batched. Meanwhile, mobile push notifications for offline members flow through a separate rate-limited Kafka consumer group so they never add latency to live WebSocket delivery. - How would you support binary file uploads and rich link or media previews safely without stalling the low-latency text messaging path? Binary payloads never touch the chat API, Kafka topics, or WebSocket frames: instead, the client calls a separate File Service to obtain a presigned URL (a short-lived, signed upload link), uploads bytes directly to object storage, and posts the chat message referencing only
file_id. The attachment initially renders with aprocessingplaceholder while isolated background workers run malware scans, strip EXIF location metadata, and generate compressed image/video thumbnails; once clean, the File Service triggers a lightweightmessage_changedevent (version + 1) so open clients swap in the inline preview. Downloads check that the requester belongs to a conversation wherefile_idwas shared before issuing a 5-minute signed CDN URL, while external URL unfurling runs in an isolated scraper tier with strict byte/timeout caps and private-IP blocking to prevent SSRF (Server-Side Request Forgery). - How would you replicate conversations across multiple geographic regions while preserving causal reply order for globally distributed teammates? Assign every conversation (or workspace) a single authoritative home region responsible for assigning its monotonic
seq = 1, 2, 3, ..., while deploying local WebSocket gateways, Redis caches, and read replicas in every user region (US, EU, APAC) fed by asynchronous cross-region Kafka/log replication so each message crosses the ocean once rather than once per recipient. Within any single conversation, causal ordering (guaranteeing that if User B reads Message X and replies with Message Y, everyone sees X before Y) holds automatically because User B's reply travels to the same home-region sequencer after X was already assigned a lowerseq; for cross-channel quote-replies, the payload carriesquoted_ref: (conv_id, seq)and remote clients hold rendering briefly if their local replica has not yet caught up toseq. The explicit trade-off is that senders far from a channel's home region pay one inter-continental round-trip (~80–180 ms, masked in the sender's UI by an immediate optimistic local echo usingclient_msg_id), and surviving a catastrophic full-region outage without losing the last ~100 ms of in-flight commits requires synchronous cross-region quorum replication on the home shard.
Follow-up questions
- How do you prevent a stampede on gateways and databases when a 100,000-person announcement channel experiences a sudden burst of posts?
- How would you support binary file uploads and rich link or media previews safely without stalling the low-latency text messaging path?
- How would you replicate conversations across multiple geographic regions while preserving causal reply order for globally distributed teammates?
Similar questions
- Hourly Window Billing With Rate Overrides
- Longest-Running Timeline Tags After Overwrites
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests