One-Time-View Multi-Recipient Messaging Service

Medium · System Design · Software Engineer · Onsite

Prompt

Architect a high-throughput ephemeral messaging service where an author can address a single outgoing note to many recipients at once — not by creating a shared group conversation, but by delivering an isolated, one-time-view copy to each recipient independently.

Your design must uphold these core product guarantees at scale:

  • Multi-target dispatch with per-recipient isolation: One send request delivers separate copies to every chosen recipient; when one person opens their copy, every other recipient's unread delivery remains intact.
  • Strict single-view lifecycle: Each recipient can reveal their copy only once, after which that recipient's payload is erased and permanently unretrievable (for instance, sending "Vault PIN: 7381" to three teammates u_10, u_24, and u_39 lets each teammate view it once independently before their copy self-destructs).
  • Real-time, offline, and retry resilience: Support instant push to active sessions, queued delivery for disconnected devices, safe handling of dropped mobile connections and client retries, and large-scale traffic volumes.

Scope & Expectations

  • APIs, data model, and architecture: Specify external endpoints, sharded storage tables, and end-to-end components separating lightweight inbox metadata from confidential message bodies and media.
  • Fan-out and atomic single-view enforcement: Detail how multi-recipient dispatch scales across shards and how concurrent open attempts across devices or failovers are serialized so a delivery never opens twice.
  • Erasure, retention, and media lifecycle: Explain both immediate logical invalidation and bounded physical byte cleanup across primary tables, replicas, logs, and shared attachments.
  • Partitioning, scaling, and consistency trade-offs: Justify shard keys, connection load balancing, retry semantics, and where the system prioritizes linearizable consistency over availability.

Step-by-step walkthrough

  1. Clarify requirements and assumptions

    When an author addresses an ephemeral note to several people in one action, the backend materializes isolated per-target delivery records rather than a shared thread. Spend the first few minutes clarifying the exact guarantees behind "single view" and "erased", because those rules dictate our storage engine, replication topology, and HTTP verbs.

    Functional requirements

    • Isolated multi-target dispatch: An author dispatches a text note (optionally carrying media attachments) to 1..1,000 targets (3 on average) in one request. Recipients never see one another, and Maya opening her delivery leaves Liam's unread delivery untouched.
    • Envelope vs. body separation: Before opening, a recipient's inbox lists only a content-free envelope (sender_id, sent_at, media_kind, size_bytes, expires_at). Tapping Open reveals the confidential body once.
    • Permanent unavailability after open: Once revealed, the backend never releases that recipient's copy again. Unopened deliveries expire automatically after 30 days.
    • Online & offline delivery: Connected clients receive the envelope live; disconnected devices receive a content-free OS push alert ("New note from Priya") and pull the envelope upon reconnecting. Authors see per-target status (PENDING | DELIVERED | OPENED | EXPIRED | REVOKED) without being able to re-read sent text.

    Clarifying edge cases and non-functional guarantees

    • Hard read-once invariant: Concurrent taps from a user's phone and laptop, network retries, worker crashes, or database primary failovers must never allow two distinct opens of the same delivery (linearizable consistency per delivery — operations behave as if executed atomically in a single strict order).
    • Lost response on open (60 s retry window): If a user taps Open and mobile Wi-Fi drops before the HTTP response arrives, the same device retrying with the same open_request_id within 60 seconds receives the body for that single tap; after 60 s, the body is purged. (A 0 s strict at-most-once mode can be toggled for high-security orgs.)
    • Payload limits: Text up to 4 KB; media attachments (images, short clips) up to 10 MB, uploaded prior to send.
    • Client-side boundary: No server can stop someone pointing a second camera at their screen. Our server guarantees single release of the payload, while official apps hold decrypted bytes in RAM only (never disk cache) and enable OS screenshot-blocking flags (FLAG_SECURE on Android, screen-capture observers on iOS).
    • Latency & erasure bounds: Online envelope notification p99 < 1 s intra-region; body unreadable via SQL within ~60 s of open, with explicit, honest bounds for database logs and backups.
  2. Back-of-the-envelope numbers

    1. Traffic & connections
       100M daily active users × 10 sends/day = 1B sends/day
       Send rate:     1B / 86,400 s ≈ 11,600 sends/s avg, ~35,000 sends/s at 3x peak
       Deliveries:    3 recipients/send avg -> 3B deliveries/day (~34,700/s avg, ~104,000/s peak)
       Opens (90%):   2.7B opens/day (~31,300/s avg, ~94,000/s peak)
       Live sockets:  30% of DAU online at peak = 30M concurrent WebSocket connections
    
    2. Delivery database storage (weekly partitions dropped once all rows pass 30-day TTL -> ~33.5d avg)
       Metadata rows: 3B/day × 33.5 days ≈ 100B rows × 200 B       = ~20 TB
       Unread text:   10% never opened × 3B/day × 30d × 1 KB avg   =  ~9 TB
       In-flight text (opened within ~12h on average):             = ~1.5 TB
       Total primary with B-tree indexes ≈ 45 TB (x3 replicas ≈ 135 TB; ~350 GB/shard across 128 shards)
    
    3. Database write throughput
       Lifecycle writes per delivery: insert + delivered_ack + open + purge ≈ 4 writes
       3B × 4 = 12B writes/day ≈ 139,000 writes/s avg, ~417,000 writes/s peak
       Across 128 shards: ~3,300 writes/s per shard primary at peak
    
    4. Attachment object storage (10% of sends carry a 300 KB image/clip -> 30 TB/day new media)
       With 3 recipients opening independently at 90%, P(>= 1 never opens) = 1 - 0.9^3 ≈ 27.1%
       Shared once-per-message storage: (0.271 × 30 TB × 30d) + ~11 TB active ≈ 255 TB live
       (Duplicating media per recipient would triple this to ~800 TB and 1,000x on max fan-out!)
    

    Three architectural conclusions from the math:

    1. Writes and deletes dominate reads: Every delivery is written ~4 times and read at most once, so read-through body caches buy nothing and create extra copies to erase.
    2. Copy small text per recipient; share encrypted media blobs: Copying 4 KB text across 1,000 recipients is at most 4 MB and makes deleting one recipient's text completely self-contained, whereas 10 MB attachments must be stored once in object storage and deleted when the last recipient finishes.
    3. Single-row sharding eliminates distributed transactions: Keying deliveries by (recipient_id, message_id) keeps every inbox list and every read-once check inside a single row on a single shard.
  3. API design

    All endpoints authenticate the caller via bearer token (me comes from the auth token, never a query parameter).

    1. Upload encrypted attachment before sending
       POST /v1/attachments  {"content_type": "image/jpeg", "size_bytes": 384000, "sha256": "..."}
       -> 200 {"attachment_id": "att_42", "upload_url": "https://... (signed PUT, 10m TTL)"}
    
    2. Send message to 1..1,000 recipients
       POST /v1/messages
       {
         "client_message_id": "uuid-v4",           // idempotency key generated on sender device
         "recipient_ids": ["u_10", "u_24", "u_39"],// deduplicated server-side, max 1,000
         "body_text": "Vault PIN: 7381",           // <= 4 KB
         "attachment_ids": ["att_42"],
         "ttl_seconds": 2592000                    // <= 30 days
       }
       -> 202 {"message_id": "m_0482...", "recipient_count": 3}   // async fan-out
    
    3. List recipient inbox (envelopes ONLY — never returns body_text!)
       GET /v1/inbox?limit=100
       -> 200 {"envelopes": [{"message_id": "m_0482...", "sender_id": "u_01",
                              "sent_at": "...", "kind": "image", "expires_at": "..."}]}
    
    4. Batch-acknowledge envelope arrival
       POST /v1/inbox/ack  {"message_ids": ["m_0482..."]}
    
    5. Open a delivery (MUST be POST, never GET!)
       POST /v1/inbox/{message_id}/open
       {"open_request_id": "uuid-per-tap", "device_id": "ios_41"}
       -> 200 {"body_text": "Vault PIN: 7381",
               "attachments": [{"download_url": "... (60s signed)", "decrypt_key": "..."}]}
       -> 410 {"reason": "ALREADY_OPENED" | "EXPIRED" | "REVOKED"}
    
    6. Sender status & sender unsend/revoke
       GET    /v1/messages/{message_id}/status -> per-recipient state
       DELETE /v1/messages/{message_id}        -> revokes all not-yet-opened deliveries
    
    7. Real-time WebSocket stream (wss://gw.example.com/v1/stream)
       server -> client: {"type": "delivery.new", "envelope": {...}}
                         {"type": "delivery.gone", "message_id": "...", "reason": "OPENED_ELSEWHERE"}
    

    Notice why open must be POST: HTTP GET URLs are prefetched by browsers, corporate proxies, and link scanners, which would silently consume the user's single view!

  4. Data model

    We use a sharded relational engine (PostgreSQL) split into sender-sharded metadata and recipient-sharded deliveries, plus S3-compatible object storage for media:

    messages (sharded by sender_id)
      message_id          bigint PK          -- 64-bit time-ordered ID (timestamp_ms + shard + seq)
      sender_id           bigint
      client_message_id   uuid               -- UNIQUE (sender_id, client_message_id) for send retries
      body_ct             bytea              -- encrypted text; wiped to NULL once fan-out finishes
      recipient_ids       bigint[]
      attachment_ids      uuid[]
      fanout_state        enum('PENDING', 'DONE', 'REVOKED')
      created_at, expires_at
    
    deliveries (sharded by recipient_id; range-partitioned weekly on message_id)
      PRIMARY KEY (recipient_id, message_id) -- guarantees at most 1 copy per recipient
      sender_id           bigint
      state               enum('PENDING', 'DELIVERED', 'OPENED', 'EXPIRED', 'REVOKED')
      body_ct             bytea              -- recipient's encrypted text copy; NULL after purge
      attachment_ids      uuid[]
      created_at, expires_at
      opened_at           timestamp
      open_request_id     uuid               -- binds the 60s network-retry grace window
      open_device_id      text
      purge_at            timestamp          -- opened_at + 60s
      INDEX (recipient_id, state, message_id)
      INDEX (purge_at)   WHERE purge_at IS NOT NULL AND body_ct IS NOT NULL
      INDEX (expires_at) WHERE state IN ('PENDING', 'DELIVERED')
    
    attachments (sharded by sender_id, co-located with messages)
      attachment_id PK, sender_id, message_id, blob_key, wrapped_data_key, size_bytes
    
    attachment_recipients (sharded by sender_id)
      PRIMARY KEY (attachment_id, recipient_id) -- live set of recipients who may still open this blob
    

    Why sharded PostgreSQL instead of a wide-column store like Cassandra?

    1. Fast single-row compare-and-set: Enforcing read-once requires locking or conditionally updating one row. PostgreSQL executes SELECT ... FOR UPDATE locally in microseconds; Cassandra requires multi-round-trip Paxos "lightweight transactions".
    2. Delete-heavy workload without tombstone stalls: Purging 3B bodies/day in log-structured wide-column stores creates tombstones (deletion markers retained for days before compaction) that slow down inbox scans. In PostgreSQL, partitioning deliveries weekly by message_id (included in the primary key as PostgreSQL requires) keeps only ~5 active weekly partitions per shard and drops whole expired weeks instantaneously via DROP TABLE deliveries_w2026_40.
  5. High-level architecture

      Sender App                                                          Recipient Devices
          | POST /v1/messages                                      WebSocket |       ^ Push (no body!)
          v                                                                  v       |
      +---------+   1. Local ACID txn   +------------------+         +--------------+ +-------------+
      |   API   |---------------------->| Message Store    |         | WS Gateways  | | APNs / FCM  |
      | Servers |                       | (by sender_id)   |         | (30M sockets)| +-------------+
      +---------+                       +--------+---------+         +-------^------+        ^
          | POST /open & GET /inbox              | 2. CDC (outbox)           |               |
          |                                      v                           |               |
          |                             +------------------+                 |               |
          |                             | fanout topic     | (by message_id) |               |
          |                             +--------+---------+                 |               |
          |                                      v                           |               |
          |                             +------------------+ 3. Batch upsert |               |
          |                             | Fan-out Workers  |----------------+|               |
          |                             +------------------+                ||               |
          |                                                                 vv               |
          |   4. Single-row FOR UPDATE (sync replica commit)     +--------------------+      |
          +----------------------------------------------------->| Delivery Store     |      |
                                                                 | 128 shards         |      |
                                                                 | (by recipient_id)  |      |
                                                                 +---------+----------+      |
                                                                           | 5. CDC stream   |
                                                                           v                 |
                                                        +----------------------------------+ |
                                                        | Event Consumers                  | |
                                                        | - Notifier (registry -> WS/Push)-+-+
                                                        | - Sender Receipts updater        |
                                                        | - Attachment GC (deletes blobs)  |
                                                        +----------------------------------+
      Object Storage (S3): encrypted media blobs (1 copy/message), fetched via 60s signed URLs
    

    Every downstream side effect flows through Change Data Capture (CDC) — a process that tails the database write-ahead log and publishes committed row changes to Kafka. Writing to the database is enqueuing the event (the transactional outbox pattern), eliminating dual-write bugs where a server writes to a database and crashes before publishing to Kafka.

  6. Deep dive 1: asynchronous fan-out and race-free sender revoke

    Writing up to 1,000 delivery rows synchronously inside POST /v1/messages would span up to 128 database shards: there is no fast cross-shard transaction, and crashing at recipient #400 would leave a half-delivered message. Instead, POST /v1/messages commits one local transaction on the sender's shard (messages row with fanout_state = PENDING plus attachment_recipients rows) and returns 202 Accepted in milliseconds.

    Idempotent fan-out worker loop:

    1. Load message row m by message_id.
       If m.fanout_state != 'PENDING': ack Kafka offset and stop.
       If now() >= m.expires_at:
           set fanout_state = 'DONE', body_ct = NULL; remove uncreated attachment_recipients; stop.
    
    2. Filter out recipients who blocked sender or exceed the 10,000-unread abuse cap;
       delete their attachment_recipients rows (idempotent DELETE).
    
    3. Group remaining recipients by delivery shard (<= 1,000 recipients -> <= 128 shard batches).
       Execute in parallel across shards:
         INSERT INTO deliveries (recipient_id, message_id, sender_id, state, body_ct, expires_at, ...)
         VALUES (...), (...)
         ON CONFLICT (recipient_id, message_id) DO NOTHING;
    
    4. If ALL shard batches succeeded:
         UPDATE messages SET fanout_state = 'DONE', body_ct = NULL WHERE message_id = m.id;
       Else (e.g. Shard 47 timed out):
         Publish {message_id} to fanout_retry with exponential backoff (healthy shards already got theirs!).
    

    Closing the subtle race between Sender Revoke (DELETE) and in-flight fan-out:

    Suppose the sender calls DELETE /v1/messages/{id} 200 ms after sending, while Shard 47 is slow and has not inserted its deliveries row yet. A naive UPDATE deliveries SET state = 'REVOKED' on Shard 47 would match 0 rows, and 2 seconds later fanout_retry would insert a fresh PENDING row and leak the revoked message! Fix this by having Revoke mark messages.fanout_state = 'REVOKED', body_ct = NULL first and execute a tombstone upsert on every recipient shard:

    INSERT INTO deliveries (recipient_id, message_id, sender_id, state, body_ct, ...)
    VALUES (:r, :mid, :sid, 'REVOKED', NULL, ...)
    ON CONFLICT (recipient_id, message_id) DO UPDATE
        SET state = 'REVOKED', body_ct = NULL
      WHERE deliveries.state IN ('PENDING', 'DELIVERED');
    

    If the row existed and was unread, it flips to REVOKED; if already OPENED, WHERE leaves it OPENED; if not yet inserted, the REVOKED tombstone row blocks any late fan-out worker's ON CONFLICT DO NOTHING!

  7. Deep dive 2: strict read-once enforcement across devices and failovers

    All read-once logic reduces to a single row-locked transaction on the recipient's shard:

    BEGIN;
      SELECT state, body_ct, expires_at, open_request_id, open_device_id, purge_at
        FROM deliveries
       WHERE recipient_id = :me AND message_id = :mid
         FOR UPDATE;  -- exclusive row lock serializes simultaneous taps on phone + laptop!
    
      -- Case 1: First open on an unread, non-expired delivery
      IF state IN ('PENDING', 'DELIVERED') AND expires_at > now() THEN
          UPDATE deliveries
             SET state = 'OPENED', opened_at = now(),
                 open_request_id = :req_id, open_device_id = :dev_id,
                 purge_at = now() + INTERVAL '60 seconds'
           WHERE recipient_id = :me AND message_id = :mid;
          COMMIT;  -- synchronous commit to >= 1 standby replica before releasing bytes!
          RETURN 200 {decrypt(body_ct), 60s signed attachment URLs};
    
      -- Case 2: Network retry of the EXACT same tap within the 60s grace window
      ELSIF state = 'OPENED' AND open_request_id = :req_id AND open_device_id = :dev_id
            AND now() < purge_at AND body_ct IS NOT NULL THEN
          COMMIT;
          RETURN 200 {decrypt(body_ct), 60s signed attachment URLs};
    
      -- Case 3: Second tap, other device, expired, or revoked
      ELSE
          COMMIT;
          RETURN 410 {ALREADY_OPENED | EXPIRED | REVOKED};
      END IF;
    

    Why database failover can silently break read-once — and how we prevent it:

    Broken async replication:
      Primary commits OPENED -> returns 200 OK ("PIN 7381") -> crashes 2 ms later before shipping WAL!
      Replica promotes with state still = DELIVERED -> attacker/second device opens a 2nd time!
    
    Safe quorum synchronous replication + home-region pinning:
      1. Configure PostgreSQL synchronous_commit = on, synchronous_standby_names = 'ANY 1 (r1, r2)'
         across 3 availability zones: COMMIT waits ~1-2 ms until at least 1 replica has the WAL record,
         and failover only promotes a caught-up replica.
      2. Pin opens to the recipient's single home region (CP over AP for /open): during a cross-region
         partition, opens wait rather than risking split-brain double opens in two regions.
    
  8. Deep dive 3: bounded physical deletion, retention, and shared attachments

    "Permanently unavailable" has two distinct layers: logical unavailability (instantaneous the millisecond state = 'OPENED' commits) and physical erasure of ciphertext bytes across every subsystem:

    Storage location              How & when bytes are removed                         Time bound
    ----------------------------  ---------------------------------------------------  ----------------
    deliveries.body_ct (primary)  Background sweeper sets body_ct = NULL at purge_at   ~60 s after open
    Read/standby replicas         Replicates the NULL update via WAL                   ~61 s after open
    messages.body_ct (sender DB)  Cleared to NULL as soon as fan-out completes         Seconds after send
    Kafka / CDC streams           CDC relays exclude body_ct; topics carry IDs only    0 s (never stored)
    Shared S3 attachment blob     Deleted when attachment_recipients set hits 0 rows   After last open/TTL
    Dead DB row versions / WAL    PostgreSQL VACUUM + encrypted WAL/backup rotation    Up to 7 days
    All disk/backup copies (opt.) Crypto-shredding: delete per-message key in KMS/KV   <= 24 hours
    

    Two subtle deletion pitfalls worth calling out explicitly:

    • Why SQL SET body_ct = NULL does not immediately zero SSD pages: Relational engines use multi-version concurrency control (MVCC), leaving the old row version on disk until VACUUM reclaims space, plus encrypted write-ahead logs (WAL) and 7-day backups still hold historical ciphertext. If strict regulatory erasure (<= 24h everywhere including backups) is required, use crypto-shredding: encrypt each message body with a unique data key stored in a dedicated short-backup key store and delete that key at purge_at, turning every leftover backup or disk page into unrecoverable random noise.
    • Why shared attachments use an idempotent recipient set instead of a reference counter: With at-least-once CDC events, a naive remaining_count = remaining_count - 1 counter would decrement twice on a duplicate Kafka delivery and delete the photo before the last recipient opened it! Storing explicit (attachment_id, recipient_id) rows seeded at send time and running DELETE WHERE attachment_id = ? AND recipient_id = ? on terminal transitions (OPENED | EXPIRED | REVOKED) is naturally idempotent: deleting an already-deleted row is a harmless no-op, and when COUNT(*) = 0, the worker deletes both the wrapped key and the S3 object (backed by a daily orphan-reconciliation sweep).
  9. Online/offline delivery, scaling, and partitioning

    Online vs. offline delivery and reconnect reconciliation

    • Online: Gateways hold 30M WebSockets (~300–400 servers at ~80K–100K sockets/node behind an L4 least-connections load balancer) and refresh user_id -> {device_id: gateway_id} in a Redis connection registry (60 s TTL). When a delivery lands, the notifier pushes delivery.new (envelope only) in < 200 ms; when opened on one device, delivery.gone clears the envelope on the user's other open devices.
    • Offline & reconnect: If no live socket exists, send a body-free APNs/FCM push. Whenever an app opens or reconnects, it calls GET /v1/inbox to replace local state from the deliveries shard (capped at 10,000 unread items, typically < 20 rows), automatically healing any missed WebSocket frames.

    Partitioning and horizontal scaling

    • Logical-to-physical sharding: Hash recipient_id into 4,096 logical shards (hash(recipient_id) mod 4096) mapped via a cached routing table onto 128 physical PostgreSQL primaries (~3,300 writes/s and ~350 GB each). Doubling cluster size streams logical shards to new hosts via logical replication without rehashing user IDs.
    • Stream partitioning: Partition fanout by message_id so a 1,000-recipient send spreads evenly across workers; partition delivery CDC by recipient_id so "delivery.new" is never processed after "delivery.gone" for the same user.
    • Media offload: Clients upload and download encrypted attachments directly against S3 via 60 s signed URLs so multi-megabyte media never touches API servers.
  10. Failure modes, consistency split, and trade-off summary

    Failure scenario                         System behavior & recovery
    ---------------------------------------  ------------------------------------------------------------
    Sender retries POST /v1/messages         UNIQUE(sender_id, client_message_id) returns original 202
    Fan-out worker crashes mid-batch         Kafka redelivers; ON CONFLICT DO NOTHING skips inserted rows
    One recipient shard is down              Other 127 shards deliver live; failed shard retries via queue
    Mobile network drops during POST /open   Same (open_request_id, device_id) succeeds within 60s window
    Primary shard crashes right after open   Sync standby already holds OPENED; refuses any second open
    Purge or expiry sweeper lags             Alert fires; /open still checks state & expires_at inline!
    

    Core consistency design: Spend strong linearizable consistency exclusively on the single-row deliveries state transition (FOR UPDATE + synchronous cross-AZ commit in the recipient's home region), and keep every surrounding step (fan-out, WebSocket push, read receipts, blob garbage collection) asynchronous, at-least-once, and idempotent.

    Summary of key trade-offs

    • Per-recipient delivery rows + copied text vs. shared message row: Writes up to 1,000 × 4 KB = 4 MB per send, in exchange for complete recipient isolation and single-row atomic opens.
    • Shared media blobs + attachment_recipients table: Saves ~3x–1,000x object storage (~255 TB vs. ~800+ TB), at the cost of event-driven blob garbage collection.
    • Synchronous standby commit + single home region on /open: Adds ~1–2 ms write latency and chooses consistency over availability during regional isolation so failovers can never permit a second open.
    • 60 s device-bound retry window vs. 0 s strict mode: Prevents flaky mobile networks from destroying unread messages on dropped HTTP responses while still blocking second devices or fresh taps.

Intuition & how it works

Imagine mailing a confidential note to three teammates — not by pinning one shared sheet onto a group bulletin board, nor by printing the secret text on the outside of a postcard, but by placing three independent claim tickets into each teammate's private post-office box. Inside their inbox, each person sees only a plain envelope ("New note from Priya, 1 image" — zero secret content). When Maya walks up to her own local post-office window to redeem her ticket, the clerk locks Maya's ledger line, stamps it OPENED in permanent ink on both the main ledger and a backup ledger (synchronous replication) before handing her the note, and shreds Maya's paper slip 60 seconds later — leaving Liam's and Noah's tickets untouched. Meanwhile, heavy photo attachments sit encrypted once in a back-room vault with {Maya, Liam, Noah} written on an access checklist; as each teammate opens (or lets expire) their ticket, their name is crossed off, and once the checklist is empty, the vault photo is destroyed.

Why do obvious designs break the single-view promise? Modeling the message as a group-chat row with a single is_read boolean causes Maya's open to hide the message from Liam and Noah. Putting the message body inside mobile push notifications or serving it over GET URLs leaks uncontrolled copies into lock-screen previews, chat link unfurlers, and proxy caches before the recipient ever taps Open. Implementing open as two separate queries ("SELECT the body, then DELETE the row") lets a phone and a laptop tap at the exact same millisecond and both read the secret before either delete executes — and using default asynchronous database replication allows a primary crash 2 milliseconds after 200 OK to fail over to a slightly behind replica that still thinks the message is unread!

Here is a concrete trace of u_01 sending "Vault PIN: 7381" with photo att_42 to u_10 and u_24, including a simultaneous two-device tap and a dropped Wi-Fi response:

Step  Event                                       u_10's delivery row (Shard 22)    u_24's row (Shard 75)  att_42 live set
----  ------------------------------------------  --------------------------------  ---------------------  ---------------
1     u_01 POST /messages to [u_10, u_24]+att_42  (fan-out queued via CDC outbox)   (queued)               {u_10, u_24}
2     Fan-out worker batch-inserts per shard      state=PENDING, body_ct=enc_bytes  state=PENDING          {u_10, u_24}
3     u_10's phone (req R1) & laptop (req R2)     Row lock serializes R1 then R2:   state=PENDING          {u_24}
      call POST /open at the exact same ms!       R1 -> state=OPENED, req=R1 (200)  (untouched!)           (u_10 removed!)
                                                  R2 -> sees req=R1 != R2 -> 410!
4     u_10's phone loses Wi-Fi; retries req R1    Matches req=R1 & dev & < 60s      state=PENDING          {u_24}
      4 seconds later                             -> returns 200 (same single tap)
5     60s pass; purge sweeper runs on Shard 22    body_ct=NULL (physically wiped)   state=PENDING          {u_24}
6     u_24 opens on Shard 75                      state=OPENED, body_ct=NULL        state=OPENED           {} -> DELETE S3!

Key trade-offs

  • Per-recipient delivery rows (copied text) vs. one shared message row: Duplicating encrypted text (<= 4 KB) across up to 1,000 recipient rows (<= 4 MB worst-case per send) costs ~4 lifecycle writes per recipient, but guarantees total recipient isolation and turns the read-once check into a fast single-row lock on one shard with zero cross-shard transactions.
  • Copying small text, sharing large media blobs: Copying 300 KB–10 MB attachments per recipient would bloat storage from ~255 TB to ~800+ TB (and 10 GB for one 1,000-recipient send). Storing one encrypted S3 blob per message with an idempotent attachment_recipients(attachment_id, recipient_id) set keeps storage minimal at the cost of asynchronous garbage collection.
  • Asynchronous outbox fan-out vs. synchronous multi-shard writes: Committing one local messages row and fanning out via Change Data Capture (CDC) (streaming committed database log entries into Kafka) adds ~100–200 ms before envelopes appear, but prevents partial sends when one of 128 recipient shards is slow.
  • Sharded PostgreSQL vs. wide-column LSM stores (Cassandra): Read-once relies on single-row compare-and-set plus deleting almost every written body. PostgreSQL handles row locks locally and drops expired weekly partitions instantaneously, whereas Cassandra requires multi-round-trip Paxos transactions and accumulates tombstones (delete markers that slow down inbox reads until compaction).
  • Quorum synchronous replication + home-region pinning on /open: Waiting ~1–2 ms for at least one cross-zone standby replica to acknowledge OPENED before returning 200 OK — and serving opens only in the recipient's home region — sacrifices availability during full regional isolation so database failover or split-brain partitions can never release a message twice.
  • 60 s same-request retry grace vs. 0 s strict at-most-once: Keeping body_ct for 60 s keyed to (open_request_id, device_id) prevents flaky mobile connections from losing unread messages on a dropped HTTP response, while strict mode (0 s) eliminates even same-device replay at the cost of occasional lost views.
  • SQL NULL purge vs. crypto-shredding: Setting body_ct = NULL hides content from the app and SQL within ~60 s, while encrypted write-ahead logs and 7-day backups age out naturally; crypto-shredding (deleting a per-message encryption key from a short-retention key store) renders every backup and unvacuumed disk page unreadable within hours, at the cost of one key-store lookup per open.

Common mistakes

  • Including message text inside inbox envelopes or APNs/FCM push payloads: Leaks copies onto lock screens, OS notification logs, smartwatch mirrors, and retry queues completely outside the server's read-once gate.
  • Using GET /messages/{id} to open a message: Browser prefetching, corporate proxies, and link-preview bots automatically issue GET requests, burning the recipient's single view before they touch the message.
  • Implementing open as SELECT followed by DELETE/UPDATE without a row lock: Two devices tapping concurrently both pass the SELECT check before either UPDATE runs, releasing the secret twice.
  • Using asynchronous replication (or semi-sync that falls back to async on timeout) on the delivery store: If the primary crashes right after returning 200 OK, promoting an asynchronous replica reverts state back to DELIVERED and permits a second open.
  • Decrementing an integer ref_count from at-least-once Kafka events to delete shared media: A single replayed Kafka event decrements ref_count early and deletes the attachment before the final recipient opens it; delete explicit (attachment_id, recipient_id) rows instead so replays are no-ops.
  • Running UPDATE deliveries SET state = 'REVOKED' alone for sender unsend: Misses recipients whose fan-out insert is still in flight in a retry queue; insert a REVOKED tombstone row with ON CONFLICT DO UPDATE so delayed fan-out inserts (ON CONFLICT DO NOTHING) are blocked cleanly.
  • Promising "instant disk erasure everywhere" or "screenshot prevention": Be transparent with interviewers that MVCC databases leave dead tuples until vacuumed, backups retain ciphertext until rotated (unless crypto-shredded), and cameras can always photograph a screen.

Follow-up questions

  • How would adding end-to-end encryption alter payload fan-out, attachment key wrapping, and single-view enforcement? Under end-to-end encryption (E2EE), the backend never sees plaintext or unwrapped attachment keys. At send time, the author's client fetches public pre-keys for each recipient's registered devices, encrypts the text (or wraps a random symmetric attachment key) separately per recipient device, and uploads that bundle. The server still enforces the linearizable OPENED transition on (recipient_id, message_id): the winning device receives its ciphertext envelope while sibling device ciphertexts for that recipient are cleared in the same transaction, and physical erasure becomes even stronger because the server never possessed plaintext or raw content keys.
  • How can a sender revoke an unread message across all targets without racing against in-flight fan-out workers? DELETE /v1/messages/{id} flips messages.fanout_state = 'REVOKED', body_ct = NULL on the sender's shard and dispatches a high-priority revoke job across recipient shards. On each shard, the worker runs an atomic tombstone upsert (INSERT ... state = 'REVOKED', body_ct = NULL ON CONFLICT (recipient_id, message_id) DO UPDATE SET state = 'REVOKED', body_ct = NULL WHERE deliveries.state IN ('PENDING', 'DELIVERED')). For every recipient, this serializes cleanly on the row lock against POST /open (either OPENED or REVOKED wins, accurately reflected on the sender's status screen) and prevents any delayed fan-out worker (ON CONFLICT DO NOTHING) from inserting the revoked delivery later.
  • If a verified account sends a single-view announcement to one million followers, how must your storage and fan-out strategy change? Fan-out on write (1,000,000 row inserts per send) becomes far too bursty and expensive, so switch to fan-out on read: store the encrypted announcement body once in a cached broadcasts table, merge active broadcasts when followers fetch their inbox, and enforce single-view via an atomic INSERT INTO broadcast_opens (recipient_id, broadcast_id, open_request_id, ...) VALUES (...) sharded by recipient_id (never by broadcast_id, which would turn one viral post into a single-shard hotspot!). The first INSERT succeeds and releases the payload; any duplicate-key conflict (23505 in PostgreSQL) returns 410 ALREADY_OPENED, and the shared broadcast blob is purged once its TTL lapses.

Follow-up questions

Similar questions

More Grammarly interview questions

All 11 Grammarly questions →