Real-Time Multi-Server Channel Chat Service

Easy · System Design · Software Engineer · Technical Screen

Prompt

Architect the backend for a real-time chat platform organized around multi-channel community workspaces ("servers") alongside one-on-one and small-group direct conversations. Connected participants should see new posts appear almost instantaneously, while members joining a channel or returning from an offline period must be able to load complete, strictly ordered chat history.

Core Capabilities

  • Workspaces, Channels, and Direct Chats: A single account can belong to many community servers, read and post inside permitted text channels within each server, and exchange direct messages.
  • Live Delivery: Messages posted to a channel are pushed in real time to online members currently subscribed to that conversation.
  • History & Catch-Up Sync: Opening a channel or reconnecting after a dropped connection lets the client fetch prior pages of messages as well as everything missed while offline.
  • Total Per-Channel Sequence: Every channel defines one unambiguous, gap-free message order shared by live viewers and historical readers alike.

Operational & Scale Constraints

  • Concurrency & Reach: Support millions of simultaneously connected clients distributed worldwide, including mobile devices on high-loss or intermittent cellular connections.
  • Latency & Uptime: Deliver live chat events with low sub-second latency while keeping the messaging plane highly available.
  • Durability First: Once the backend confirms a sent message to its author, that record must survive server crashes and zone failures without disappearing.

Sample Interaction Trace

  1. Maya posts "Deploy finished" to the #releases channel (ch_releases).
  2. The backend authenticates Maya's token, verifies her permission to post in #releases, and commits the sequenced message to durable storage before acknowledging the send.
  3. All connected members watching #releases receive the new message over their live push connections.
  4. Teammate Liam, whose phone was offline in a subway tunnel when "Deploy finished" was sent, regains connectivity minutes later and runs a cursor-based sync to fetch every #releases message committed after his last seen sequence position.

Scope & Expectations

  • Client-Server Protocols: Define the HTTP and persistent push interfaces for posting messages, paginating history, maintaining sessions, and catching up after disconnects.
  • Schema & Partitioning Strategy: Propose storage models for workspace/channel membership metadata and high-volume append-only channel messages.
  • End-to-End Routing & Fan-Out: Show how a sent message moves from permission validation and durable persistence to live subscriber delivery without overwhelming large community servers.
  • Distributed Sequencing & Reconnect Guarantees: Explain how strict per-channel ordering, duplicate suppression on flaky networks, and efficient offline catch-up work together at scale.

Step-by-step walkthrough

  1. Clarify requirements and core guarantees

    Building a basic chat room on one machine is straightforward. Building a multi-server community chat platform for millions of concurrent users is challenging because four core promises pull directly against one another:

    1. Real-time low latency: online members see a new message within a fraction of a second.
    2. Strict per-channel ordering: every live viewer and every historical scroll-back sees the exact same message sequence in a channel, with no silent gaps.
    3. Durability first: once the sender receives a "message sent" confirmation, that message must never vanish—even if a server or an entire availability zone crashes a millisecond later.
    4. Resilient offline sync: mobile and global users on unstable networks drop connections constantly and must catch up cleanly without duplicate or missing messages.

    Functional requirements

    • Servers, channels, and DMs: users can join multiple servers (communities), access permitted text channels inside them, and send 1:1 or small-group direct messages (modeled as server-less channels).
    • Real-time messaging: users send messages and active subscribers of that channel receive them live.
    • Message history and synchronization: clients fetch older pages when scrolling up and fetch missed messages (after their last known position) upon joining or reconnecting.
    • Strict per-channel ordering: every channel defines one authoritative, total message order. (Ordering across two unrelated channels is neither needed nor meaningful.)

    Non-functional requirements and assumptions

    • Scale: 200M registered users, 50M daily active users (DAU), and 10M concurrent online sessions across servers ranging from 5 friends to 500,000 community members (50,000 online at once).
    • Latency: < 300 ms p99 end-to-end delivery within the same continent; < 500 ms across continents.
    • Availability and durability: 99.99% uptime; acknowledged messages are replicated across 3 availability zones before returning HTTP 201.
    • Payload scope: text up to 2,000 characters (~300 B with metadata); images and files upload directly to object storage (S3/GCS) via pre-signed URLs, leaving only attachment keys inside the message record. Edits and deletes modify a message in place without changing its order position. Voice/video and full-text search are out of scope, though search can subscribe to our message event stream.
  2. Back-of-the-envelope numbers

    Let us size writes, live fan-out, persistent connections, and storage step by step:

    1. Traffic & message write rate
       Daily active users (DAU)       = 50,000,000
       Messages sent per DAU / day    = 40  ->  2,000,000,000 (2B) messages/day
       Average write throughput       = 2,000,000,000 / 86,400 s = ~23,150 messages/s
       Peak write throughput (3x)     = ~70,000 messages/s
    
    2. Durable storage growth
       Average stored row size        = ~300 B (text + message_id + seq + author_id + nonce + flags)
       Daily raw volume               = 2B * 300 B = 600 GB/day
       Replicated across 3 zones      = 600 GB * 3 = 1.8 TB/day  ->  ~660 TB/year (~280 TB compressed)
    
    3. Real-time fan-out (push) rate
       Average online viewers/message = 30 (most channels are small; big community channels skew high)
       Outbound client pushes at peak = 70,000 messages/s * 30 = 2,100,000 (2.1M) pushes/s
    
    4. Persistent WebSocket gateway fleet
       Peak concurrent connections    = 10,000,000 (10M) open sockets
       Capacity per gateway server    = 100,000 sockets (~20 KB RAM/socket for TLS + buffers = ~2 GB)
       Minimum gateways needed        = 10M / 100k = 100 -> run 150 across 3 zones (survives 1 zone loss)
       Deliveries per gateway at peak = 2.1M pushes/s / 150 gateways = 14,000 pushes/s
       2-minute session resume buffer = 14,000/s * 120 s * ~500 B = ~840 MB RAM per gateway
    
    5. History reads & reconnect sync
       Channel opens / scroll-backs   = 10M users * 1 fetch / 5 min = ~33,000 range reads/s (50 rows each)
       Reconnect channel-head summary = 15 servers * 30 channels * 16 B (channel_id + last_seq) = ~7.2 KB
    

    What the arithmetic tells us:

    • Writes (70k/s) are moderate, whereas live pushes (2.1M/s) and open sockets (10M) dominate compute. Inside our backend, we must route each message once per interested gateway (at most 150 copies), never once per individual user (up to 50,000 copies).
    • Writing to offline users' inboxes is impossible at large-community scale: one message in a 500,000-member server would trigger 500,000 inbox writes! Active sessions must get pushed events, while disconnected users pull history only for the channels they actually open.
  3. API design: REST for writes/history and WebSockets for live push

    A WebSocket is a long-lived, two-way TCP connection between client and server that stays open so the server can push new events instantly without waiting for the client to poll. We use HTTPS REST for stateless request/response actions (sending messages, loading history) and one WebSocket per client session for receiving live events:

    HTTPS REST API (Authorization: Bearer <session_token>)
    
    1. Send a message (idempotent via client-generated `nonce`)
       POST /v1/channels/{channel_id}/messages
       Body: {"content": "Deploy finished", "nonce": "client-uuid-7c41b9"}
       201 Created -> {
         "channel_id": "ch_releases",
         "seq": 48213,
         "message_id": "117604928174000128",
         "created_at": "2026-11-30T17:20:01.104Z"
       }
       (403 no permission | 429 rate-limited with Retry-After | 503 shard moving, retry with same nonce)
    
    2. Fetch channel history (catch-up forward or scroll-back backward)
       GET /v1/channels/{channel_id}/messages?after_seq=48100&limit=100    -> ascending (48101..48200)
       GET /v1/channels/{channel_id}/messages?before_seq=48213&limit=50    -> descending (48212..48163)
    
    3. Server/DM management & read state
       GET  /v1/users/@me/servers                                          -> joined servers & channels
       POST /v1/users/@me/channels   {"recipient_ids": ["u_42"]}           -> create/open DM channel
       PUT  /v1/channels/{channel_id}/read-state {"last_read_seq": 48213}  -> update unread marker
    
    WebSocket Gateway Protocol (wss://gateway.chat.example/v1, zstd-compressed JSON/msgpack frames)
    
    Server -> Client  HELLO          {"heartbeat_interval_ms": 40000}
    Client -> Server  IDENTIFY       {"token": "..."}                                (fresh login/boot)
    Client -> Server  RESUME         {"token": "...", "session_id": "s_9", "last_event_no": 318}
    Server -> Client  READY          {"session_id": "s_9", "resume_url": "...",
                                      "channels": [{"channel_id": "ch_releases", "last_seq": 48213}],
                                      "read_states": [{"channel_id": "ch_releases", "last_read_seq": 48210}]}
    Client -> Server  FOCUS          {"channel_ids": ["ch_releases"]}                 (currently visible UI tab)
    Client -> Server  HEARTBEAT      {"last_event_no": 319}    <-->   Server -> Client  HEARTBEAT_ACK
    
    Server -> Client  EVENT          {"event_no": 320, "type": "MESSAGE_CREATE",
                                      "data": {"channel_id": "ch_releases", "seq": 48213,
                                               "message_id": "117604928174000128",
                                               "author_id": "u_maya", "content": "Deploy finished",
                                               "nonce": "client-uuid-7c41b9"}}
    Server -> Client  EVENT          {"event_no": 321, "type": "CHANNEL_HEAD",
                                      "data": {"channel_id": "ch_99", "last_seq": 9104}}
    

    Three small API choices prevent whole classes of bugs:

    • nonce (idempotency key): a random ID generated by the client before sending. On a spotty cellular link, the HTTP response may drop after the server saved the message. Retrying POST with the same nonce returns the already-stored message (seq: 48213) instead of posting a duplicate!
    • Why sends use REST instead of the WebSocket: HTTP POST gives clear request timeouts, standard load-balancing, and independent scaling, leaving WebSocket gateways purely stateless push pipes that never touch the database.
    • Two distinct sequence numbers: seq (1, 2, 3, ...) is per-channel and gap-free so clients can spot any missing message (48211 -> 48213 means 48212 is missing!). event_no (318, 319, 320, ...) counts frames delivered on one specific WebSocket session so RESUME can replay missed frames after a brief Wi-Fi blip.
  4. Data model: relational metadata and bucketed wide-column messages

    1. Community and permission metadata (PostgreSQL, sharded by server_id / user_id)

    Servers, channels, memberships, and role permissions change infrequently, fit easily in memory caches, and benefit from relational integrity:

    users               user_id PK (64-bit Snowflake), username, avatar_key, created_at
    servers             server_id PK, name, owner_id, home_region, member_count
    channels            channel_id PK, server_id (NULL for DMs), type (TEXT|DM|GROUP_DM), name
    members             PK (server_id, user_id), role_ids[], joined_at
    user_servers        PK (user_id, server_id)                 -- lookup table: "all servers I joined"
    roles               PK (server_id, role_id), permissions_bitmask (64-bit integer)
    channel_overwrites  PK (channel_id, target_id), allow_mask, deny_mask
    dm_members          PK (channel_id, user_id)                -- plus reverse table PK (user_id, channel_id)
    

    2. Durable message history (ScyllaDB or Apache Cassandra, Replication Factor = 3)

    Messages are append-heavy (2B/day) and almost always queried as "give me 50 consecutive messages in channel_id before or after seq". A wide-column store partitioned by (channel_id, bucket) and sorted by seq serves every history page from a single contiguous disk slice:

    messages
      PRIMARY KEY ((channel_id, bucket), seq) WITH CLUSTERING ORDER BY (seq DESC)
        channel_id      64-bit Snowflake ID
        bucket          (seq - 1) // 50_000     -- caps each partition at 50,000 messages (~15 MB)
        seq             64-bit per-channel monotonic sequence (1, 2, 3, ...)
        head_seq        STATIC bigint           -- highest `seq` committed in this partition (for fencing)
        message_id      64-bit Snowflake ID     -- global identity & cross-channel rough time sort
        author_id       bigint
        content         text
        nonce           text
        attachment_keys list<text>
        edited_at       timestamp, deleted boolean
    
    channel_latest_bucket  PK (channel_id) -> latest_bucket   -- updated only once every 50,000 messages
    read_states            PK (user_id, channel_id) -> last_read_seq, mention_count
    

    Why bucket by (seq - 1) // 50_000 instead of a 10-day time window? If you bucket by 10-day calendar windows, a quiet channel whose previous message was 8 months ago forces the server to probe 24 empty 10-day partitions backward just to fill one screen of history! Conversely, a viral channel can cram millions of messages into a single 10-day partition and create an oversized hot partition. Bucketing by (seq - 1) // 50_000 means every partition holds at most ~15 MB regardless of traffic speed, and jumping to after_seq=48100 computes bucket = 48099 // 50000 = 0 in O(1) arithmetic with zero empty probes.

    Why keep BOTH message_id (Snowflake) and seq? A Snowflake ID packs a timestamp, machine ID, and local counter into 64 bits:

    +-------------------------------------------+-----------------+------------------+
    | 41 bits: milliseconds since custom epoch  | 10 bits: worker | 12 bits: counter |
    +-------------------------------------------+-----------------+------------------+
      (~69 years of timestamps)                   (1,024 nodes)     (4,096 IDs / ms)
    

    message_id gives every message a globally unique permalink and sorts roughly by time across different channels (essential for a global @mentions inbox or future search index), while seq provides strict, gap-free 1, 2, 3, ... ordering inside one channel.

  5. High-level architecture and end-to-end workflow

      [ Maya (Online) ]                                          [ Liam (Offline -> Reconnects) ]
           |                                                            ^                 |
           | 1. HTTPS POST /channels/ch_releases/messages               | 4. WSS push     | 5. WSS READY +
           v                                                            |    (live)       |    GET ?after_seq
      [ Stateless API Tier ]                                     [ WebSocket Gateways (150 nodes) ]
        - validate session token & cached role permissions              ^         |
        - route by hash(channel_id)                                     |         +--> [ Redis Session Dir ]
           |                                                            |              (user_id -> gateways)
           v                                                            | batched gRPC streams
      [ Stateful Channel Owners (4,096 shards via etcd leases) ]        |
        - single writer per channel: assign `seq` + monotonic Snowflake |
        - keep last 200 msgs & 10m nonces in RAM                        |
           |                                                     [ Fan-out Workers ]
           | 2. Conditional quorum write (RF=3, LOCAL_QUORUM)     - consume by server_id
           +------------------------------> [ ScyllaDB /          - map server_id -> subscribed gateways
           |   (reply HTTP 201 to Maya        Cassandra ]               ^
           |    ONLY after durable write!)        ^                     |
           |                                      |              [ Kafka ("channel-events") ]
           +--- 3. Publish persisted event -------|---------------> partitioned by server_id
                   (decouples DB from push)       |                     |
                                                  |                     +--> [ Mobile Push Workers ]
           (History reads miss tail cache) -------+                          (APNs / FCM for offline @mentions)
    

    Let us trace our #releases interaction end to end through this architecture:

    1. Maya posts "Deploy finished" to #releases: Maya's client calls POST /v1/channels/ch_releases/messages carrying nonce="client-uuid-7c41b9".
    2. Session authentication, role check, and durable quorum commit: an API worker validates Maya's bearer token, checks cached workspace/channel permission bitmasks for SEND_MESSAGES, and routes the call to ch_releases's channel owner. That owner assigns seq = 48213 and a monotonic Snowflake message_id, commits the row across 2 of 3 availability zones (LOCAL_QUORUM) in ScyllaDB, and returns HTTP 201 only after durable persistence completes.
    3. Decoupled live fan-out: the channel owner appends the committed record to Kafka (channel-events, partitioned by server_id). A fan-out worker resolves which WebSocket gateways hold active subscribers for that server, sends one copy per gateway, and each gateway pushes MESSAGE_CREATE to permitted sockets watching #releases. Placing Kafka between storage and push ensures slow sockets or restarting workers never stall database commits.
    4. Offline Liam catches up on reconnect: when Liam exits the subway tunnel and reconnects, his READY payload lists "ch_releases": {"last_seq": 48213}. Comparing 48213 against his locally stored cursor 48200, Liam's client requests GET /v1/channels/ch_releases/messages?after_seq=48200 and receives messages 48201..48213 in exact order.
  6. Deep dive 1: strict message ordering in a distributed environment

    Why server timestamps—and even uncoordinated Snowflake IDs—fall short on their own

    Relying on wall-clock timestamps fails immediately because two servers' clocks drift by several milliseconds (even with NTP synchronization), two messages in the same millisecond tie, and NTP adjustments can step a clock backward.

    Switching to Snowflake IDs gives globally unique, roughly time-ordered 64-bit IDs without coordination. However, if multiple stateless API servers independently stamp Snowflake IDs and write directly to the database for the same channel, two subtle ordering bugs still occur:

    Bug 1 (Clock skew):
      API Node 1 (clock +8 ms fast) stamps id = 1008 for Maya's post   at real t = 1000 ms
      API Node 2 (clock accurate)   stamps id = 1003 for Noah's reply  at real t = 1003 ms
      Result: Noah's reply sorts BEFORE Maya's post!
    
    Bug 2 (Out-of-order visibility + silent cursor skip):
      API Node 1 stamps id = 500, starts slow DB write...
      API Node 2 stamps id = 505, fast DB write finishes first!
      Liam reconnects, asks "messages after 490" -> receives [505], advances local cursor to 505.
      10 ms later, id = 500 finishes writing -> Liam NEVER queries <= 505 again; message 500 is silently lost!
    

    The solution: single channel owner + gap-free seq + fenced group commit

    We hash all channels into 4,096 shards, where each shard is owned by one stateful channel owner node holding a short lease (10 s TTL, renewed every 3 s) in etcd (a strongly consistent coordination service). Because every write to ch_releases passes through that single owner: - It assigns a strictly gap-free seq = 1, 2, 3, ... and clamps its Snowflake generator (message_id = max(next_snowflake(), last_message_id + 1)) so both seq and message_id strictly increase! - Group commit batches concurrent arrivals while the previous database round-trip is in flight: if 80 people post during one 8 ms ScyllaDB write, all 80 messages commit in the next single-partition batch (80 / 0.008 s = 10,000 messages/s in a single channel!). - Storage-side zombie fencing: what if an old owner freezes in a garbage-collection pause for 12 seconds, loses its etcd lease, and wakes up thinking it still owns ch_releases? To prevent two owners (split-brain) from overwriting the same seq, every batch performs an atomic conditional write (compare-and-swap on the partition's STATIC head_seq column):

    from collections import deque
    
    
    def process_channel_writes(channel, store, kafka_bus, snowflake_gen):
        """Single-owner write loop for one channel with nonce dedupe and group commit."""
        while channel.is_lease_valid():
            # Block for at least 1 send request, then drain up to 50 queued requests
            batch_requests = channel.inbox.take_batch(max_items=50)
            rows_to_insert = []
            client_replies = []
    
            for req in batch_requests:
                dedupe_key = (req.author_id, req.nonce)
                existing_row = channel.recent_nonces.get(dedupe_key)
                if existing_row is not None:
                    # Client retried a send we already sequenced: reuse the original row
                    client_replies.append((req, existing_row))
                    continue
    
                # Assign gap-free `seq` and strictly monotonic Snowflake `message_id`
                msg_id = max(snowflake_gen.next_id(), channel.last_message_id + 1)
                channel.last_message_id = msg_id
                row = channel.build_row(seq=channel.next_seq, message_id=msg_id, req=req)
    
                channel.next_seq += 1
                channel.remember_nonce(dedupe_key, row)
                rows_to_insert.append(row)
                client_replies.append((req, row))
    
            if rows_to_insert:
                expected_prev_seq = rows_to_insert[0].seq - 1
                # Conditional batch: succeeds ONLY if `head_seq == expected_prev_seq`
                committed = store.write_batch_if_head_matches(
                    channel_id=channel.id,
                    rows=rows_to_insert,
                    expected_head=expected_prev_seq,
                )
                if not committed:
                    # Another owner took over our shard! Abort and return 503 so clients retry
                    channel.abort_and_return_503(batch_requests)
                    return
    
                # Cache latest 200 rows in memory (bounded deque) & publish to Kafka
                channel.tail_cache.extend(rows_to_insert)
                kafka_bus.publish(partition_key=channel.server_id, events=rows_to_insert)
    
            for req, row in client_replies:
                req.reply_201(row)
    

    On the client side, gap-free seq makes rendering resilient even if network events arrive out of order or drop:

    def on_live_message(view_state, channel_id: str, msg) -> None:
        """Render strictly in `seq` order and fetch missing gaps automatically."""
        last_seen = view_state.last_seq.get(channel_id, 0)
    
        if msg.seq <= last_seen:
            # Duplicate delivery (from session resume or worker replay): ignore
            return
    
        if msg.seq == last_seen + 1:
            # Exact next message in sequence: display immediately!
            view_state.render(msg)
            view_state.last_seq[channel_id] = msg.seq
            # Drain any future messages (`last_seen + 2`, ...) already waiting in buffer
            view_state.flush_contiguous_buffered(channel_id)
            return
    
        # Gap detected (e.g. jumped from 41 to 43): stash 43 and pull missing range > 41
        view_state.buffer_out_of_order(channel_id, msg)
        view_state.schedule_gap_fetch(channel_id, after_seq=last_seen)
    
  7. Deep dive 2: real-time fan-out to millions of online users

    Two-hop fan-out (copy per gateway, not per user)

    If 50,000 online members belong to a gaming server spread across 150 gateways, a new message should travel over the internal network 150 times (once to each gateway), not 50,000 times:

    [ Kafka partition (server_id = S) ]
            |
            v
    [ Fan-out Worker ]
      in-memory routing map: server S -> {gateway_1, gateway_2, ..., gateway_150}
      flushes batched events every 5 ms over 1 persistent gRPC stream per gateway
            |
            +---> [ Gateway 1 ] -> checks local permission map -> pushes to 340 local WebSockets
            +---> [ Gateway 2 ] -> checks local permission map -> pushes to 325 local WebSockets
    

    Race-free subscription handshakes

    When User U connects to Gateway 1 and needs events for Server S for the first time on that gateway, how do we avoid missing a message sent during the subscription setup? Gateway 1 writes a tiny SUBSCRIBE(server_id=S, gateway_id=1) control record into the exact same Kafka partition that carries Server S's messages! The fan-out worker reads the partition sequentially: it records Gateway 1 at offset K, immediately replies with Server S's current last_seq channel heads as of offset K, and streams every message after offset K live. Zero messages can fall between the snapshot and the live stream.

    Taming 500,000-member servers with FOCUS subscriptions

    Even among online users, 49,000 out of 50,000 online members of a huge server are looking at a different server or channel tab right now. Pushing every raw MESSAGE_CREATE to all 50,000 sockets wastes bandwidth and client CPU:

    • Small servers (< 1,000 members): push full MESSAGE_CREATE events for all permitted channels.
    • Large servers (>= 1,000 members): push full MESSAGE_CREATE events only to sessions that sent FOCUS for that active channel (plus any @mention or DM). All other online members receive a tiny coalesced CHANNEL_HEAD {"channel_id": "ch_99", "last_seq": 9104} at most once every 2 seconds so their sidebar unread dot lights up cleanly!
    • Slow-client protection: every WebSocket session has a strict outbound memory cap (2,000 queued frames or 1 MB). If a user enters an elevator and stops acknowledging TCP packets, the gateway closes that single socket rather than letting buffered frames exhaust server RAM, and the client cleanly resyncs when signal returns.
  8. Deep dive 3: offline synchronization and flaky networks

    Combining live push for connected sessions with on-demand pull for disconnected clients handles every disconnect duration cleanly:

    Disconnect duration          Synchronization path on reconnect
    ---------------------------  ------------------------------------------------------------------
    Brief drop (< 2 minutes)     Client sends `RESUME {session_id, last_event_no}` to `resume_url`.
                                 Gateway replays missed frames straight from its 2-minute RAM ring
                                 buffer -> zero database queries!
    
    Long offline (>= 2 minutes)  Client sends `IDENTIFY`. Gateway returns `READY` containing
    or gateway node restarted    `{channel_id, last_seq}` for the user's servers + `read_states`.
                                 1. Client compares `last_seq > last_read_seq` locally to light up
                                    unread badges across all 450 channels instantly (zero DB reads!).
                                 2. ONLY when the user clicks into a channel does the client call
                                    `GET /messages?after_seq=<cached_seq>` (1 single-partition read).
    
    App backgrounded on mobile   WebSocket closes to save battery; Kafka `Mobile Push Workers` check
                                 Redis `user_sessions:{user_id}` -> if empty, send APNs/FCM push
                                 notifications ONLY for DMs and `@mentions`.
    

    Surviving reconnect storms ("thundering herds"): if a gateway node crashes, 100,000 clients lose their socket simultaneously. If all 100,000 reconnected within 50 ms, they would overwhelm TLS handshakes and IDENTIFY processing. Clients add random jitter (0–5 seconds uniform delay before the first reconnect, followed by exponential backoff with jitter), gateways rate-limit IDENTIFY handshakes to 2,000/s per node, and READY channel heads are served purely from gateway/fan-out worker memory caches rather than hitting ScyllaDB.

  9. Scaling, bottlenecks, and multi-region topology

    • WebSocket gateways: horizontally scalable and durable-state-free; placed at edge regions worldwide behind GeoDNS/Anycast so TLS termination and mobile round-trip times stay local (< 30 ms).
    • Channel owners: 4,096 shards spread across ~64 nodes (~64 shards/node). Hot-channel reads hit the owner's 200-message in-memory tail_cache, shielding ScyllaDB when 50,000 members click an @everyone announcement at the exact same second! Hot-channel writes combine via group commit (~10,000 msgs/s), while user-level rate limits and optional channel "slow mode" (e.g., 1 message per user every 5 seconds) keep human chat readable.
    • ScyllaDB / Cassandra cluster: sized both for ~70,000 conditional Paxos batches/second (LOCAL_SERIAL / LOCAL_QUORUM) and ~280 TB/year of LZ4-compressed storage (~90–120 NVMe nodes in year 1, scaling linearly by adding nodes).
    • Multi-region layout: each server has a home_region (chosen near its creator/community, e.g., us-east or eu-central) where its channel owner shard, primary ScyllaDB quorum (3 AZs), and primary Kafka partition live, with asynchronous cross-region replication to a backup region. A user in Tokyo posting to a us-east server pays one cross-Pacific hop (~150 ms) so the single owner can sequence the message cleanly, and regional Kafka mirroring streams the committed event out to gateways worldwide within < 300–450 ms.
  10. Failure handling and trade-off summary

    Failure mode User-visible effect Automated recovery
    Gateway server crashes 100k sockets drop Clients reconnect with 0–5 s jitter to surviving gateways and catch up via IDENTIFY + lazy after_seq pulls.
    Stateless API node crashes In-flight POST times out Client retries POST with the exact same nonce; channel owner returns the original stored row without duplicating it.
    Channel owner crashes Writes to 1/64 of channels return 503 for <= 10 s etcd lease expires; new owner reads head_seq and recent rows/nonces at LOCAL_SERIAL, resumes sequencing, and emits CHANNEL_HEAD in case the old owner crashed between DB commit and Kafka publish.
    Old owner freezes then wakes (zombie) Brief dual-owner race Storage-side conditional batch (IF head_seq = expected) rejects the zombie's write; zombie sees lease lost and returns 503.
    One ScyllaDB node or whole AZ fails Zero downtime LOCAL_QUORUM (2 of 3 AZ replicas) continues reading and writing without interruption.
    Fan-out worker crashes Few seconds of push delay on its partitions Replacement consumer loads periodic subscription/head snapshot from Kafka compact topic, replays from last offset; clients ignore duplicate pushes via msg.seq <= last_seen.

    Core architectural trade-offs

    • Persist at quorum before returning 201, then push via Kafka: guarantees an acknowledged message is never lost or shown live without existing in history, adding ~5–10 ms to send latency.
    • Single channel owner + gap-free seq + monotonic Snowflake message_id: provides strict ordering, hole detection, and global IDs, at the cost of one cross-region hop for distant senders and a <= 10 s shard failover pause if an owner crashes.
    • Conditional Paxos batch writes vs. lease-only fencing: pays extra local round-trips per batch in ScyllaDB (amortized via group commit) to make zombie-owner overwrites mathematically impossible.
    • Push to active/focused sockets, pull on demand for offline users: avoids 500,000 wasted inbox writes per message in large communities while keeping active chats instantaneous.

Intuition & how it works

Picture a busy community hall with a permanent glass bulletin board for each room and radio announcers broadcasting live to members wearing headsets. Whenever someone posts a note in the #releases room, a single clerk at #releases's desk stamps it with the next sequential ticket number (#41, #42, #43), pins it behind the glass first, and only then gives the sender a thumbs-up. Next, the radio announcer reads #42 aloud once to everyone currently tuned in; anyone whose radio cut out in a tunnel simply looks at the board later, sees ticket #43 is the newest, and reads whatever tickets came after #40—the last number they remember.

Naive chat designs break down quickly at millions of users. Having 10 million clients poll an HTTP endpoint every second generates 10 million mostly empty database queries per second, while relying on wall-clock timestamps from many API servers scrambles message order whenever server clocks drift by a few milliseconds. Just as fatal, copying every new message into per-user "unread inboxes" (fan-out on write) turns a single message in a 500,000-member community server into 500,000 database writes—mostly for offline users who may never even open that channel.

Walk through five concrete events in #releases (channel_id = ch_releases) to see how the design keeps messages fast, durable, and strictly ordered:

  1. Maya posts "Deploy finished": Maya sends POST /v1/channels/ch_releases/messages with a random idempotency key (nonce = "client-uuid-7c41b9"—a client-generated token so retrying a timed-out request never creates a duplicate message).
  2. Single-owner sequencing & durable quorum write: The stateless API checks permissions and routes ch_releases to its single stateful channel owner, which assigns both a globally unique Snowflake ID (a 64-bit integer packing timestamp, worker ID, and counter) and the next gap-free channel sequence number seq = 42. It writes seq = 42 to ScyllaDB/Cassandra at quorum (2 of 3 availability-zone replicas) using a conditional write (IF head_seq = 41, an atomic compare-and-swap that blocks stale "zombie" owners), then replies HTTP 201.
  3. Decoupled Kafka publish: The channel owner appends seq = 42 to Kafka (an append-only distributed message log), separating database durability from live push delivery.
  4. Two-hop WebSocket push: A fan-out worker sends one copy of seq = 42 to each WebSocket gateway (a server holding ~100,000 persistent two-way client connections) that has subscribed members, and each gateway pushes seq = 42 to online viewers in < 300 ms.
  5. Offline Liam reconnects and pulls: Liam lost signal in a subway tunnel at seq = 40. On reconnect, his READY summary reports ch_releases's latest head is 42, so when Liam opens #releases, his client pulls GET /messages?after_seq=40 and receives 41 and 42 in exact order from a single database partition.

Key trade-offs

  • Persist to quorum before replying vs. push before persisting. Waiting for 2 of 3 database replicas before returning 201 and publishing to Kafka adds ~5–10 ms to send latency, but guarantees durability first: a user never sees a message appear live and then vanish from history after a server crash.
  • Single channel owner + gap-free seq vs. uncoordinated Snowflake IDs from any API node. Letting any stateless server stamp a Snowflake ID avoids shard leases, but clock skew between servers can invert conversation order and natural gaps between Snowflake timestamps prevent clients from knowing whether a WebSocket packet was dropped. Routing each channel through one owner (with group commit—batching concurrent arrivals into a single database round-trip) gives gap-free 1, 2, 3, ... ordering and ~10,000 messages/s per channel, at the cost of a <= 10 s shard failover pause on crash and one cross-region hop for distant senders.
  • Storage-side conditional writes (IF head_seq = ...) vs. lease-only fencing. Relying solely on a timed lease fails when an old owner freezes in a long garbage-collection pause, loses its lease, and wakes up to write stale sequence numbers (split-brain). Conditional Paxos writes cost extra local round-trips per batch in ScyllaDB/Cassandra, but guarantee two owners can never overwrite the same seq.
  • Bucketing partitions by (seq - 1) // 50_000 vs. calendar time buckets. Fixed 50,000-message sequence buckets keep every database partition near a predictable ~15 MB and let any after_seq cursor compute its exact bucket in O(1) math, whereas 10-day time buckets force quiet channels to scan dozens of empty buckets and let viral channels blow up partition sizes.
  • Push to active/focused online users, pull on read for offline users. Pushing live events over WebSockets (and coalescing background tabs in huge servers down to lightweight CHANNEL_HEAD badge updates) keeps active chats instant while avoiding millions of wasted per-user inbox writes for offline members.
  • In-memory gateway resume buffers vs. replicated session logs. Keeping 2 minutes of recent frames (~840 MB) in each gateway's RAM lets brief Wi-Fi drops RESUME with zero database load, accepting that a full gateway crash forces its 100,000 clients to do a jittered IDENTIFY + READY resync rather than paying to replicate every session buffer across machines.

Common mistakes

  • Sorting messages by client clocks or uncoordinated server timestamps: clocks drift across machines and jump backward during NTP syncs, causing replies to appear above the message they answered.
  • Using Snowflake IDs across multiple writers without gap detection: if Writer A stamps ID 100 (slow DB write) and Writer B stamps ID 105 (fast DB write), a reconnecting client querying after_id=95 receives 105, advances its cursor to 105, and permanently misses 100 when it lands milliseconds later.
  • Sending messages without a client nonce (idempotency key): mobile connections frequently drop HTTP responses after the server already stored the message, causing retries to post embarrassing duplicates.
  • Fan-out on write to every member of a 500k-member server: writing per-user inbox rows or pushing full message payloads to 49,000 online users who are not even viewing that channel melts both storage and gateway bandwidth.
  • Unbounded outbound WebSocket queues: if one user on flaky train Wi-Fi stalls TCP acknowledgments and the gateway buffers forever, slow clients exhaust gateway memory; always cap per-session buffers and disconnect lagging sockets so they resync cleanly.
  • Writing heartbeats to a database: persisting 10M connection heartbeats every 40 seconds creates 250,000 pointless database writes/second instead of keeping liveness in gateway memory.
  • Ignoring the reconnect thundering herd: when one gateway crashes, 100,000 clients reconnecting at millisecond zero will cascade-crash surviving gateways unless clients wait a random jitter window (0–5 s) and READY summaries read from memory caches.

Follow-up questions

  • What breaks first when tens of thousands of members pile into one viral channel and post concurrently, and how do you keep writes and fan-out healthy? On the write path, a single channel owner serializes sequence numbers in RAM (nanoseconds) and uses group commit to pack up to 50–100 concurrent sends into one conditional ScyllaDB batch every ~8 ms, sustaining 6,000–10,000 messages/s—far higher than human typing speed (2,000 active senders posting once every 5 seconds is 400 messages/s)—while per-user rate limits and optional channel "slow mode" block bot floods. On the read and fan-out path, where 400 messages/s × 25,000 viewers = 10M pushes/s is the real bottleneck, gateways coalesce outbound MESSAGE_CREATE events for that hot channel into one batched WebSocket frame every 100 ms per viewer (10 frames/s instead of 400/s), non-focused server members receive only a 2-second coalesced CHANNEL_HEAD badge update, and GET /messages history loads hit the channel owner's 200-message in-memory tail cache instead of hammering ScyllaDB replicas.
  • How would you add unread/read tracking and live online-status indicators without overwhelming storage or gateway bandwidth? Store read state as one compact cursor (user_id, channel_id) -> last_read_seq, never one receipt row per message; clients debounce updates to once every few seconds (last_read_seq = max(old, new)), and live "Seen by X" indicators broadcast only in DMs and small group chats (<= 10 members), while large servers only use last_read_seq locally to light up the user's own unread badges. For presence, run an in-memory presence service sharded by user_id that writes only on state transitions (online, idle, offline), never on routine heartbeats—each gateway sends a single lease heartbeat covering all 100,000 of its sessions so a dead gateway marks sessions offline in bulk. Finally, scope presence fan-out strictly to friends and the ~50–100 member rows currently scrolled into view on a user's sidebar (lazy member-list subscriptions), coalescing status changes into 5-second batches.
  • Suppose product asks for end-to-end encrypted channels—what changes for multi-device history recovery, full-text search, and push notifications? With end-to-end encryption (E2EE)—where plaintext is encrypted on the sender's device so the server stores and routes only opaque ciphertext—routing envelopes (channel_id, seq, message_id, author_id) stay unencrypted, so our sequencing, ScyllaDB bucketing, and after_seq synchronization continue working unchanged. However, message history becomes a cryptographic key-management problem: a newly logged-in phone or laptop can decrypt older messages only if past encryption keys are backed up in an encrypted key vault (unlocked via a user recovery passphrase/PIN) or synced device-to-device, and rotating group keys (via Sender Keys or the Messaging Layer Security / MLS protocol) whenever members join or leave is practical for DMs and small groups (<= 100–1,000 users) rather than 500,000-member public servers. Because the server never sees plaintext, server-side full-text search, link-preview scraping, and content-based spam filtering become impossible: search must run against a local encrypted SQLite/FTS index built on each client device over the history it has decrypted, and push notifications must either show generic "New message" text or wake a local mobile notification-service extension to decrypt the payload on the phone.

Follow-up questions

Similar questions

More Onepay interview questions

All 3 Onepay questions →