Direct Two-Person Web Messaging
Hard · System Design · Software Engineer · Technical Screen
Prompt
Design a browser-based private messaging backend where signed-in users exchange plain-text messages in strictly two-person threads (for example, Maya and Liam chatting in conv_74). Assume 100 million daily active web users, each sending 100 messages per day on average—roughly 116,000 message writes per second steady-state before you apply an explicit peak-load factor and storage projection. Group channels, mobile push notifications, file or media uploads, public online indicators, typing signals, end-to-end encryption key handling, and content moderation are excluded from scope, though an internal routing table may track which edge gateway currently holds a user's open browser connection.
Your architecture must satisfy the following operational and consistency requirements:
- Idempotent durable writes & single thread order: A send operation returns a stable message ID and success to the caller only after the record is durably persisted (
p95 < 300 ms), surviving routine host crashes and single-availability-zone outages, with at least1 yearof retained history. Retries must never produce duplicate visible entries, and every two-person thread must expose a single consistent message order. - Low-latency delivery & shard-free catch-up: Online recipients should see newly committed messages in
< 1 secondwithout duplicate rendering. Build a dedicated user-to-thread index so reconnecting browsers list all threads they belong to, paginate ordered history, and catch up from a saved cursor without scanning across message partitions. - Replica-aware reads, caching & spike protection: Backward history pagination and offline catch-up may read from bounded-lag replicas, whereas live gap repair for a just-committed message on an open client must consult an authoritative fresh source. When traffic surges abruptly, protect durable sends first while explicitly shedding or delaying historical reads, and detail the exact workload each cache removes without letting cached state become authoritative.
- Replayable event streaming: Route committed writes through a persistent, replayable log with bounded consumer delay. Detail how Apache Kafka (key partitioning, producer retry deduplication, offset replay, consumer groups, and lag bounds) supports this pipeline, and contrast it with Redis Pub/Sub and Redis Streams for low-latency fan-out versus crash recovery (any alternative log technology works provided it enforces identical per-thread ordering, multi-day retention, offset replay, and consumer-group coordination).
- Multi-region extension: Suppose the two participants connect through different geographic regions. Explain thread placement and request routing, cross-region push and replay, storage overhead, and recovery when an inter-region link severs versus when an entire region fails. Preserve one thread order, retry identity, authorization checks, and explicit read-freshness metadata; state your replication and commit policy, which acknowledged writes survive a full regional outage, when writes must pause to prevent conflicting owners, and what WAN latency and recovery bounds your chosen topology achieves on top of the single-region baseline.
Scope & Expectations
- Establish concrete capacity, throughput, storage, and latency budgets alongside clear entity boundaries separating authoritative thread records, per-user inbox indexing, and replaceable socket-location state.
- Define client request and WebSocket contracts—including idempotent retries, cursor resumption, throttling, uncertain timeouts, and replica-lag repair—backed by an end-to-end architecture and a rigorous comparison of Kafka, Redis Streams, and Redis Pub/Sub.
- Extend the design across regions with explicit ownership fencing, WAN latency accounting, read-staleness reporting, and failure behavior under both network partitions and full regional loss.
Step-by-step walkthrough
Clarify requirements, guarantees, and non-functional targets
A private two-person messaging service looks simple on the surface, yet at 100 million daily active users (DAU) it requires crisp separation between authoritative message persistence, per-user conversation discovery, and ephemeral live connection routing.
Scope & core functional guarantees: - Strictly two-person web chat: Signed-in browsers exchange plain-text messages inside private two-person threads (
participant_a,participant_b). Multi-user rooms, file uploads, mobile push alerts, live typing animations, public online badges, client-side E2EE key exchange, and abuse filtering stay outside scope. - Durable idempotent sends: A caller sees success only after the record commits to a quorum (a majority of storage replicas, such as 2 out of 3 data centers) and flushes to disk (fsync), keyed by an idempotency key (client_msg_id— a unique per-attempt token minted by the browser so retries never produce duplicate entries). - Single total order per conversation: Every thread assigns a dense, strictly increasing integerseq = 1, 2, 3, ...so both peers always view identical ordering and immediately detect any missing sequence number. - Sub-second live push & index-driven catch-up: Active recipients see committed writes in< 1 s, while returning browsers list their active threads and resume from a saved cursor via a user-sharded index—avoiding scatter-gather reads across message partitions. - Write priority during surges: Under sudden load spikes, compute and disk budgets protect durable commits and live push first while throttling or shedding cold historical scrollback.Most important non-functional targets:
Quality / Metric Design Target / Contract -------------------------------------------------------------------------------- Daily scale 100M DAU, web clients only (WebSocket/HTTPS) Durable send acknowledgement p95 < 300 ms (after 3-AZ quorum disk commit) Online live delivery to recipient p95 < 1,000 ms (end-to-end send -> browser) Fault tolerance (single-region) Zero loss of acked messages on 1-AZ failure History retention >= 1 year of ordered conversation history Read consistency Bounded-lag replicas OK for history/catch-up; authoritative primary required for gap repairBack-of-the-envelope traffic, connection, and storage math
Calculating write rates, concurrent sockets, and annual storage upfront shows why single-node databases, scatter-gather queries, and RAM-only event buses fail at this scale.
1. Message Write & Inbox Throughput - Total daily writes: 100,000,000 DAU * 100 msgs/day = 10,000,000,000 (10B) msgs/day - Average write rate: 10,000,000,000 / 86,400 s ~= 115,741 ~= 116,000 writes/s - Peak multiplier: 3x daily peak -> ~348,000 writes/s 5x sudden flash burst -> ~580,000 writes/s - Inbox updates/s: Every 1:1 message updates 2 participant inboxes -> ~232,000 avg / ~696,000 peak inbox index updates/s 2. Concurrent Web Connections & Connection Directory - Peak online tabs: Assume 25% of DAU online concurrently at peak, ~1.2 tabs/user -> 25M users * 1.2 = 30,000,000 concurrent WebSockets - Gateway fleet: At 50,000 open sockets per gateway host -> ~600 gateway VMs - Directory footprint: 30M entries * ~100 bytes (user_id -> gateway_id, socket_id, ttl) ~= 3 GB in-memory (fits easily in a small sharded Redis cluster) 3. Storage Forecast (1-Year Retention) - Per-message size: ~250 B UTF-8 text + ~150 B metadata/idempotency + ~100 B index ~= 500 bytes logical per message - Daily logical growth:10B msgs/day * 500 B = 5.0 TB/day - 1-year logical data: 5.0 TB/day * 365 days = 1.825 PB/year - Raw physical disk: With 3-way multi-AZ replication -> ~5.5 PB/year raw SSD before compression (~2 PB physical once older months > 30 days compact in compressed Log-Structured Merge-tree [LSM-tree] tiers while staying indexed by (conversation_id, seq)).Model conversations, ordered messages, inbox index, and connection state
Because callers query data in two completely different ways—"read messages in conversation C" versus "list all conversations for user U"—we split durable storage into conversation-partitioned shards and user-partitioned inbox shards, paired with an ephemeral connection directory.
1. Conversation & Message Shard (partitioned by
hash(conversation_id)): -conversations: -conversation_id: deterministic UUID derived from canonical sorted pair(min(user_a, user_b), max(user_a, user_b))so two users share at most one 1-on-1 conversation. -user_low_id,user_high_id(immutable participant membership),last_seq(monotonicBIGINTstarting at0),home_region,epoch(monotonic ownership generation1, 2, ...),created_at. -messages: - Primary key(conversation_id, seq ASC)so range queries read contiguous ordered blocks on disk. -epoch,message_id(UUIDv7 — time-ordered unique ID),sender_id,client_msg_id,body_text,committed_at. -message_idempotency(co-located on the exact sameconversation_idshard!): - Primary key(conversation_id, sender_id, client_msg_id)->(seq, epoch, message_id, committed_at), retained for 7 days so retries resolve inside one local single-shard transaction.2. User-to-Conversation Inbox Index (partitioned by
hash(user_id)): -user_inbox: - Primary key(user_id, conversation_id), plus local secondary index(user_id, inbox_sync_seq DESC). - Fields:peer_user_id,latest_conv_seq(highest messageseqindexed for that conversation),last_acked_conv_seq(durable client cursor),preview_text,updated_at, andinbox_sync_seq(a per-user monotonic integer incremented whenever any conversation ofuser_idadvances). - Whyinbox_sync_seqavoids scatter-gather scans: When an offline user reconnects holdinglast_inbox_sync_seq = 1040, a single-shard queryWHERE user_id = :u AND inbox_sync_seq > 1040returns only the conversations updated while they were offline—never querying unrelated message shards!3. Connection Location Directory (ephemeral, partitioned by
hash(user_id)): - Mapsuser_id -> Set[(gateway_id, socket_id, expires_at)]in Redis with a45 sTTL refreshed every15 sby WebSocket heartbeats. If a gateway crashes or Redis restarts, zero authoritative data is lost: browsers reconnect, re-register their socket, and replay missed messages frominbox_sync_seqandseq.Entity Ownership & Invariants: [Conversation Shard: key = conversation_id] <-- Single source of truth for: - Participant membership (user_low, user_high) - Dense monotonic seq = 1, 2, 3... (no gaps, no duplicates) - (sender_id, client_msg_id) -> seq idempotency [User Inbox Shard: key = user_id] <-- Derived index (~50ms async lag) - Discovery of all user's conversations monotonically advancing via - Reconnect delta via inbox_sync_seq GREATEST(latest_conv_seq, event.seq) [Connection Directory: key = user_id] <-- Replaceable routing hint only - Active gateway_id(s) holding WebSockets (never trusted for durability)Define client messaging APIs, WebSocket protocol, and replica-lag contracts
Web clients keep one persistent WebSocket open for bidirectional frames and can also invoke HTTPS endpoints through the API Gateway.
1. Send Message (
POST /v1/conversations/{conv_id}/messagesor WSsend_msg): - Inputs:conv_id(orrecipient_user_idto resolve canonicalconv_id),client_msg_id,body_text(1..4096UTF-8 chars). - Outcomes & guarantees: -200 OK (Committed):{"conv_id": "conv_74", "epoch": 1, "seq": 121, "message_id": "m_01J...", "duplicate": false}— guarantees the message is committed across a multi-AZ quorum and queued for replayable fan-out. -200 OK (Duplicate): Retry of an already-committed(conv_id, sender_id, client_msg_id)returns the originalseq: 121withduplicate: true. -202 Accepted (Pending): If an eager client retry arrives while the first request for the exact sameclient_msg_idis still in flight on the write service, the server coalesces onto the in-flight write (or returnsstatus: "PENDING"), and the browser UI displays the bubble asPendingwithout asequntil200 OKarrives. -400 Bad Request/403 Forbidden(Invalid): Empty/oversized body, or caller is neitheruser_lownoruser_high. -429 Too Many Requests(Throttled): Per-user or per-conversation rate limit exceeded (Retry-After). -503 / Network Timeout(Uncertain): Commit outcome is unknown to the browser; client must retry with the identicalclient_msg_iduntil resolved.2. List Conversations & Reconnect Sync (
GET /v1/me/conversations): - Initial conversation list:?before_sync_seq=999999&limit=50-> ordered slice of{conv_id, peer_user_id, latest_conv_seq, last_acked_conv_seq, preview_text, inbox_sync_seq}+next_cursor. - Offline reconnect delta:?since_inbox_sync_seq=2040-> returns every conversation changed since2040, pluscurrent_inbox_sync_seq: 2052. - Race-free reconnect handshake: On reconnect, the browser (1) opens and registers its WebSocket first (buffering incoming live push frames in memory), (2) queriessince_inbox_sync_seq+ per-conversationafter_seqsecond, and (3) merges buffered live frames with fetched rows by(conv_id, seq)so no message committed mid-reconnect can ever fall between live push and inbox catch-up! - Stale cursor (410 CursorExpired): If a browser was offline beyond compacted sync metadata, returns410telling the client to re-pageGET /v1/me/conversationsfrom the top.3. Read History & Replica-Lag-Aware Gap Repair (
GET /v1/conversations/{conv_id}/messages): - Backward history pagination:?before_seq=120&limit=50&consistency=bounded_replica- Forward catch-up / Online gap repair:?after_seq=121&min_required_seq=123&limit=50- How replica lag is detected and repaired: Every read replica exposes its locally appliedmax_applied_conv_seqwatermark. When a live WebSocket deliversseq = 123to a browser still atseq = 121(revealing missingseq = 122), the browser sendsmin_required_seq = 123. If the chosen replica reportsmax_applied_conv_seq < 123, the read service detects the lag instantly and transparently routes that read to the authoritative leader shard!High-level single-region architecture and authority boundaries
Here is how the write path, durable event backbone, live push router, and separated read paths fit together:
Sender Browser Recipient Browser | ^ | 1. WS / HTTPS Send | 6. WS Push (seq=42) v (client_msg_id) | (< 1s p95) +-------+---------------+ +-------+---------------+ | WebSocket / API GW | | WebSocket Gateway | | (Auth, Rate Limit) | | (600 stateful nodes) | +-------+---------------+ +-------+---------------+ | ^ | 2. Route by conv_id 5. gRPC push to | 4b. Register 1st v gateway_id | + Heartbeat +-------+---------------+ +-----------------------+ | | Chat Write Service | | Delivery Router |-----------+ +-------+---------------+ | (Kafka Consumer Grp 1)|------>+-------------------+ | +-----------+-----------+ | Connection Dir | | 3. Atomic Tx: ^ | (Redis Cluster, | | seq++ + msg + | | ephemeral 45s) | | idempotency + outbox | +-------------------+ v | +-------+--------------------+ 4a. Outbox|CDC +-------------------------------+ | Message Store (Leader) |=======>======+======>| Durable Event Log (Kafka) | | Sharded by conversation_id | (key = conv_id) | Partitioned by conv_id, 7d | | (3-AZ Synchronous Quorum) | +---------------+---------------+ +-------+--------------------+ | | async replication (< 1s) | Consumer Grp 2 v v +-------+--------------------+ +-------------------+ +-------+---------------+ | Bounded-Lag Read Replicas |<-----| History & Sync |-->| User Inbox Store | | (Serves history pages & | | Read Service | | Sharded by user_id | | offline bulk catch-up) | | (Tiered Shedding) | | (user_inbox + sync_seq| +----------------------------+ +---------+---------+ +-----------------------+ ^ | | Fallback to Leader if v | replica_seq < min_required_seq [Purpose-Specific Redis Caches: Conv Auth, Tail-50 Msgs, Top-50 Inbox]End-to-end write & delivery trace: 1. Maya sends
"Ship at 4pm?"(client_msg_id = "k_81").Chat Write Serviceverifies cached participant membership (Maya, Liam) and opens a single-shard transaction onconv_74's leader. 2. Inside one 3-AZ quorum commit (~15–25 ms), the shard checks"k_81"is unseen, incrementsconversations.last_seq(120 -> 121), inserts(conv_74, seq=121)intomessages, writes"k_81" -> 121intomessage_idempotency, and writes anoutboxrow. Maya receives200 OK (seq=121)well under300 ms. 3. A local Transactional Outbox / Change-Data-Capture (CDC) relay (streaming committed changes straight from the database's Write-Ahead Log [WAL] — the append-only disk log of committed transactions) publishesMessageCommitted(conv_74, seq=121)to Kafka keyed byconv_id. 4.Delivery Routerconsumes the Kafka record in~20–50 ms, looks upLiam(plusMaya's other open browser tabs!) inConnection Directory, and pushesseq=121over persistent gRPC streams to their WebSocket Gateways (<< 1,000 ms). 5. Independently,Inbox Indexerconsumes the same Kafka topic and advancesMayaandLiam's rows inuser_inbox.Deep dive: Durable sequence generation and dual-sharded inbox updates
Why not order messages by timestamps, and why not update
messagesplus both users'user_inboxrows inside one distributed multi-shard transaction?1. Dense per-conversation
seqvs. timestamps: Server clocks drift (5–50 msNTP skew), so sorting bycreated_atflips rapid back-and-forth replies and makes it impossible for a browser seeing10:00:01.002and10:00:01.050to tell whether a message at.025was dropped! With contiguous integersseq = 121, 122, 123, receivingseq = 123right afterseq = 121proves mathematically thatseq = 122is missing and triggers immediate gap repair.2. Avoiding cross-shard Two-Phase Commit (2PC): Two-Phase Commit (2PC) (a coordination protocol that locks multiple database shards simultaneously so all commit or all abort) across
conversation_id+Maya's shard +Liam's shard at348,000 peak writes/swould triple lock contention and blow pastp95 < 300 mswhenever any shard hiccups. Instead: - Onlyconversation_id's shard commits synchronously (messages+outbox). -MayaandLiam'suser_inboxshards update asynchronously via Kafka (p95 ~ 50 ms) using an idempotent monotonic upsert so out-of-order retries never move an inbox backward:INSERT INTO user_inbox (user_id, conversation_id, peer_user_id, latest_conv_seq, preview_text, inbox_sync_seq) VALUES (:uid, :cid, :peer, :seq, :preview, next_user_sync_seq(:uid)) ON CONFLICT (user_id, conversation_id) DO UPDATE SET latest_conv_seq = GREATEST(user_inbox.latest_conv_seq, EXCLUDED.latest_conv_seq), preview_text = CASE WHEN EXCLUDED.latest_conv_seq > user_inbox.latest_conv_seq THEN EXCLUDED.preview_text ELSE user_inbox.preview_text END, inbox_sync_seq = CASE WHEN EXCLUDED.latest_conv_seq > user_inbox.latest_conv_seq THEN next_user_sync_seq(:uid) ELSE user_inbox.inbox_sync_seq END;Deep dive: Replayable event bus — Kafka vs. Redis Streams vs. Redis Pub/Sub
Once
seq = 42commits in the database, the event path must route live messages in< 1 sand guaranteeuser_inboxand recovering consumers never drop an update. Let's compare the three options directly:Property Kafka (Chosen Backbone) Redis Streams Redis Pub/Sub --------------------------------------------------------------------------------------------------- Durability Disk-backed log replicated In-memory; async primary-> Zero persistence across >= 3 brokers replica failover can drop (fire-and-forget in (acks=all, min.isr=2) acknowledged entries RAM only) Ordering Strict per-partition order Strict per-stream key Best-effort per (keyed by conv_id) order channel while up Replay & Retention Cheap multi-day (7d = 35TB Expensive DRAM ceiling! Impossible: missed sequential NVMe/tiered S3) 24h at 5TB/day = >5TB RAM events vanish Consumer Groups Native partition leases & Native XREADGROUP + None (broadcast to committed offsets XPENDING / XCLAIM currently live subs) Typical End-to-End ~15 - 50 ms ~2 - 10 ms < 1 - 2 ms LatencyHow Kafka satisfies both low latency and deterministic recovery: - Partitioning:
partition = murmur2(conversation_id) % 4096. Every event forconv_idlands in one partition in exactseqorder. - Producer retries: Outbox relays publish withacks=allandenable.idempotence=true(brokers deduplicate network retries via producer sequence numbers); even if a relay restarts and re-publishesseq = 42, browserseqtracking anduser_inbox'sGREATEST(...)treat duplicates as harmless no-ops. - Bounded consumer latency & replay: Withlinger.ms = 5, Kafka adds only~20–40 ms(< 5%of our1,000 msdelivery budget) while keeping 7 days of replayable history on cheap SSDs. If anInbox Indexershard goes down for 30 minutes, rewinding its consumer-group offset replays every missed inbox update without scanning the 1.8 PB message store. - Where Redis Pub/Sub and Redis Streams fall short: Redis Pub/Sub loses events whenever a subscriber restarts or disconnects—unacceptable as the primary bridge touser_inbox. Redis Streams adds consumer groups (XREADGROUP), but retaining even 24–48 hours of5 TB/dayin DRAM is prohibitively expensive and still risks losing recently acknowledged entries during an asynchronous Redis primary failover. (FromDelivery Routerto the 600 statefulWebSocket Gateways, direct persistent gRPC streams already deliver in~1–2 mswithout needing an extra Redis Pub/Sub hop.)Deep dive: Replica-aware reads, online gap repair, and cache safety
Routing all reads to leaders wastes primary write capacity, while routing all reads to asynchronous replicas hides brand-new messages during gap repair. We match read freshness to the client's causal watermark and keep caches strictly subordinate to the database.
1. Authoritative vs. Bounded-Lag Replica Read Routing: - Historical scrollback (
before_seq = 200): Messages150..199are immutable once written; a bounded-lag replica (lag< 1–2 s) serves them with 100% accuracy. - Offline reconnect catch-up: When Liam reconnects and readslatest_conv_seq = 121fromuser_inbox, his client asks forafter_seq = 105, min_required_seq = 121. Any replica withmax_applied_conv_seq >= 121serves it; only if the replica trails121does the read router fall back to the leader. - Online gap repair (authoritative fresh path): When Liam's live WebSocket receivesseq = 123right afterseq = 121,seq = 122committed milliseconds ago—so an async replica is very likely still at121! Passingafter_seq = 121, min_required_seq = 123(reason = GAP_REPAIR) forces the read service to checkreplica.max_applied_conv_seq >= 123(or route directly to the leader shard), healing the missing message in< 50 ms.2. Purpose-specific caches (and why none can become a stale source of truth):
Cache Exact Load Removed Guard Against Becoming Truth ----------------------------------------------------------------------------------------------------- 1. Conv Auth Cache Eliminates 99.9% of DB membership 1:1 participants (user_low, conv_id -> (uA, uB, home) reads on Send & Read (~500k QPS) user_high) never change! 2. Conv Tail-50 Cache Serves tab refreshes & brief Stores {max_seq, msgs[last 50]}; conv_id -> [last 50 msgs] reconnects without hitting DB disks Lua update applies ONLY if new_seq == max_seq + 1; bypassed whenever max_seq < min_required_seq! 3. User Top-50 Inbox Cache Absorbs app-open conversation list Stamped with inbox_sync_seq; any user_id -> [top 50 convs] queries during reconnect waves cursor mismatch reloads from DB.Deep dive: Burst load shedding, hot conversations, and gateway recovery
During sudden traffic spikes (
580,000 writes/sor massive reconnect storms), we protect durable sends (Tier 0) by degrading cold reads explicitly:1. Tiered burst degradation ladder: - Resource isolation:
Chat Write ServiceandHistory Read Serviceuse separate compute pools and separate storage IOPS budgets (70%reserved for leader commits + online gap repair,30%capped for historical pagination). - Stage 1 (Moderate burst): Shrink initial history page sizes (50 -> 20), disable speculative scrollback prefetching, and blockbefore_seqpagination from falling back to leader shards. - Stage 2 (Severe burst — write p95 > 200 ms): Shed older history pagination (before_seq) with503 Retry-After: 5(error_code: "HISTORY_DEGRADED"), so active live chats keep committing and delivering smoothly while older scrollback pauses gracefully. Meanwhile, Kafka buffersInbox Indexerspikes safely on disk.2. Hot conversations & gateway crash recovery: - Hot conversations: Because every conversation has at most 2 participants, delivery fan-out is bounded (~2–4 open browser tabs), never
100,000xlike celebrity channels. Abusive bots flooding one 1-on-1 conversation hit a per-conversation token bucket at the API Gateway (10 msgs/ssustained,25burst). - Gateway crash: Losing 1 of 600 WebSocket Gateways drops50,000sockets. Clients reconnect with randomized jitter (0..10 s— spreading retry times randomly so 50,000 browsers don't slam auth servers on the same millisecond) and run the race-free reconnect flow (register socket -> since_inbox_sync_seq -> after_seq).Deep dive: Cross-region conversations, link partitions, and failover
Now suppose Maya connects via
us-eastand Liam connects viaeu-west(~80 msone-way /~160 msround-trip inter-region fiber latency). How do we preserve one conversation order, idempotency, explicit read freshness, and clear regional failure guarantees?[Maya Browser] ---> [us-east Gateway] ---> [us-east Home Leader Shard (conv_74, epoch=1)] (us-east) | 1. Sync 3-AZ quorum commit in us-east (~20ms) | 2. Outbox -> us-east Kafka +--------------------+ | mTLS WAN Backbone | Async Cross-Region WAL | (~80ms one-way) | Standby Stream (lag ~1s) v v [Liam Browser] <--- [eu-west Gateway] <--- [eu-west Router & [eu-west Standby Replica (eu-west) (WS push ~160ms) Liam's Inbox Shard] of conv_74 + watermark]1. Single
home_regionauthority, latency budget, and database growth: - Routing & placement: Eachconversation_idhas one active(home_region, epoch)stored in a small globally replicatedconversation_routingtable (defaulting to the creator's region and cached everywhere). Each user'suser_inboxshard lives in that user's own region (Mayainus-east,Liamineu-west). - Cross-region latency budget: When Liam (eu-west) sends toconv_74(home_region = us-east),eu-westforwards the write over a warm mTLS (mutually authenticated encrypted) WAN channel (+80 ms),us-eastcommits across its 3 local AZs synchronously (~20 ms), and replies (+80 ms) ->~180–210 mstotal, comfortably meetingp95 < 300 ms! Live push fromus-eastKafka across the WAN toeu-westreaches Liam's browser in~150–250 ms(<< 1,000 ms). - Database growth:user_inboxis never duplicated across regions (each user lives in one home region).messages(1.825 PB/yearlogical) maintains one asynchronous disaster-recovery standby replica in a paired region (~3.65 PB/yearlogical across both regions, streaming5 TB/day / 86,400 s ~= 58 MB/sof compressed WAL over the WAN).2. Replication policy, link partitions, and full regional loss: Here RPO (Recovery Point Objective) is the maximum age of committed data that could be lost in a disaster, and RTO (Recovery Time Objective) is how long failover takes to restore writes. - Acknowledgement policy: Synchronous 3-AZ quorum inside
home_region(RPO = 0for any process or single-AZ failure) + asynchronous cross-region WAL replication (lag ~ 0.5–1.5 s) toeu-west. (Synchronous multi-region quorum would give cross-continentRPO = 0, but adds+160 msWAN RTT to every same-region chat message.) - Inter-region link cut (us-east<->eu-westpartitioned, both regions healthy): - Pause remote writes rather than split-brain:eu-westmust NOT promote itself whileus-eaststill holds theepoch = 1lease! Allowing both regions to accept writes would assign conflictingseq = 122messages and break single conversation order. Instead, Liam's sends tous-east-owned conversations pause cleanly with503 RegionLinkUnavailable(Liam's browser holds themPendingwith theirclient_msg_idand retries automatically when the link heals), whileeu-west-owned conversations keep running at full speed. - Explicit read freshness: Liam can still readconv_74fromeu-west's local standby replica, stamped withread_freshness: { is_stale: true, max_applied_seq: 121, replicated_as_of_ms }so the UI clearly indicates cross-region sync is paused. - Fullhome_regiondisaster (us-eastcompletely lost): - After consensus lease expiry (RTO ~ 60–120 s), the global routing store atomically advancesconv_74to(home_region = eu-west, epoch = 2)(epoch = 2permanently fencesus-eastif it ever comes back online). - Survival & contiguous sequence continuity: Every message replicated before the outage survives; at most the final~0.5–1.5 sof un-replicated commits in deadus-eastcan be lost (RPO <= 2 s). Becauseepoch = 2fencesepoch = 1,eu-westresumes cleanly atseq = max_replicated_seq + 1(tagging messages with(epoch = 2, seq)), preserving gap-free integer sequence numbers (121, 122, 123...) without breaking client gap detection!
Intuition & how it works
Picture a 1-on-1 chat service for 100 million daily users as a numbered dual-ledger mailroom. Every pair of users shares one master conversation ledger (sharded by conversation_id) whose clerk stamps each accepted message with the next dense integer seq = 1, 2, 3, ... and checks an idempotency key (client_msg_id — a unique token created by the sender's browser before sending so network retries return the existing stamp instead of duplicating the message). Because nobody wants to scan billions of ledgers just to find out who messaged them while they were asleep, each user also has a personal inbox index card (sharded by user_id) listing only their own conversations alongside a personal change counter (inbox_sync_seq). Connecting the two is a durable replayable event log (Apache Kafka fed by a transactional outbox — writing the message and a pending publish record inside the same database commit) that simultaneously notifies an ephemeral connection directory (a short-TTL lookup table mapping online users to whichever WebSocket gateway holds their open browser tab) and updates both personal inbox cards.
Why do simpler designs fail at 116,000 average (~348,000 peak) writes per second? Storing messages only by conversation_id forces an expensive scatter-gather query across hundreds of shards every time a user opens the app to list their conversations. Ordering messages by wall-clock timestamps lets slight server clock skew scramble rapid replies and hides dropped packets from online browsers. And publishing directly to fire-and-forget Redis Pub/Sub right after the database commit silently loses both live deliveries and inbox updates whenever a router restarts—leaving an offline user's conversation list permanently missing active threads!
Let's trace a concrete 5-step sequence between Maya and Liam in conv_74 (currently at seq = 120):
1. Durable Send (t = 0 ms):
Maya sends "Ship at 4pm?" with client_msg_id="k_81".
conv_74's leader shard commits (epoch=1, seq=121, idempotency "k_81"->121, outbox row)
across a 3-AZ quorum (2-of-3 data centers) in 18 ms -> Maya gets 200 OK (seq=121).
2. Replayable Fan-Out (t = 35 ms):
Outbox Relay publishes (conv_74, seq=121) to Kafka partition hash(conv_74).
- Consumer Group 1 (Delivery Router) looks up Liam in Connection Directory
-> pushes seq=121 to Gateway-19 -> Liam's browser renders seq=121 at t = 55 ms.
- Consumer Group 2 (Inbox Indexer) advances Maya's and Liam's user_inbox rows
to latest_conv_seq = 121 and bumps each user's inbox_sync_seq.
3. Socket Blip & Instant Gap Detection (t = 500 ms):
Maya sends seq=122 ("Check PR #8") and seq=123 ("Merged!").
A brief packet drop loses push frame seq=122, so Liam's browser receives seq=123
while holding last_seen_seq = 121 -> dense integers immediately reveal missing 122!
4. Replica-Aware Gap Repair (t = 520 ms):
Liam's client calls GET /conversations/conv_74/messages?after_seq=121&min_required_seq=123.
Read replica is still at max_applied_seq = 121 (< 123!), so Read Service bypasses
the lagging replica and reads seq=122 straight from conv_74's authoritative leader.
5. Race-Free Offline Recovery (hours later):
Maya opens her laptop, registers her WebSocket FIRST (buffering live pushes),
then queries her single user_id inbox shard (inbox_sync_seq > 2040) to fetch only
changed conversations and deduplicates by (conv_id, seq).
Key trade-offs
- Single-Shard Message Commit + Async Kafka Inbox Update vs. Cross-Shard Distributed Transactions: Committing synchronously only on
conversation_id's shard and updatingMayaandLiam'suser_idinbox shards asynchronously via Kafka (~50 ms lag) avoids Two-Phase Commit (2PC) (locking multiple shards together per write)—keeping send latency well below300 msat348,000+peak writes/s and preventing one slow inbox shard from stalling unrelated conversations. - Kafka Durable Event Backbone vs. Redis Pub/Sub or Redis Streams: Kafka adds ~15–40 ms of disk-replicated broker latency compared to sub-millisecond Redis Pub/Sub, yet easily meets our
1,000 msdelivery target while providing cheap 7-day SSD retention (35 TB) andacks=alldurability that neither zero-persistence Redis Pub/Sub nor RAM-bound, asynchronously replicated Redis Streams can match economically at5 TB/day. - Bounded-Lag Replicas for History + Leader Fallback for Gap Repair vs. Leader-Only Reads: Serving scrollback pagination and bulk offline catch-up from read replicas offloads >85% of read IOPS from write leaders, while checking
replica.max_applied_conv_seq >= min_required_seqguarantees authoritative leader freshness whenever an online browser repairs a millisecond-old gap. - Tiered Burst Shedding (Degrade History Before Sends) vs. Uniform Throttling: Rejecting 30% of all traffic uniformly during a flash spike breaks live sends and triggers retry storms; isolating compute and storage IOPS pools so cold historical pagination sheds (
503 HISTORY_DEGRADED) first preserves 100% of durable sends and live delivery. - Single Home-Region Ownership per Conversation vs. Active-Active Multi-Region Conversation Writes: Routing cross-region messages to the conversation's
home_regionadds ~160 ms of round-trip WAN latency for the remote participant (still< 300 msp95) and pauses remote sends if the inter-region link breaks, in exchange for preserving one conflict-free contiguousseqorder without split-brain sequence collisions.
Common mistakes
- Sharding messages only by
conversation_idwith nouser_id-partitioned inbox index: Listing a user's conversations or catching up after being offline then requires querying every message shard in the database—anO(num_shards)scatter-gather bottleneck at 100M DAU. - Querying offline catch-up before registering the new WebSocket on reconnect: Any message routed during the gap between reading
user_inboxand registering inConnection Directorymisses both the query and the socket push; always register the socket first, buffer live pushes, then fetch the cursor delta. - Using timestamps (
created_at) or uncoordinated Snowflake IDs as the conversation order: Clock skew flips rapid message order, and non-contiguous IDs make it impossible for browsers to tell whether a message was dropped between two received frames. - Serving online gap-repair queries blindly from an asynchronous read replica: When a fast WebSocket push delivers
seq = 43ahead of a replica still atseq = 41, reading missingseq = 42from that lagging replica returns empty and tricks a naive client into permanently skippingseq = 42. - Allowing both regions to assign
seqnumbers during an inter-region partition—or jumpingseq + 1000on failover: Dual writers create conflictingseq = 43messages, while artificial sequence gaps (42 -> 1042) trick client gap detection into requesting 999 nonexistent messages. Fencing old owners via monotonicepochlets the promoted region continue seamlessly atmax_replicated_seq + 1.
Follow-up questions
- How does your delivery layer keep multiple open browser tabs across two laptops synchronized when the same user sends a message from one tab? Each open browser tab registers its own
(gateway_id, socket_id)entry insideConnection Directory's active set forMaya. WheneverDelivery Routerconsumes a newly committedMessageCommittedevent forconv_74, it fans that push frame out to both participants' full socket sets—including all ofMaya's other open tabs—so every tab rendersseq = 121in real time without polling. - How do you stop two peers who message each other for the very first time at the exact same millisecond from initializing two separate threads? Compute
conversation_iddeterministically from the canonical sorted pair(min(user_a, user_b), max(user_a, user_b))rather than assigning a random UUID per request. Both simultaneous initial writes hash to the exact same conversation shard, where an atomicINSERT ... ON CONFLICT (conversation_id) DO NOTHINGcreates a single shared thread and sequences one message asseq = 1and the other asseq = 2. - How would you store nearly two petabytes of annual chat text economically while still serving backward history pages in tens of milliseconds? Store messages in a sharded Log-Structured Merge-tree (LSM-tree) engine (an append-oriented storage structure that merges sorted on-disk files in the background) keyed by
(conversation_id, seq). Keep the newest 30 days on fast NVMe SSDs backed by a Redis tail-50 message cache (absorbing >98% of active reads), and compact months 2 through 12+ into Zstandard-compressed cold tiers (~3xcompression) that still answer indexed(conversation_id, seq)range queries in< 80 ms.
Follow-up questions
- How does your delivery layer keep multiple open browser tabs across two laptops synchronized when the same user sends a message from one tab?
- How do you stop two peers who message each other for the very first time at the exact same millisecond from initializing two separate threads?
- How would you store nearly two petabytes of annual chat text economically while still serving backward history pages in tens of milliseconds?
More Anthropic interview questions
- In-Memory Key-Field Store with Expiring Entries and Snapshots Medium
- Inferring Call-Trace Events from Sampled Stacks Hard
- Anthropic Recruiter Screen: Lab Motivation, Safety Taxonomy, and Misuse Risks Medium Pro
- Time-Versioned Key-Field Store Hard Pro
- Collaborative Prompt Studio and Model Execution Service Medium Pro
- Anthropic Values Alignment, Integrity Under Friction, and Policy Critique Medium Pro
- Single-GPU and All-GPU Batch Scheduling for Model Inference Hard Pro
- Fleet-Wide Model Artifact Rollout System Hard Pro
- Same-Host Sequential and Concurrent Web Crawler Medium Pro
- Motivation for Anthropic and Perspective on AI Safety Hard Pro