Real-Time Direct Messaging Service Architecture

Medium · System Design · Software Engineer · Technical Screen

Prompt

Architect a real-time direct-messaging service supporting private two-person conversations across up to 10 million Daily Active Users (DAU) and millions of simultaneously connected devices.

Core product capabilities: - Live two-party chat: Two users can exchange direct messages with sub-second turnaround (for instance, Maya sending Liam "Coffee at 3?" and seeing his reply immediately). - Persistent thread history: Participants can open any conversation and page backward through earlier messages. - Peer presence: Clients display whether a contact is actively connected or currently offline.

System guarantees: - Resilience to server faults: Losing an individual gateway, application worker, or database node must neither cause an outage nor drop acknowledged messages. - Near-instant responsiveness: Deliver messages to online peers in well under a second. - Strict per-chat ordering: Messages within any two-person thread must appear in the exact sequence they were dispatched. - Elastic scale: Sustain 10 million DAU across peak daily traffic waves.

Scope & Expectations

  • Client-server protocols & APIs: Define wire contracts for live message exchange, historical pagination, and presence subscriptions.
  • Storage model & partitioning: Lay out schemas for accounts, two-user threads, and ordered message logs so reads stay fast even during node failures.
  • Topology & online/offline routing: Trace how clients, load balancers, connection gateways, chat services, and databases coordinate when a recipient is connected versus unreachable.
  • Design trade-offs: Justify your persistence engine choices (relational SQL vs. distributed NoSQL) and delivery semantics (at-least-once with deduplication vs. exactly-once).

Step-by-step walkthrough

  1. Clarify requirements and scope

    Unlike a traditional web app where a client sends an HTTP request, gets a response, and hangs up, a real-time chat system must solve three tricky distributed problems at once: keeping millions of long-lived phone connections reachable ("which server holds Liam's open socket right now?"), giving both participants the exact same message order even when networks drop and retry packets, and reliably catching up recipients who were offline on an airplane or subway.

    Functional requirements

    • One-to-one real-time messaging: users send and receive text messages instantly.
    • Conversation history: users scroll backward through past messages, newest page first.
    • Online/offline presence: users see whether a contact is currently online or their last_seen timestamp.
    • Delivery states: the sender sees when a message is sent (durably stored by the server), delivered (reached at least one recipient device), and read.

    Non-functional requirements

    • Scale: 10 million Daily Active Users (DAU), with millions of simultaneous open connections at peak hours.
    • Low latency: sub-second delivery to online users. Specifically, we target p99 latency (the response time that 99% of messages beat, measuring even the slowest 1% of cases) under 500 ms end-to-end within a region, and under 100 ms inside our backend.
    • Strict per-conversation ordering: messages in a chat appear in the exact same order on every device, matching the order each sender sent them.
    • High availability and durability: no single server or availability zone (AZ) (an isolated data center within a cloud region with its own power and networking) failing takes the service down, and no acknowledged message is ever lost.

    Scope assumptions to state up front

    • Multi-device support: up to 4 active devices per user (phone, tablet, web, desktop), all kept in sync.
    • Message size: text up to 4 KB. Images and videos upload separately to object storage and send a small URL/reference inside the text message.
    • History retention: stored on the server indefinitely so logging in on a new phone restores past chats (end-to-end encryption changes this; covered in the follow-ups).
    • Geography: start with one region spread across 3 AZs, then extend to multi-region under scaling.
  2. Back-of-the-envelope numbers

    Before picking databases or server counts, let's convert 10M DAU into concrete connection, throughput, and disk numbers (using 86,400 seconds per day and a 3x peak-to-average multiplier).

    Connections
      DAU                             10,000,000 users
      peak concurrent connections     ~30% of DAU = 3,000,000 open sockets
      sockets per gateway server      ~50,000 (~30 KB RAM per socket for TLS + buffers = ~1.5 GB RAM)
      gateway servers needed          3,000,000 / 50,000 = 60 gateways minimum
                                      run 90 gateways (30 per AZ across 3 AZs) so losing 1 AZ still leaves 60
      socket heartbeats               1 ping every 30 s -> 3,000,000 / 30 = 100,000 pings/s total
                                      (~1,100 pings/s handled locally per gateway)
    
    Message throughput
      messages sent per DAU per day   40 -> 400,000,000 messages/day
      average write rate              400,000,000 / 86,400 s = ~4,600 messages/s
      peak write rate (3x)            ~14,000 messages/s
      network bandwidth at peak       14,000/s x ~3 frames (send + ack + push) x ~1 KB = ~42 MB/s
    
    Persistent storage
      average message row             ~200 bytes (100 B text + IDs + timestamps)
      daily message growth            400M x 200 B = 80 GB/day raw; x3 replicas = 240 GB/day on disk
      yearly message growth           80 GB x 365 = ~29 TB/year raw (~88 TB/year with 3 replicas)
      storage nodes per year          88 TB / ~2 TB usable per node = ~45 nodes added per year
      30-day sync inbox (pointers)    400M msgs x 2 users x 60 B x 30 days = ~1.4 TB raw (~4.3 TB replicated)
    
    Presence and session registry
      connect + disconnect events     10M DAU x 10 sessions/day x 2 events = 200M/day
                                      -> ~2,300/s average, ~7,000/s peak (budget for 10,000/s)
      in-memory session map           3,000,000 active devices x ~150 B = ~450 MB total in Redis
    

    What these numbers tell us: 14,000 message writes/s and 42 MB/s of bandwidth are modest for modern servers. The three hard engineering problems are: 1. Stateful routing: tracking which of the 90 gateways holds each of the 3 million live sockets. 2. Fault-tolerant storage growth: storing ~88 TB/year of conversations so history stays fast and survives server crashes. 3. Presence amplification: avoiding multiplying 10,000 connect/disconnect events/s by 200 contacts per user.

  3. API design: WebSockets for live events, HTTPS for history

    If 3 million phones polled an HTTP endpoint every second asking "any new messages?", our servers would drown in 3 million mostly empty requests per second. Instead, each active device opens one WebSocket — a single long-lived, two-way TCP connection over TLS that lets either the client or the server push frames immediately without repeated HTTP headers or handshakes.

    We keep history pagination, catch-up sync, and device registration on standard HTTPS, because request/response calls are stateless, easy to load-balance, and straightforward to retry.

    HTTPS endpoints (stateless request/response)
      POST /v1/conversations                {peer_id} -> 200 {conversation_id}
      GET  /v1/conversations?cursor=...     paginated list of conversations (for fresh installs)
      GET  /v1/conversations/{id}/messages?before_seq=1200&limit=50
                                            -> 200 {messages: [...newest first], next_before_seq}
      GET  /v1/sync?cursor=<event_id>&limit=500
                                            -> 200 {changes: [...], next_cursor, has_more}
      POST /v1/devices                      {device_id, platform, push_token}
      GET  /v1/presence?user_ids=u1,u2,u3   -> 200 [{user_id, state, last_seen}]
      GET  wss://chat.example.com/v1/ws     upgrades HTTPS request to a persistent WebSocket
    
    WebSocket frames (encoded with Protobuf in production; shown as JSON for clarity)
      client -> server
        send        {client_msg_id, conversation_id, body, retry: false}
        delivered   {conversation_id, up_to_seq}           "my device stored everything up to seq"
        read        {conversation_id, up_to_seq}           "user viewed everything up to seq"
        presence    {subscribe: [user_id, ...]}            up to 50 contacts currently on screen
        typing      {conversation_id}                      ephemeral hint, never written to disk
    
      server -> client
        ack         {client_msg_id, conversation_id, seq, server_ts}
        message     {conversation_id, seq, sender_id, client_msg_id, body, server_ts}
        receipt     {conversation_id, user_id, delivered_up_to, read_up_to}
        presence    {user_id, state: "online" | "offline", last_seen}
        error       {client_msg_id, code: "rate_limited" | "blocked" | "too_large"}
    

    Three design details make this API reliable: - Client-generated client_msg_id: before sending, the app generates a random UUID called an idempotency key — a unique identifier attached to a request so if the client retries after a network drop, the server recognizes the repeat and avoids storing a duplicate message. - Server-assigned seq: an integer (1, 2, 3, ...) giving every message its exact position in that conversation. Devices sort by seq, deduplicate by seq, and detect missing messages immediately if 89 arrives right after 87. - Deterministic conversation_id: for fixed-format user IDs (such as UUIDs or integers), conversation_id = "dm:" + min(user_a, user_b) + ":" + max(user_a, user_b). If Maya and Liam tap "New Chat" at the exact same instant, both compute "dm:u_215:u_740" instead of accidentally creating two separate conversations.

  4. Data model and partitioning for fault tolerance

    Our data splits naturally into two workloads with very different shapes:

    1. Small relational account data (users, devices, blocks): 100M registered users at ~1 KB each is ~100 GB total, rarely modified, and needs strict uniqueness constraints (one account per phone number). PostgreSQL with primary-standby replication across AZs handles this cleanly.
    2. High-volume, append-heavy chat data (messages, inbox, receipts): ~88 TB/year of writes read almost exclusively by key range ("fetch 50 messages before seq = 1200 in conversation X"). A wide-column store (Cassandra or ScyllaDB) — a distributed NoSQL database that hashes a partition key to spread data across nodes and keeps rows inside each partition physically sorted on disk by a clustering key — fits this access pattern natively.
    PostgreSQL (account metadata)
      users               user_id PK, phone UNIQUE, display_name, created_at, last_seen_at
      devices             device_id PK, user_id, platform, push_token, created_at
      blocks              (user_id, blocked_user_id) PK
    
    Cassandra / ScyllaDB (replication factor = 3 across 3 AZs; reads & writes at LOCAL_QUORUM)
      messages
        PRIMARY KEY ((conversation_id, bucket), seq)     bucket = seq // 10,000
        sender_id, client_msg_id, body, server_ts
        CLUSTERING ORDER BY (seq DESC)
    
      conversations
        PRIMARY KEY (conversation_id)
        member_ids, created_at, latest_bucket
    
      user_conversations
        PRIMARY KEY ((user_id), conversation_id)
        peer_id, created_at
    
      inbox                                              temporary catch-up queue per user
        PRIMARY KEY ((user_id, day), event_id)           event_id = UUIDv7 (time-ordered UUID)
        conversation_id, seq, kind ('message' | 'receipt')
        DEFAULT TTL 30 days
    
      receipts
        PRIMARY KEY ((conversation_id), user_id)
        delivered_seq, read_seq, updated_at
    

    Here is how this schema satisfies both performance and fault tolerance:

    Partitioning & bounded buckets for conversation "dm:u_215:u_740":
    
      Partition ("dm:u_215:u_740", bucket=0)  --> seq 9999, 9998, ..., 2, 1     (~2 MB max, 3 replicas in AZ1/AZ2/AZ3)
      Partition ("dm:u_215:u_740", bucket=1)  --> seq 10205, ..., 10001, 10000  (~2 MB max, 3 replicas in AZ1/AZ2/AZ3)
                                                   ^
                                      newest page is 1 sequential disk slice!
    
    • Surviving node and AZ failures: Cassandra hashes (conversation_id, bucket) onto a ring of storage nodes and stores 3 copies across 3 different AZs. Reading and writing at LOCAL_QUORUM — requiring at least 2 of the 3 replicas to confirm every operation — guarantees that even if a storage node crashes or an entire AZ loses power, 2 replicas remain online and message history stays 100% readable and writable.
    • Why 10,000-message buckets? Without bucket = seq // 10_000, two chatty friends sending 500,000 messages over five years would create a single huge partition that slows down compaction and unbalances storage nodes. Capping each bucket at 10,000 rows keeps every partition around ~2 MB (10,000 x 200 B).
    • Why inbox uses daily partitions + TTL: inbox is an append-only per-user change feed using UUIDv7 (a unique ID whose leading bits encode the current millisecond timestamp, so entries sort chronologically). Instead of deleting individual rows on delivery — which creates tombstones (slow deletion markers in log-structured databases) — entire daily partitions expire cleanly after 30 days.
  5. High-level architecture

    Separating stateful socket servers from stateless business logic keeps deployments and crashes painless:

       Maya's phone                                                     Liam's phone
            |  WebSocket (TLS)                                      WebSocket |   ^ APNs / FCM
            v                                                                 v   | (wake-up push)
     [ L4 Load Balancer ]                                          [ L4 Load Balancer ]
            |                                                                 |
            v                                                                 v
     [ Gateway gw09 ] ----- send RPC ------> [ Message Service ] --- push -> [ Gateway gw31 ]
      (holds open sockets,                    | 1. auth & rate-limit           (holds open sockets)
       30 s heartbeats,                       | 2. assign seq & persist
       serializes per-chat bursts)            | 3. append inbox pointers
            |                                 | 4. ack Maya & route to Liam
            |                                 +-----------------------------> [ Push Service ]
            v                                 v                                (offline devices)
     [ Session Registry (Redis) ]     [ Cassandra (RF=3, 3 AZs) ]
      sessions:{user} -> {dev: gw}     messages, inbox, receipts, conversations
      gw:{id} -> 15 s liveness TTL
            ^
            | connect / disconnect
     [ Presence Service ] <---------> [ Redis Sharded Pub/Sub: presence:{user} ]
    
     [ Stateless HTTPS API ] -------> [ Cassandra (history, sync) + PostgreSQL (users, devices) ]
    
    • L4 Load Balancer: a network-layer load balancer that routes raw TCP packets by IP and port, keeping a client's long-lived WebSocket pinned to one gateway.
    • WebSocket Gateways (gw01..gw90): hold open TLS connections, verify auth tokens on connect, answer 30-second pings locally, and forward frames to internal services. They store zero durable chat state.
    • Message Service: stateless workers. Gateway gw09 routes calls for conversation_id using consistent hashing so one worker usually has that conversation's latest seq warm in RAM — though correctness comes from the database, never from in-memory state.
    • Session Registry (Redis Cluster): maps each user_id to their currently connected {device_id: gateway_id} pairs in one sub-millisecond lookup.
  6. Deep dive 1: message ordering and at-least-once delivery

    Why timestamps fail for ordering

    If Maya says "Coffee at 3?" and Liam replies "Sounds good!" 80 ms later through a different server whose clock runs 120 ms behind, sorting by timestamp puts "Sounds good!" before "Coffee at 3?". Wall clocks across machines always drift slightly (clock skew), so we assign a gap-free integer seq per conversation instead.

    Assigning seq without gaps or single-node bottlenecks

    Each conversation has at most two human writers, so contention is rare. We assign seq directly inside Cassandra using a compare-and-swap (CAS) lightweight transaction — an atomic conditional write (INSERT ... IF NOT EXISTS, backed by the Paxos consensus protocol across replicas) that guarantees only one writer can ever claim (conversation_id, bucket, seq):

    MAX_ATTEMPTS = 5
    BUCKET_SIZE = 10_000
    
    
    def store_message(db, seq_cache, conversation_id, sender_id, client_msg_id, body, now_ms):
        """Assign the next gap-free sequence number in conversation_id and persist the message."""
        for _ in range(MAX_ATTEMPTS):
            # Step 1: propose the next sequence number from our local cache hint.
            seq = seq_cache.last_seq(conversation_id) + 1
            bucket = seq // BUCKET_SIZE
    
            # Step 2: when crossing into a new 10,000-message bucket, record it on conversations
            # so cold-cache servers know which bucket to inspect first.
            if seq % BUCKET_SIZE == 0:
                db.ensure_latest_bucket(conversation_id, bucket)
    
            # Step 3: atomic conditional insert — succeeds only if no message owns this seq yet.
            applied, existing = db.insert_if_not_exists(
                table="messages",
                key={"conversation_id": conversation_id, "bucket": bucket, "seq": seq},
                values={
                    "sender_id": sender_id,
                    "client_msg_id": client_msg_id,
                    "body": body,
                    "server_ts": now_ms,
                },
            )
            if applied:
                seq_cache.set_last_seq(conversation_id, seq)
                return seq
    
            # If our own earlier retry already won this exact slot, return its seq idempotently.
            if existing["sender_id"] == sender_id and existing["client_msg_id"] == client_msg_id:
                seq_cache.set_last_seq(conversation_id, seq)
                return seq
    
            # Another concurrent message won `seq`; refresh from serial read (at least `seq`).
            db_latest = seq_cache.refresh_from_db_serial(conversation_id)
            seq_cache.set_last_seq(conversation_id, max(db_latest, seq))
    
        raise RuntimeError(f"Too much write contention on {conversation_id}")
    

    Let's trace Maya and Liam pressing Send at the exact same millisecond when last_seq = 87:

      Maya's request                      Cassandra replicas (RF=3)                Liam's request
      --------------                      -------------------------                --------------
      proposes seq = 88  ---------------> Paxos round on seq = 88 <--------------- proposes seq = 88
                                          Maya wins! Row 88 written.
      applied = True     <--------------- Liam gets applied = False (existing=88) -> updates hint to 88
      acks Maya (seq=88)                                                           proposes seq = 89 -> wins!
                                                                                   acks Liam (seq=89)
    

    Both devices receive 88 (Maya) followed by 89 (Liam), with zero gaps and no single master server to fail over. And to preserve the order of a rapid multi-message burst from one sender ("Hey", "Got a minute?"), the gateway processes frames for a given (connection, conversation_id) one at a time in FIFO order; if message 1 fails, queued messages behind it fail together so the client retries them in the original order.

    Why we choose at-least-once delivery + idempotency (not "exactly-once")

    Over an unreliable mobile network, pure transport-level "exactly-once" delivery is mathematically impossible: if Maya's phone sends a message and never receives an ack, the phone cannot tell whether the message died before reaching the server or the ack died on the way back. Refusing to retry loses messages; retrying can send duplicates.

    We make retries completely safe by combining at-least-once delivery with idempotent deduplication at every hop: 1. Local outbox on the sender: Maya's app saves the message with client_msg_id to a local outbox (a small SQLite table on the phone) before sending, retrying on reconnect until it receives ack {client_msg_id, seq}. 2. Server deduplication on retry: when a frame arrives with retry: true, the message service scans the newest ~200 rows of the conversation (~40 KB in one partition) for a matching (sender_id, client_msg_id). If found, it skips inserting a second row, re-ensures the inbox pointers exist, and re-sends the original ack {client_msg_id, seq}. 3. Recipient deduplication: every client device deduplicates incoming messages by seq and by (sender_id, client_msg_id), so every message is displayed once.

  7. Deep dive 2: routing to online and offline recipients

    Once message seq = 88 is durably written in messages and appended to both Liam's inbox and Maya's inbox (so Maya's laptop also gets her sent message), the message service delivers it to Liam.

    Step 1: Check the Session Registry in Redis

    Redis keys (sharded by user_id):
      sessions:u_740    HASH    { "iphone_1": "gw31", "macbook_2": "gw04" }
      gw:gw31           STRING  "alive"   (15 s TTL, refreshed every 5 s by gateway gw31)
    

    The message service reads sessions:u_740 in one Redis lookup and filters out any gateway whose gw:{id} liveness lease has expired (cached locally on message-service nodes every few seconds). If gateway gw31 crashes hard without running cleanup code, its lease expires within 15 seconds and traffic stops going to it automatically.

    Step 2: Online vs. offline delivery trace

    Case A — Liam's iPhone is online on gw31:
      Message Service --(gRPC)--> Gateway gw31 --(WebSocket)--> Liam's iPhone
                                                                     |
      Message Service <--(gRPC)-- Gateway gw31 <--(delivered: 88)----+  (within 5 s -> two check marks!)
    
    Case B — Liam's iPhone is offline (or has a half-open socket that fails to ack within 5 s):
      Message Service --> Push Service --> APNs / FCM ("New message from Maya")
      (later, Liam exits subway and opens app / reconnects)
      Liam's iPhone ----> GET /v1/sync?cursor=<last_event_id>
                    <---- returns inbox changes from (cursor_time - 10 s) .. now, sorted by seq
      Liam's iPhone deduplicates by seq, renders msg 88, and sends delivered {up_to_seq: 88}
    

    Two critical real-world subtleties here: - Half-open mobile sockets: when a phone walks into an elevator, the radio drops without sending a TCP FIN packet, leaving a half-open socket — a dead connection that the server OS still believes is open. That is why "writing bytes to the socket" does not count as delivered! If Liam's phone does not reply with an application-level delivered frame within 5 seconds, the message service falls back to a push notification. - Push notifications wake the app; inbox delivers the data: Apple Push Notification service (APNs) and Firebase Cloud Messaging (FCM) can throttle, drop, or reorder pushes, and users can disable notifications. Therefore, the push is just a doorbell. On reconnect, the device calls GET /v1/sync?cursor=... to read its inbox from 10 seconds before its last cursor timestamp (absorbing minor clock skew across message-service writers; any duplicate pointers in that 10-second overlap are harmlessly dropped by seq). Devices offline longer than the 30-day inbox TTL perform a fresh conversation-list sync instead.

  8. Deep dive 3: presence without fan-out storms

    Tracking "Online / Last seen" looks simple until you check the multiplication:

    Naive approach 1 (client DB heartbeats):
      3,000,000 connected phones writing "online" every 5 s = 600,000 writes/s to storage!
    
    Naive approach 2 (push to every contact in address book):
      10,000 status changes/s x 200 contacts per user = 2,000,000 fan-out frames/s
      (99% sent to people whose phones are in their pockets or looking at a different chat!)
    
    Our design (connection-derived + viewport subscriptions):
      10,000 status changes/s -> published ONLY to gateways watching that specific user on screen!
    

    We eliminate both bottlenecks with three rules: 1. Derive presence from WebSocket lifecycle, not extra heartbeats: gateways already ping open sockets every 30 seconds. When a user's first device connects to sessions:{user}, the presence service publishes online to Redis channel presence:{user}. 2. 20-second offline grace period: when a user's last device disconnects, the presence service waits 20 seconds before publishing offline and updating last_seen_at. Phones switching from Wi-Fi to cellular reconnect in 2–5 seconds; without this buffer, contacts would watch "Online / Offline" flicker constantly. 3. Subscribe only to the viewport (on-screen contacts): a client sends presence {subscribe: [...]} for at most the 50 contacts currently visible on screen. Each gateway aggregates interest across its local sockets and subscribes once per watched user via Redis sharded pub/sub (SSUBSCRIBE / SPUBLISH, which hashes each channel onto a single Redis shard instead of broadcasting across every cluster node). And gateways verify authorization (existing conversation, not blocked, privacy setting enabled) so strangers cannot stalk a user's online habits.

  9. Scaling, failure handling, and trade-offs

    Scaling & multi-region - Safe gateway deploys without reconnect storms: restarting a gateway drops up to 50,000 sockets. During deploys, a gateway drains gradually over several minutes, and clients reconnect using exponential backoff with jitter — doubling wait time after a failure (1 s, 2 s, 4 s...) plus a random millisecond offset so 50,000 clients do not slam authentication and Redis in the same instant (a thundering herd). - Multi-region chats: users connect to their nearest regional gateway for crisp TLS/ping latency. Each conversation has a single home region (where it was created) that assigns its seq, adding one cross-region backbone hop (~70–200 ms) only when Maya and Liam sit on different continents, while replicating storage asynchronously for disaster recovery.

    Failure handling summary

    Failure scenario Impact How the architecture recovers
    Gateway node crashes ~33,000 sockets drop Clients reconnect to surviving gateways with backoff + jitter; unacked messages resend from local outbox (retry: true); gw:{id} TTL expires in 15 s
    Message service crashes mid-send Sender receives no ack Client retries with same client_msg_id; server finds stored row (or inserts it), repairs inbox pointers, and returns ack
    Cassandra node or full AZ fails 1 of 3 replicas offline Remaining 2 AZs satisfy LOCAL_QUORUM reads/writes and host 60 gateways (capacity for all 3M connections)
    Redis session shard fails over Brief loss of live socket map Affected recipients temporarily appear offline -> messages route safely via inbox + push; gateways re-register live sockets every 60 s
    APNs / FCM outage Wake-up pushes delayed Zero data loss; messages wait durably in messages + inbox and sync the moment the user opens the app

    Core trade-offs recap - WebSockets + HTTPS split: sub-second bidirectional push without polling overhead, trading off stateful gateway connection draining and a Redis session registry. - Wide-column store (messages) + PostgreSQL (users): effortless horizontal write scaling (~88 TB/year) and AZ fault tolerance on sorted conversation buckets, trading off SQL joins for per-query table modeling and Paxos CAS on seq. - At-least-once + idempotency (client_msg_id, seq): zero lost messages over lossy mobile networks, trading off small client/server deduplication logic instead of chasing impossible network-level "exactly-once". - 30-day pointer inbox + viewport presence: cheap append-only reconnect catch-up and 100x lower presence traffic, trading off full resyncs for >30-day inactive devices and a few seconds of presence lag.

Intuition & how it works

Think of a real-time direct-messaging service like an apartment building mailroom paired with a live intercom board. Even though residents move between rooms or step outside to run errands, their shared conversation ledger stays permanently organized in the mailroom: every time Maya sends Liam a note, the clerk stamps it with the next sequential page number (seq) in Maya-and-Liam's notebook, files the note permanently (messages), and drops a lightweight pickup slip into Liam's cubby (inbox). Next, the clerk glances at the live intercom directory (session registry): if Liam's phone currently has an open line (WebSocket) to switchboard gw31, the note is pushed straight to his screen in milliseconds; if Liam is away, the clerk triggers a pocket buzzer (push notification) so Liam's phone fetches its pickup slips from inbox the moment it gets signal back.

A naive design falls apart quickly at 10 million daily users. If 3 million active phones polled an HTTP server every second asking for new messages, the backend would burn millions of empty database queries per second while still feeling sluggish. Worse, ordering messages by phone or server timestamps scrambles fast back-and-forth replies whenever two clocks disagree by 50 milliseconds, and assuming "written to a TCP socket = delivered" silently drops messages into dead mobile connections when a user steps into an elevator.

Walk through a concrete 4-event trace between Maya and Liam (where their thread "dm:u_215:u_740" is currently at seq = 87): 1. Maya sends "Coffee at 3?": her app saves "Coffee at 3?" in a local outbox with a fresh random idempotency key (client_msg_id = "m1", a unique request ID used to catch duplicate retries) and sends it over her open WebSocket (a persistent two-way connection) to gateway gw09. 2. Server assigns seq = 88 and persists: the message service atomically claims seq = 88 in the conversation partition, writes pickup pointers into Maya's and Liam's inbox, and sends ack(m1, seq=88) to Maya (one check mark: sent). 3. Online delivery: Redis shows Liam's phone is connected to gateway gw31; the server pushes seq = 88 through gw31, and Liam's phone answers delivered(up_to_seq=88) within 60 ms (two check marks: delivered). 4. Offline fallback + reconnect: Maya sends "Corner cafe?" (seq = 89) just as Liam enters a subway tunnel; when no delivered ack comes back within 5 seconds, the server sends an APNs/FCM wake-up push, and when Liam regains signal his app calls GET /v1/sync, pulls seq = 89 from his inbox, deduplicates by seq, and displays "Coffee at 3?" then "Corner cafe?" in exact order.

Key trade-offs

  • Wide-column NoSQL (Cassandra/ScyllaDB) vs. sharded SQL for messages. A wide-column store (a distributed database that partitions data by hash key across nodes and sorts rows inside each partition on disk by a clustering key) matches append-heavy chat history (~14,000 writes/s at peak, ~88 TB/year replicated across 3 availability zones) with zero primary-failover downtime, at the cost of no multi-row SQL joins and using a compare-and-swap (CAS) lightweight transaction (an atomic conditional insert backed by Paxos consensus) to assign seq. A sharded SQL cluster (such as MySQL with Vitess or PostgreSQL with Citus) sharded by conversation_id also works well — incrementing conversations.last_seq inside a single-shard SQL transaction — trading automatic leaderless failover for familiar ACID transactions. Both run at massive scale in industry (for example, Discord uses ScyllaDB while Slack uses Vitess-sharded MySQL), while small relational tables (users, devices, blocks) belong in PostgreSQL either way.
  • At-least-once delivery with idempotency vs. exactly-once delivery. Pure network-level "exactly-once" delivery is impossible when acknowledgments can drop, because a sender cannot distinguish a lost message from a lost ack. Choosing at-most-once (never retrying) loses messages, so we retry at every hop and use client_msg_id on the server plus seq deduplication on devices to guarantee each message is displayed once, paying only a small deduplication check on retries.
  • Per-conversation seq via conditional insert vs. in-memory sequencers vs. timestamps. Server or client timestamps suffer from clock skew (slight clock drift between machines) and swap rapid replies. A single in-memory sequencer node per conversation is fast (~1 ms) but requires distributed leases so two servers never hand out the same seq during a failover. Conditional inserts (INSERT ... IF NOT EXISTS) add a few milliseconds for a Paxos round across replicas, which is cheap for 2 human writers in a 1:1 chat (though a 10,000-person group chat would use an owned sequencer or log).
  • WebSockets vs. HTTP long polling or Server-Sent Events (SSE). WebSockets provide low-latency two-way framing over a single TLS connection for sends, pushes, receipts, and typing indicators. Long polling creates repeated HTTP request overhead, and SSE (a one-way HTTP stream from server to client) still requires separate HTTP POST requests for every client send; the trade-off of WebSockets is managing stateful gateways and graceful connection draining.
  • Shared per-user pointer inbox (30-day TTL) vs. per-device delete-on-ack queues. Storing lightweight (conversation_id, seq) pointers in daily partitions that expire automatically avoids per-message deletes, which would otherwise create tombstones (expensive deletion markers that slow down reads in log-structured databases). Each of a user's 4 devices simply advances its own cursor, at the minor cost that devices offline longer than 30 days perform a full conversation resync.
  • Connection-derived viewport presence vs. client heartbeats and full contact fan-out. Deriving online/offline transitions from socket connect/disconnect events (with a 20-second offline grace period) and publishing via sharded pub/sub only to gateways actively displaying that user cuts traffic from ~600,000 heartbeat writes/s and ~2M contact broadcasts/s down to ~10,000 state transitions/s, trading off a few seconds of presence delay.

Common mistakes

  • Ordering messages by client or server timestamps, which reorders fast replies whenever server or phone clocks disagree by milliseconds.
  • Assuming writing to a TCP/WebSocket connection means the user received the message, ignoring half-open sockets (connections that silently broke on mobile radio loss without closing cleanly) instead of requiring an application-level delivered ack.
  • Treating APNs/FCM push notifications as the message transport rather than a wake-up signal; mobile OSes throttle, coalesce, or drop pushes, so the app must always pull authoritative messages from inbox.
  • Unbounded conversation partitions (storing years of messages in a single conversation_id partition without fixed 10,000-message buckets) or partitioning by timestamp alone (which funnels 100% of global writes onto a single hot node).
  • Keeping socket mappings only inside gateway RAM, forcing the message service to broadcast every message across all 90 gateways instead of doing one lookup in a shared session registry.
  • Broadcasting every presence change to all 200 contacts or skipping the offline grace period so contacts flicker online/offline during Wi-Fi-to-cellular switches.
  • Draining gateways abruptly without client exponential backoff and jitter (gradually increasing retry delays with random offsets), triggering reconnect storms that overwhelm authentication servers.
  • Assigning random UUIDs to new 1:1 conversations, allowing two users who message each other simultaneously to create two split chat threads instead of one deterministic "dm:min_id:max_id" thread.

Follow-up questions

  • How can you support seen indicators for read messages without flooding backend servers with per-message status writes? Instead of sending an update per message, clients send a single watermark (a high-water sequence number meaning "every message up to seq = 1240 has been read"): read {conversation_id, up_to_seq: 1240}. Opening an unread thread of 50 messages therefore produces just one frame, debounced on the client to at most one update every ~2 seconds while the chat is visible. On the server, receipts stores a single (delivered_seq, read_seq) row per (conversation_id, user_id) updated monotonically (MAX), forwards one tiny receipt frame to the sender's live sockets, and appends a receipt pointer to the sender's inbox for offline devices. Notably, delivered indicators add almost zero extra traffic because they piggyback directly on the delivered {up_to_seq} acknowledgment already required for reliable delivery.
  • As message volume expands by an order of magnitude, how would you partition chat storage so loading older threads remains fast? Keep the partition/shard key aligned with the single-conversation read pattern — (conversation_id, bucket) where bucket = seq // 10_000 — because sharding by user_id splits one conversation across two shards (requiring double writes or scatter-gather reads) and sharding by time creates a single write-hot newest shard. Using consistent hashing (mapping partition hashes onto a virtual token ring so adding new storage nodes moves only 1/N of keys rather than reshuffling the entire cluster) lets the hot cluster scale horizontally while keeping every history page a single 2 MB sequential partition slice. To control multi-year storage cost, tier buckets older than 1 year into cheaper, high-density cold storage or compressed object-storage archives and record an archived_up_to_bucket pointer on conversations, since almost all reads hit the newest bucket.
  • If conversations use end-to-end encryption, how can users still run full-text searches across their past messages? Under end-to-end encryption (E2EE) (such as the Signal Double Ratchet protocol, where keys live exclusively on user devices so the server handles only opaque ciphertext — encrypted bytes it cannot read), building a plaintext search index on the server is fundamentally impossible without breaking E2EE. Instead, full-text search runs locally on each device: as messages are decrypted, the app indexes them in an on-device full-text engine (for example SQLite FTS5), keeping search sub-millisecond and completely private. To support new phones, the primary device transfers history directly peer-to-peer or uploads an E2EE backup blob encrypted with a user-held passphrase/hardware key to object storage, and the new phone builds its own local FTS5 index after decrypting; server-side "searchable encryption" schemes leak word-frequency and co-occurrence patterns and are generally avoided in secure messengers.

Follow-up questions

Similar questions

More Temporal interview questions

All 2 Temporal questions →