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 least 1 year of 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 second without 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

  1. 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 integer seq = 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 repair
    
  2. Back-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)).
    
  3. 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 (monotonic BIGINT starting at 0), home_region, epoch (monotonic ownership generation 1, 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 same conversation_id shard!): - 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 message seq indexed for that conversation), last_acked_conv_seq (durable client cursor), preview_text, updated_at, and inbox_sync_seq (a per-user monotonic integer incremented whenever any conversation of user_id advances). - Why inbox_sync_seq avoids scatter-gather scans: When an offline user reconnects holding last_inbox_sync_seq = 1040, a single-shard query WHERE user_id = :u AND inbox_sync_seq > 1040 returns only the conversations updated while they were offline—never querying unrelated message shards!

    3. Connection Location Directory (ephemeral, partitioned by hash(user_id)): - Maps user_id -> Set[(gateway_id, socket_id, expires_at)] in Redis with a 45 s TTL refreshed every 15 s by WebSocket heartbeats. If a gateway crashes or Redis restarts, zero authoritative data is lost: browsers reconnect, re-register their socket, and replay missed messages from inbox_sync_seq and seq.

    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)
    
  4. 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}/messages or WS send_msg): - Inputs: conv_id (or recipient_user_id to resolve canonical conv_id), client_msg_id, body_text (1..4096 UTF-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 original seq: 121 with duplicate: true. - 202 Accepted (Pending): If an eager client retry arrives while the first request for the exact same client_msg_id is still in flight on the write service, the server coalesces onto the in-flight write (or returns status: "PENDING"), and the browser UI displays the bubble as Pending without a seq until 200 OK arrives. - 400 Bad Request / 403 Forbidden (Invalid): Empty/oversized body, or caller is neither user_low nor user_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 identical client_msg_id until 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 since 2040, plus current_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) queries since_inbox_sync_seq + per-conversation after_seq second, 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, returns 410 telling the client to re-page GET /v1/me/conversations from 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 applied max_applied_conv_seq watermark. When a live WebSocket delivers seq = 123 to a browser still at seq = 121 (revealing missing seq = 122), the browser sends min_required_seq = 123. If the chosen replica reports max_applied_conv_seq < 123, the read service detects the lag instantly and transparently routes that read to the authoritative leader shard!

  5. 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 Service verifies cached participant membership (Maya, Liam) and opens a single-shard transaction on conv_74's leader. 2. Inside one 3-AZ quorum commit (~15–25 ms), the shard checks "k_81" is unseen, increments conversations.last_seq (120 -> 121), inserts (conv_74, seq=121) into messages, writes "k_81" -> 121 into message_idempotency, and writes an outbox row. Maya receives 200 OK (seq=121) well under 300 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) publishes MessageCommitted(conv_74, seq=121) to Kafka keyed by conv_id. 4. Delivery Router consumes the Kafka record in ~20–50 ms, looks up Liam (plus Maya's other open browser tabs!) in Connection Directory, and pushes seq=121 over persistent gRPC streams to their WebSocket Gateways (<< 1,000 ms). 5. Independently, Inbox Indexer consumes the same Kafka topic and advances Maya and Liam's rows in user_inbox.

  6. Deep dive: Durable sequence generation and dual-sharded inbox updates

    Why not order messages by timestamps, and why not update messages plus both users' user_inbox rows inside one distributed multi-shard transaction?

    1. Dense per-conversation seq vs. timestamps: Server clocks drift (5–50 ms NTP skew), so sorting by created_at flips rapid back-and-forth replies and makes it impossible for a browser seeing 10:00:01.002 and 10:00:01.050 to tell whether a message at .025 was dropped! With contiguous integers seq = 121, 122, 123, receiving seq = 123 right after seq = 121 proves mathematically that seq = 122 is 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 at 348,000 peak writes/s would triple lock contention and blow past p95 < 300 ms whenever any shard hiccups. Instead: - Only conversation_id's shard commits synchronously (messages + outbox). - Maya and Liam's user_inbox shards 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;
    
  7. Deep dive: Replayable event bus — Kafka vs. Redis Streams vs. Redis Pub/Sub

    Once seq = 42 commits in the database, the event path must route live messages in < 1 s and guarantee user_inbox and 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
    Latency
    

    How Kafka satisfies both low latency and deterministic recovery: - Partitioning: partition = murmur2(conversation_id) % 4096. Every event for conv_id lands in one partition in exact seq order. - Producer retries: Outbox relays publish with acks=all and enable.idempotence=true (brokers deduplicate network retries via producer sequence numbers); even if a relay restarts and re-publishes seq = 42, browser seq tracking and user_inbox's GREATEST(...) treat duplicates as harmless no-ops. - Bounded consumer latency & replay: With linger.ms = 5, Kafka adds only ~20–40 ms (< 5% of our 1,000 ms delivery budget) while keeping 7 days of replayable history on cheap SSDs. If an Inbox Indexer shard 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 to user_inbox. Redis Streams adds consumer groups (XREADGROUP), but retaining even 24–48 hours of 5 TB/day in DRAM is prohibitively expensive and still risks losing recently acknowledged entries during an asynchronous Redis primary failover. (From Delivery Router to the 600 stateful WebSocket Gateways, direct persistent gRPC streams already deliver in ~1–2 ms without needing an extra Redis Pub/Sub hop.)

  8. 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): Messages 150..199 are immutable once written; a bounded-lag replica (lag < 1–2 s) serves them with 100% accuracy. - Offline reconnect catch-up: When Liam reconnects and reads latest_conv_seq = 121 from user_inbox, his client asks for after_seq = 105, min_required_seq = 121. Any replica with max_applied_conv_seq >= 121 serves it; only if the replica trails 121 does the read router fall back to the leader. - Online gap repair (authoritative fresh path): When Liam's live WebSocket receives seq = 123 right after seq = 121, seq = 122 committed milliseconds ago—so an async replica is very likely still at 121! Passing after_seq = 121, min_required_seq = 123 (reason = GAP_REPAIR) forces the read service to check replica.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.
    
  9. Deep dive: Burst load shedding, hot conversations, and gateway recovery

    During sudden traffic spikes (580,000 writes/s or massive reconnect storms), we protect durable sends (Tier 0) by degrading cold reads explicitly:

    1. Tiered burst degradation ladder: - Resource isolation: Chat Write Service and History Read Service use 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 block before_seq pagination from falling back to leader shards. - Stage 2 (Severe burst — write p95 > 200 ms): Shed older history pagination (before_seq) with 503 Retry-After: 5 (error_code: "HISTORY_DEGRADED"), so active live chats keep committing and delivering smoothly while older scrollback pauses gracefully. Meanwhile, Kafka buffers Inbox Indexer spikes 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,000x like celebrity channels. Abusive bots flooding one 1-on-1 conversation hit a per-conversation token bucket at the API Gateway (10 msgs/s sustained, 25 burst). - Gateway crash: Losing 1 of 600 WebSocket Gateways drops 50,000 sockets. 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).

  10. Deep dive: Cross-region conversations, link partitions, and failover

    Now suppose Maya connects via us-east and Liam connects via eu-west (~80 ms one-way / ~160 ms round-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_region authority, latency budget, and database growth: - Routing & placement: Each conversation_id has one active (home_region, epoch) stored in a small globally replicated conversation_routing table (defaulting to the creator's region and cached everywhere). Each user's user_inbox shard lives in that user's own region (Maya in us-east, Liam in eu-west). - Cross-region latency budget: When Liam (eu-west) sends to conv_74 (home_region = us-east), eu-west forwards the write over a warm mTLS (mutually authenticated encrypted) WAN channel (+80 ms), us-east commits across its 3 local AZs synchronously (~20 ms), and replies (+80 ms) -> ~180–210 ms total, comfortably meeting p95 < 300 ms! Live push from us-east Kafka across the WAN to eu-west reaches Liam's browser in ~150–250 ms (<< 1,000 ms). - Database growth: user_inbox is never duplicated across regions (each user lives in one home region). messages (1.825 PB/year logical) maintains one asynchronous disaster-recovery standby replica in a paired region (~3.65 PB/year logical across both regions, streaming 5 TB/day / 86,400 s ~= 58 MB/s of 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 = 0 for any process or single-AZ failure) + asynchronous cross-region WAL replication (lag ~ 0.5–1.5 s) to eu-west. (Synchronous multi-region quorum would give cross-continent RPO = 0, but adds +160 ms WAN RTT to every same-region chat message.) - Inter-region link cut (us-east <-> eu-west partitioned, both regions healthy): - Pause remote writes rather than split-brain: eu-west must NOT promote itself while us-east still holds the epoch = 1 lease! Allowing both regions to accept writes would assign conflicting seq = 122 messages and break single conversation order. Instead, Liam's sends to us-east-owned conversations pause cleanly with 503 RegionLinkUnavailable (Liam's browser holds them Pending with their client_msg_id and retries automatically when the link heals), while eu-west-owned conversations keep running at full speed. - Explicit read freshness: Liam can still read conv_74 from eu-west's local standby replica, stamped with read_freshness: { is_stale: true, max_applied_seq: 121, replicated_as_of_ms } so the UI clearly indicates cross-region sync is paused. - Full home_region disaster (us-east completely lost): - After consensus lease expiry (RTO ~ 60–120 s), the global routing store atomically advances conv_74 to (home_region = eu-west, epoch = 2) (epoch = 2 permanently fences us-east if it ever comes back online). - Survival & contiguous sequence continuity: Every message replicated before the outage survives; at most the final ~0.5–1.5 s of un-replicated commits in dead us-east can be lost (RPO <= 2 s). Because epoch = 2 fences epoch = 1, eu-west resumes cleanly at seq = 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 updating Maya and Liam's user_id inbox shards asynchronously via Kafka (~50 ms lag) avoids Two-Phase Commit (2PC) (locking multiple shards together per write)—keeping send latency well below 300 ms at 348,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 ms delivery target while providing cheap 7-day SSD retention (35 TB) and acks=all durability that neither zero-persistence Redis Pub/Sub nor RAM-bound, asynchronously replicated Redis Streams can match economically at 5 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_seq guarantees 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_region adds ~160 ms of round-trip WAN latency for the remote participant (still < 300 ms p95) and pauses remote sends if the inter-region link breaks, in exchange for preserving one conflict-free contiguous seq order without split-brain sequence collisions.

Common mistakes

  • Sharding messages only by conversation_id with no user_id-partitioned inbox index: Listing a user's conversations or catching up after being offline then requires querying every message shard in the database—an O(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_inbox and registering in Connection Directory misses 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 = 43 ahead of a replica still at seq = 41, reading missing seq = 42 from that lagging replica returns empty and tricks a naive client into permanently skipping seq = 42.
  • Allowing both regions to assign seq numbers during an inter-region partition—or jumping seq + 1000 on failover: Dual writers create conflicting seq = 43 messages, while artificial sequence gaps (42 -> 1042) trick client gap detection into requesting 999 nonexistent messages. Fencing old owners via monotonic epoch lets the promoted region continue seamlessly at max_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 inside Connection Directory's active set for Maya. Whenever Delivery Router consumes a newly committed MessageCommitted event for conv_74, it fans that push frame out to both participants' full socket sets—including all of Maya's other open tabs—so every tab renders seq = 121 in 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_id deterministically 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 atomic INSERT ... ON CONFLICT (conversation_id) DO NOTHING creates a single shared thread and sequences one message as seq = 1 and the other as seq = 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 (~3x compression) that still answer indexed (conversation_id, seq) range queries in < 80 ms.

Follow-up questions

More Anthropic interview questions

All 254 Anthropic questions →