Core Mobile Chat Architecture: Delivery Flow, Storage Design, and Scale

Easy · System Design · Software Engineer · Technical Screen

Prompt

Architect the core messaging backend for a mobile chat service similar to WhatsApp, focusing on the end-to-end journey of sending a message from one user and delivering it to another.

Begin by stating clear engineering assumptions for the open product boundaries: - Direct 1-on-1 threads versus multi-user group threads - Offline delivery expectations, server retention windows for undelivered messages, and whether full cloud history is stored or messages are deleted after delivery - Status indicators (sent, delivered, read), rich media attachments, and single-device versus multi-device accounts - Target traffic volume (daily active users, daily message volume, and peak write throughput) and the ordering guarantee expected within a conversation

Walk through how messages travel in real time when the recipient has an active connection as well as how missed messages synchronize once an offline phone reconnects. Specify the client-facing APIs, database schemas for accounts, threads, and messages, and horizontal scaling strategy—defending where a relational database outperforms a NoSQL store and vice versa based on concrete read and write patterns.

Scope & Expectations

  • Online Push & Offline Synchronization: Client-facing protocols and APIs, persistent connection handling, real-time delivery vs. reconnect catch-up, acknowledgement cursors, retry deduplication, and per-conversation message ordering.
  • Data Modeling & Storage Engine Selection: Schemas and primary/partition keys for users, conversations, and messages grounded in dominant access patterns, paired with an explicit trade-off analysis of relational vs. NoSQL storage across scale regimes.
  • Horizontal Scale & Fault Recovery: Scaling stateful connection gateways and routing messages to the right host, sharding message storage while preventing hot partitions, and surviving gateway, worker, or storage node failures.

Step-by-step walkthrough

  1. Clarify scope, guarantees, and assumptions

    A messaging system's schema and network protocol depend heavily on what "delivered" and "ordered" mean, so start by turning the open product boundaries into explicit engineering commitments.

    Scope decisions

    • Chat topology: One-to-one text chats for the core design, while keying everything by conversation_id (rather than recipient_id) so group chats fit cleanly later.
    • Offline delivery and history: Messages sent while the recipient has no signal must never be lost. The server stores full chat history (moving messages older than 90 days to cheaper cold storage) so reinstalling the app restores past conversations. (In the follow-ups, we examine how end-to-end encryption shifts this to store-until-delivered.)
    • Receipts, media, and devices: Sent (one tick), delivered (two ticks), and read receipts are included. Media attachments upload directly to object storage (S3/GCS), and the message body carries only a media_id. Assume one active device per user initially; multi-device sync is addressed in the follow-ups.
    • Ordering guarantee: Within any single conversation, every participant sees messages in the exact same total order, and messages from the same sender always appear in the order they were sent. Ordering across separate conversations is not required.

    Scale and non-functional targets

    • Traffic: 500 million daily active users (DAU), each sending an average of 40 messages per day.
    • Durability: Once the server returns a "sent" acknowledgement (one tick), that message is never lost, even if a server crashes immediately afterward.
    • Idempotency (no duplicates): Mobile networks drop packets constantly, forcing clients and servers to retry, yet recipients must never see duplicate messages.
    • Latency: Under 500 ms at p99 server-side for online recipients in the same region.
  2. Estimate scale and separate the two scaling axes

    Let us run the numbers to see what grows with connected users versus what grows with messages sent:

    1. Message throughput
       Daily volume        = 500M DAU * 40 messages = 20B messages/day
       Average write rate  = 20,000,000,000 / 86,400 s = ~231,500 messages/s
       Peak rate (3x avg)  = ~700,000 messages/s
    
    2. Message storage (full history)
       Average row size    = ~100 B UTF-8 text + ~100 B metadata (IDs, seq, timestamps) = 200 B
       Daily logical data  = 20B * 200 B = 4 TB/day  (12 TB/day raw across 3 replicas)
       Annual data         = 4 TB * 365 = ~1.46 PB/year logical (~4.4 PB/year raw before compression)
    
    3. Persistent connections
       Peak concurrent online (30% of DAU) = 150M open connections
       Capacity per gateway (~12 KB RAM/socket) = 500,000 idle connections on a 16-32 GB host
       Gateway fleet       = 150M / 500,000 = 300 hosts (~450 hosts with zone-failure headroom)
       Heartbeats (1 / 30 s) = 150M / 30 s = 5M pings/s total (~16.7k/s handled locally per gateway)
    
    4. Session routing registry (maps online user_id -> gateway host)
       Memory footprint    = 150M entries * ~100 B = ~15 GB in RAM
       Write rate          = 500M users * ~20 reconnects/day * 2 (connect + disconnect) / 86,400 s
                           = ~231,000 writes/s
       Read rate           = 1 lookup per message delivery = ~700,000 reads/s at peak
    

    What these numbers tell us: - Per-connection state (open sockets and the 15 GB session registry) scales with concurrent online users (150M) and requires zero disk I/O. - Per-message data scales with write rate (700k/s) and cumulative retention (~1.5 PB/year), requiring horizontally partitioned storage and cold tiering for messages older than 90 days. Separating stateless message workers, connection gateways, and message storage lets each tier scale independently.

  3. Client-facing API and connection model

    Standard HTTP request/response forces a phone to poll ("any new messages yet?") every few seconds, wasting battery and adding latency. Instead, each online phone opens one long-lived WebSocket over TLS—a persistent, two-way network tunnel that lets the server push frames to the phone the instant a message arrives. Every 30 seconds the phone sends a tiny ping frame (NAT keep-alive) so mobile carrier firewalls do not close an idle tunnel. When the OS suspends the app in the background and closes the socket, the server falls back to Apple Push Notification service (APNs) or Firebase Cloud Messaging (FCM) to wake the device.

    WebSocket Tunnel: WSS /v1/connect   (Headers: Authorization: Bearer <jwt>, X-Device-Id)
    
      Client -> Server frames:
        send       { client_msg_id: "m901...", conversation_id: 7420, type: "text", body: "Landed at Gate B4" }
        delivered  { conversation_id: 7420, up_to_seq: 61 }     <- batched cursor ack
        read       { conversation_id: 7420, up_to_seq: 61 }     <- batched read cursor
        sync       { }                                          <- sent right after every reconnect
        ping       { }                                          <- every 30 s keep-alive
    
      Server -> Client frames:
        send_ack   { client_msg_id: "m901...", conversation_id: 7420, seq: 62, server_ts: 1764500100 }
        send_error { client_msg_id: "m901...", code: "RATE_LIMITED" | "NOT_MEMBER" | "RETRY" }
        message    { conversation_id: 7420, seq: 62, client_msg_id: "m901...", sender_id: 305,
                     type: "text", body: "Landed at Gate B4", server_ts: 1764500100 }
        receipt    { conversation_id: 7420, user_id: 418, delivered_up_to: 62, read_up_to: 60 }
        sync_done  { }
    
    Companion HTTPS Endpoints (stateless request/response):
      POST /v1/conversations                               { peer_user_id } -> { conversation_id }
      GET  /v1/conversations?limit=50&cursor=...           -> inbox list with last message & unread count
      GET  /v1/conversations/{id}/messages?before_seq=300&limit=50  -> scroll upward in history
      POST /v1/media                                       -> { media_id, presigned_upload_url }
    

    Two design details carry huge weight here: 1. client_msg_id is an idempotency key—a unique identifier generated on the phone and saved to the phone's local SQLite outbox before the first send attempt. Every retry reuses the exact same client_msg_id so the server can detect retries instead of inserting duplicates. 2. Receipts are cursors (up_to_seq), not per-message rows: Saying "User 418 received everything up to seq = 62" acknowledges an entire offline burst in one network frame and stores just two integers (delivered_seq, read_seq) per user per conversation instead of updating 20 billion receipt rows per day.

  4. Schema design, access patterns, and SQL vs. NoSQL

    Always list the dominant reads and writes before picking a database engine or primary key:

    Dominant Access Pattern                        Peak Rate         Lookup Key Needed
    ---------------------------------------------  ----------------  ----------------------------------------
    1. Append a new message                        ~700k writes/s    (conversation_id, seq)
    2. Deduplicate a retried client_msg_id         ~700k ops/s       (conversation_id, client_msg_id)
    3. Sync missed messages after seq S            every reconnect   (conversation_id, seq > S) range scan
    4. Scroll back 50 messages before seq S        every chat open   (conversation_id, seq < S) reverse scan
    5. Find all chats with undelivered messages    every reconnect   (user_id) single-partition scan
    6. Advance delivered / read cursors            ~1M writes/s      (user_id, conversation_id)
    7. Look up user by phone / ensure 1 direct chat contact sync     phone_e164 UNIQUE; (user_lo, user_hi) UNIQUE
    

    No single database is best at both #7 (secondary unique constraints and multi-row transactions) and #1–#6 (700k/s append-heavy key-range operations across petabytes). We split storage by access pattern:

    1. Relational DB (sharded PostgreSQL) for identity and conversation metadata (~500 GB)

    users                 user_id BIGINT PK, phone_e164 TEXT UNIQUE, display_name, created_at
    devices               device_id UUID PK, user_id BIGINT FK, push_platform, push_token, updated_at
    conversations         conversation_id BIGINT PK, kind ('direct' | 'group'),
                          user_lo BIGINT, user_hi BIGINT, created_at,
                          UNIQUE (user_lo, user_hi)   -- smaller ID first: guarantees at most one 1:1 chat!
    conversation_members  (conversation_id, user_id) PK, role, joined_at
    

    2. Wide-column NoSQL store (ScyllaDB / Cassandra) for messages and inbox state (~1.5 PB/year)

    A wide-column store organizes rows into partitions (deciding which storage servers hold the data via a partition key) and keeps rows physically sorted on disk within each partition by a clustering key, making range scans blazingly fast.

    messages
      partition key:  (conversation_id, bucket)     where bucket = seq // 10000 (integer division)
      clustering key: seq ASC                       physically sorts messages 1, 2, 3... on disk!
      columns:        client_msg_id, sender_id, type, body_or_media_id, server_ts
    
    conversation_heads
      partition key:  conversation_id
      columns:        last_seq                      tracks highest assigned seq so active bucket is known
    
    message_dedupe
      partition key:  (conversation_id, client_msg_id)
      columns:        seq                           TTL = 7 days (covers all client retry windows)
    
    user_conversations
      partition key:  user_id
      clustering key: conversation_id
      columns:        peer_id, last_message_seq, last_message_at, delivered_seq, read_seq, muted
    

    See how cleanly a concrete 3-message conversation (conversation_id = 7420 between User 305 and User 418) sits on disk after User 305 sends message 1, User 418 replies with 2, and User 305 sends message 3 while User 418 is offline:

    messages  [partition = (7420, bucket 0)]
      seq | sender_id | client_msg_id | body
      ----+-----------+---------------+------------------------
        1 |       305 | "m701..."     | "Flight just landed"
        2 |       418 | "m702..."     | "Awesome, baggage claim?"
        3 |       305 | "m703..."     | "Meet at Door 4"
    
    user_conversations  [partition = user_id 418]
      conversation_id | peer_id | last_message_seq | delivered_seq | read_seq
      ----------------+---------+------------------+---------------+---------
                 7420 |     305 |                3 |             2 |        2
      -> Unread count = last_message_seq - read_seq = 3 - 2 = 1 (zero COUNT(*) queries!)
      -> Reconnect sync sees last_message_seq (3) > delivered_seq (2) -> fetches seq > 2!
    

    (Note: Sending a message also sets the sender's own delivered_seq and read_seq to at least that seq, so in a 1-to-1 chat every message above read_seq came from the peer, making last_message_seq - read_seq exact aside from a sub-second race when both type simultaneously.)

    Why Relational vs. Wide-Column NoSQL here—and when Relational wins even for messages: - Identity & membership -> Relational: Phone numbers require strict global uniqueness (UNIQUE (phone_e164)), creating a direct chat requires atomic deduplication (UNIQUE (user_lo, user_hi)), and dataset size (500M * 1 KB = 500 GB) fits comfortably in a small sharded Postgres cluster. Rebuilding secondary unique indexes manually on top of NoSQL invites bugs. - Messages & inboxes -> Wide-Column at 500M DAU: Every query supplies conversation_id or user_id with zero joins; bucketing (seq // 10000) caps every partition near 10,000 * 200 B = 2 MB forever; LSM-tree storage absorbs 700k writes/s sequentially; and built-in TTL expires message_dedupe rows automatically. The trade-off is the lack of multi-partition ACID transactions, requiring conditional writes for seq assignment. - When Relational IS better even for messages: At smaller scale—say 10M DAU (~14k peak messages/s)—a sharded PostgreSQL cluster keyed by conversation_id is dramatically simpler to operate and makes sequencing trivial in a single ACID transaction (UPDATE conversations SET last_seq = last_seq + 1 WHERE conversation_id = $1 RETURNING last_seq followed by INSERT INTO messages). Switch to wide-column storage when petabyte-scale resharding and multi-zone operational overhead outweigh transactional convenience.

  5. High-level architecture

     Phone A (Sender)                                                       Phone B (Recipient)
        | WSS                                                                     ^ WSS
        v                                                                         |
     L4 Load Balancer ---> Gateway G1 ----+                        +---> Gateway G2
                                          | 1. forward send        | 5. push message (RPC)
                                          v                        |
                                Message Service (stateless) -------+
                                  |               |                |
             2. dedupe + seq +    |               | 4. lookup B    | 5'. if B offline
                quorum insert +   |               v                v
                update inboxes    |       Session Registry     Push Service ---> APNs / FCM
                                  v       (in-memory KV:
                         Wide-Column DB    user_id -> G2, conn_id)
                          - messages
                          - message_dedupe          Relational DB (users, conversations)
                          - conversation_heads      Object Storage (encrypted media blobs)
                          - user_conversations
                                  |
                                  +---> Change Stream ---> Repair Worker (finishes interrupted inbox updates)
    
    • Gateways (G1..G450) terminate TLS/WebSockets, run 30-second heartbeats, and hold zero message state—losing a gateway drops sockets, never data.
    • Session Registry is a ~15 GB sharded in-memory store (Redis) mapping each connected user_id to (gateway_id, conn_id).
    • Message Service is stateless and orchestrates membership checks (cached), sequence assignment, durable storage, inbox updates, and live routing.
    • Repair Worker tails the message store's change stream so if a Message Service node crashes right after writing a message (before updating user_conversations), the inbox index still catches up within seconds.
  6. Online push and offline catch-up flows

    ONLINE PATH                                        OFFLINE + RECONNECT SYNC PATH
    Phone A     G1    MsgSvc    DB    G2    Phone B    Phone B (later)   G3    MsgSvc    DB
      |--send-->|       |        |     |       |          |--connect---->|       |        |
      |         |--rpc->|        |     |       |          |--sync------->|------►|        |
      |         |       |--write>|     |       |          |              |       |--scan->| user_conversations
      |         |       |<-quorum|     |       |          |              |       |--read->| messages (seq > 2)
      |<--send_ack(1✓)--|        |     |       |          |<-----message(seq=3)--|        |
      |         |       |----push----->|--msg->|          |<-----sync_done-------|        |
      |         |       |<---delivered(seq)----|          |------delivered(3)--->|------►| update cursor
      |<--receipt(2✓)---|        |     |       |          |   (sender gets 2✓ live or on next sync)
    

    When Recipient B is online: 1. Phone A saves the outgoing message in its local SQLite outbox (showing a clock icon) and sends send {client_msg_id, conversation_id, body} over WebSocket to G1. For a single conversation on one socket, G1 forwards one send at a time so A's own messages stay strictly in send order. 2. Message Service verifies A belongs to conversation_id, assigns the next seq idempotently (next step), writes the message with a quorum write—meaning at least 2 of 3 storage replicas confirm the data is safely on disk before returning—and advances last_message_seq on both A's and B's user_conversations rows. 3. Only after the durable write succeeds does Message Service send send_ack {seq} back to A (clock becomes one tick). 4. Message Service looks up B in the Session Registry (G2), makes an internal RPC to G2, and G2 pushes message {seq} down B's WebSocket. 5. Phone B writes (conversation_id, seq) to its local database and replies delivered {up_to_seq: seq}. Message Service raises B's delivered_seq and pushes receipt to A (two ticks). Opening the chat screen sends read {up_to_seq: seq} the exact same way.

    When Recipient B is offline (or just dropped into an elevator): - At step 4, either the Session Registry has no entry for B, or G2 reports the socket just closed. Because step 2 already persisted the message and bumped B's last_message_seq, nothing is lost; Message Service triggers an APNs/FCM push notification. - When B regains connectivity (seconds or days later), Phone B connects to any gateway G3 and immediately sends sync. Message Service reads B's single user_conversations partition, finds every chat where last_message_seq > delivered_seq, streams the missing messages rows in seq order (100 per batch), and finishes with sync_done. - Overlap and gap safety: If a live push frame arrives while sync is mid-stream, Phone B keys local storage by (conversation_id, seq), turning the duplicate arrival into a harmless overwrite. And Phone B only advances delivered {up_to_seq} to the highest contiguous seq with no missing numbers below it; if push delivers seq = 64 while Phone B only has up to 62, it fetches seq = 63 before acknowledging 64.

  7. Deep dive: acknowledgements, retries, deduplication, and ordering

    Why do duplicates and out-of-order bugs happen so easily in chat systems? Suppose Phone A sends "Send invoice #12", the server writes it at seq = 62, and Phone A's cellular tunnel drops 5 ms before send_ack arrives. Phone A must retry—it cannot tell whether the packet died before or after reaching the database. And if we ordered messages by phone timestamps instead of server sequence numbers, a phone whose clock is 10 seconds fast would display answers above questions!

    To make retries 100% duplicate-free—even if a handler crashes mid-flight and 10,000 newer messages arrive before Phone A reconnects—we claim the idempotency record in message_dedupe before inserting into messages, using conditional writes (atomic compare-and-set operations such as INSERT IF NOT EXISTS that execute safely across replicas on a single partition):

    def store_message_once(store, msg) -> int:
        """Assign a unique per-conversation seq to msg and persist it exactly once."""
        conv_id = msg.conversation_id
    
        while True:
            # Phase 1: Check or reserve (conv_id, client_msg_id) -> candidate_seq in message_dedupe.
            head_seq = store.get_head_seq(conv_id)  # 0 if conversation has no messages yet
            reserved_seq = store.insert_dedupe_if_absent(
                conv_id,
                msg.client_msg_id,
                candidate_seq=head_seq + 1,
                ttl_days=7,
            )
    
            # Phase 2: Try to claim (conv_id, bucket, reserved_seq) in the messages table.
            bucket = reserved_seq // 10000
            inserted, existing_msg = store.insert_message_if_absent(
                conv_id, bucket, reserved_seq, msg
            )
    
            if inserted or existing_msg.client_msg_id == msg.client_msg_id:
                # Either we just won reserved_seq, OR an earlier attempt of THIS exact
                # client_msg_id already wrote it here! Monotonically advance head_seq.
                store.raise_head_seq(conv_id, reserved_seq)
                return reserved_seq
    
            # Another concurrent sender won reserved_seq before us (or after our earlier attempt
            # crashed between Phase 1 and Phase 2). Refresh head_seq and CAS our dedupe pointer.
            latest_head = max(head_seq, reserved_seq, store.get_head_seq(conv_id))
            store.compare_and_swap_dedupe(
                conv_id,
                msg.client_msg_id,
                expected_seq=reserved_seq,
                new_seq=latest_head + 1,
            )
    

    Trace why every failure interleaving is completely safe: - Normal send (99.99% of 1:1 traffic): Two people in a direct chat rarely press Send within the same 5 milliseconds, so Phase 1 reserves head_seq + 1, Phase 2 inserts messages[head_seq + 1], and the loop finishes in one pass. - Retry after server persisted the message (even hours and thousands of messages later): insert_dedupe_if_absent returns the original reserved_seq (say 62). Phase 2 checks messages[62], sees existing_msg.client_msg_id == msg.client_msg_id, and immediately returns 62—zero chance of a duplicate at seq = 500! - Crash right between Phase 1 and Phase 2: If nobody else sent a message yet, the retry finishes Phase 2 at 62. If Peer B sent 62 in the meantime, Phase 2 sees B's client_msg_id != msg.client_msg_id, advances the dedupe reservation to 63, and inserts cleanly at 63. - Monotonic index updates: last_message_seq, delivered_seq, and read_seq only ever move upward (SET col = GREATEST(col, :new_seq)), so out-of-order retries or background repair workers can never roll an inbox cursor backward.

  8. Scaling connection routing, hot partitions, and failure handling

    Scaling the connection layer and routing

    • Stateless gateways behind L4 load balancing: Any phone can land on any of the ~450 gateway servers. On connect, Gateway G2 writes sess:{user_id} -> {gateway: "G2", conn_id: "c_99"} to the sharded Redis Session Registry. On disconnect, G2 deletes the key only if conn_id == "c_99" (via a tiny Lua check), preventing a slow disconnect notification on old G1 from accidentally wiping out a fresh connection that Phone B already opened on G3!
    • Why Session Registry beats Pub/Sub or sticky hashing: Creating 150M per-user Pub/Sub topics causes massive broker subscription churn whenever mobile radios flap, while consistent-hashing users directly to gateways forces mass reconnections whenever a gateway scales up or down. One in-memory Redis lookup per message (< 0.5 ms) decouples routing cleanly.

    Eliminating storage hot partitions and reconnect storms

    • Decades-long conversations: Partitioning by (conversation_id, seq // 10000) caps every partition at ~2 MB while keeping recent reads inside 1–2 partitions.
    • Automated bots / business accounts: Humans cannot type fast enough to overload a partition, so enforce per-sender rate limits (e.g., 20 msgs/s burst, 5 msgs/s sustained). For verified support accounts with millions of chats, split user_conversations across 16 sub-partitions ((user_id, conversation_id % 16)).
    • Gateway crash reconnect storms: If a gateway holding 500,000 sockets crashes, half a million phones trying to reconnect and run sync in the same second would hammer gateways and storage. Clients apply exponential backoff with random jitter—doubling wait delays on failure plus a random 0–30 second offset—smoothing 500,000 syncs down to ~17,000/s across the remaining 449 gateways.

    Failure handling summary

    Component Failure                   System Behavior & Recovery
    ----------------------------------  -------------------------------------------------------------------
    Gateway host crashes                500k clients reconnect with jitter to healthy gateways and send sync;
                                        stale registry lookups get RPC refusal -> fallback to push + sync.
    Message Service crashes mid-send    No send_ack -> client retries same client_msg_id -> gets same seq;
                                        Change-Stream Repair Worker completes any missed inbox index updates.
    Wide-column storage node dies       3 replicas with quorum (2 of 3) reads & writes -> zero downtime,
                                        and every acknowledged message still survives on >= 1 live replica.
    Session Registry shard fails        Lookups miss -> recipients treated as offline (push + sync still work)
                                        while gateways re-publish active conn_ids on their next 30 s ping.
    
  9. Summary of key trade-offs

    • Long-lived WebSockets + Session Registry vs. HTTP polling: Achieves sub-second push delivery and tiny framing overhead, at the cost of managing 450 stateful-socket gateway servers and a 15 GB routing cache.
    • Acknowledge after quorum disk write vs. acknowledge in gateway memory: Adds a few milliseconds to send_ack latency, but guarantees that one tick truly means "never lost."
    • Server-assigned seq via conditional writes vs. client timestamps: Costs atomic per-partition coordination on write, but guarantees every participant sees one identical order and enables gap-free seq > delivered_seq sync cursors.
    • Cursor receipts (up_to_seq) vs. per-message status rows: Compresses receipt storage and network chatter by orders of magnitude, trading away the ability to mark message 62 "read" while leaving message 61 "unread."
    • Hybrid Relational + Wide-Column storage vs. single database: Uses PostgreSQL where uniqueness and transactions matter (users, conversations) and wide-column storage where 700k/s append throughput and petabyte partitioning dominate (messages, user_conversations), accepting two storage engines to run in exchange for clean scaling.

Intuition & how it works

Think of a messaging service like a certified mailroom connected to pneumatic desk tubes: when Maya sends a note to Liam, the mailroom first stamps it with the next sequential ticket number for their chat and locks a photocopy in a fireproof ledger before handing Maya her "sent" receipt; then, if Liam is sitting at his desk (an open WebSocket—a persistent two-way network tunnel), the mailroom shoots the note straight down his tube in milliseconds, and if Liam is away, the note simply waits safely in the ledger until Liam walks back in and asks for "every ticket number higher than the last one I received."

A naive design—forwarding messages straight from Maya's socket to Liam's socket in memory, ordering chats by phone timestamps, and retrying timeouts without tracking message IDs—breaks down immediately on mobile networks. Phones drop connections in elevators and subways constantly, so in-memory forwarding loses messages whenever Liam or a server blips; skewed phone clocks make replies appear above questions; and blind retries insert embarrassing duplicate messages whenever a "sent" confirmation gets lost on the way back to Maya.

Trace a tiny 3-event example in conversation 7420 (currently at sequence seq = 2): 1. Idempotent durable send: Maya's phone generates a unique client_msg_id = "m703" in its local outbox and sends "Meet at Door 4". The server reserves "m703" -> seq = 3, writes (conv = 7420, seq = 3) across a quorum (at least 2 of 3 database replicas), sets last_message_seq = 3 on both users' inbox rows, and sends send_ack(seq = 3) (one tick) back to Maya. If Maya's connection dropped right before receiving send_ack, her retry re-sends "m703", matches seq = 3, and never creates a seq = 4 copy. 2. Offline gap: Liam's phone is in airplane mode, so looking up Liam in the in-memory Session Registry (which maps each online user to the gateway server holding their socket) returns nothing; the server fires a mobile push wake-up, and the message waits safely on disk at seq = 3. 3. Cursor resync: Ten minutes later, Liam reconnects to any gateway and sends sync. The server reads Liam's inbox partition, sees last_message_seq (3) > delivered_seq (2), streams seq = 3, and receives Liam's delivered(up_to_seq = 3)—raising Liam's cursor to 3 and sending Maya her second tick.

Key trade-offs

  • Acknowledge after durable quorum write vs. acknowledge on socket receipt. Waiting for 2 of 3 storage replicas to persist a message before returning send_ack adds ~5–15 ms to the send path, but makes "one tick means never lost" strictly true. Acknowledging from gateway RAM is slightly faster and silently loses acknowledged messages whenever a host crashes.
  • Server-assigned seq via conditional writes vs. client or server timestamps. Device clocks drift by seconds or minutes, and wall-clock timestamps across servers cannot guarantee gap-free ranges. Assigning a monotonic integer seq per conversation via conditional writes (atomic INSERT IF NOT EXISTS operations on a partition) costs coordination on the write path, but guarantees identical ordering on every phone and exact seq > delivered_seq catch-up scans.
  • Session Registry lookup vs. per-user Pub/Sub vs. user-hashed gateways. A sharded in-memory Session Registry costs one < 0.5 ms lookup per delivery while letting any phone connect to any stateless gateway. Per-user Pub/Sub pushes 150 million rapidly churning subscriptions into a broker, while hashing users to fixed gateways forces mass reconnections whenever gateways scale or deploy.
  • Relational vs. Wide-Column NoSQL storage by access pattern. Identity and conversation setup (users, conversations) belong in a sharded relational database (PostgreSQL) because they are small (~500 GB) and rely on unique secondary indexes (phone_e164) and atomic pair constraints (UNIQUE(user_lo, user_hi)). Messages and per-user inboxes (700k writes/s, ~1.5 PB/year, pure key-and-range scans with zero joins) fit a wide-column store (ScyllaDB/Cassandra), which partitions and expires rows natively—though for smaller apps (< 10M DAU), keeping messages in sharded PostgreSQL is simpler and gives seq increments via ordinary ACID transactions.
  • Cursor-based receipts (up_to_seq) vs. per-message receipt rows. Storing just delivered_seq and read_seq per user per conversation turns a 50-message reconnect ack into one small frame and one integer update, trading away per-message selective read states that chat UIs do not need anyway.
  • Full server history with cold tiering vs. store-until-delivered. Retaining full history makes restoring chats on a new phone seamless at the cost of ~1.5 PB/year (mitigated by tiering messages older than 90 days to compressed cold storage), whereas deleting upon delivery minimizes server footprint and privacy surface.

Common mistakes

  • Sending send_ack before durable storage, or marking a message "delivered" the moment bytes are written to a TCP socket rather than waiting for an application-level delivered ack from the recipient's phone.
  • Sorting messages by client_ts or multi-server wall clocks, causing two participants in the same chat to see interleaved replies in different orders and causing time-based sync cursors (ts > last_seen_ts) to skip slightly delayed writes.
  • Retrying sends without a client-generated client_msg_id, or recording the deduplication key after inserting the message row without crash recovery (which produces duplicates if the worker crashes in between and retries arrive later).
  • Partitioning messages by message_id or timestamp alone, scattering a single conversation across every storage node so opening one chat requires querying the entire cluster.
  • Partitioning messages by conversation_id alone without bucketing, letting multi-year chats grow into huge, unbalancable partitions instead of capping partitions at ~2 MB via (conversation_id, seq // 10000).
  • Storing unsent messages inside Gateway memory, turning stateless connection proxies into single points of data loss.
  • Forgetting exponential backoff and jitter on client reconnects, so a crashed gateway drops 500,000 phones that all slam healthy gateways and run sync in the exact same millisecond.

Follow-up questions

  • What schema and message-routing changes are required to support large multi-participant group conversations? In the schema, a group is simply a conversations row with kind = 'group' and membership rows in conversation_members(conversation_id, user_id), while the group's messages are still written once per (conversation_id, bucket, seq) in messages. On the send path, the Message Service fetches cached member IDs, batches Session Registry lookups, sends one batched RPC per gateway holding online members, and triggers push notifications for offline members. For small groups (say up to 100 members), we still update each member's user_conversations row on write (fan-out on write); for large groups (hundreds or thousands of members) where writing thousands of inbox rows per message is expensive and concurrent senders contend on seq, we route each large group by consistent hashing to a single leased sequencer node that assigns seq in memory and switch inboxes to fan-out on read (checking active group heads during sync).
  • How does your architecture evolve when a single account stays logged in across multiple phones or laptops simultaneously, with every linked client receiving each message without duplicates? Expand the Session Registry value under sess:{user_id} into a map of {device_id -> (gateway_id, conn_id)} so every send fans out both to all of the recipient's registered devices and to the sender's own other devices (so sent messages appear on the sender's laptop too). Move delivered_seq out of user_conversations into a per-device cursor table device_cursors(user_id, device_id, conversation_id -> delivered_seq) so an offline tablet still syncs every message that the user's phone already received, while keeping read_seq at the user_id level so reading a chat on the phone clears unread badges everywhere. Combining at-least-once cursor sync with local client storage keyed by (conversation_id, seq) gives each device exact, duplicate-free delivery.
  • Once end-to-end encryption is enabled, which metadata fields remain visible to the backend for indexing, and how do storage and delivery change? Under end-to-end encryption (E2EE)—where messages are encrypted on the sender's device into unreadable ciphertext using recipient device keys (such as the Signal Double Ratchet protocol)—the server can still read and index routing metadata (conversation_id, sender_id, recipient device_id, seq, client_msg_id, timestamps, payload size, and public pre-key bundles in a Key Directory), leaving sequencing, deduplication, and WebSocket routing intact. However, because each recipient device has its own cryptographic session, the sender uploads a separate encrypted envelope per target device into a per-device delivery queue, and the server deletes each envelope as soon as that device sends delivered (since keeping undecryptable history on the server cannot restore a lost phone anyway; history recovery moves to client-encrypted cloud backups or device-to-device transfer). Server-side full-text search, link previews, and push-notification text rendering also move entirely onto the client devices.

Follow-up questions

Similar questions

More Fivetran interview questions

All 2 Fivetran questions →