High-Throughput Notification Platform for Million-Write Bursts

Medium · System Design · Software Engineer · Onsite

Prompt

Architect a multi-channel alerting and messaging platform engineered to absorb sudden traffic surges reaching 1,000,000 writes per second—for instance, when live tournament updates or market alerts fire simultaneously alongside urgent P0 login passcodes like mfa-31 for account usr_19.

Because baseline volume, surge duration, target delivery channels, priority SLAs, recipient opt-outs and quiet hours, inbox history retention, and the exact unit counted as one "write" are left open, establish explicit assumptions first before sizing clusters or selecting storage engines.

Scope & Expectations

  • Traffic modeling, SLAs, and capacity tiers: Clarify write granularity, supported channels (in-app inbox, mobile push, email, SMS), user controls, and priority-dependent latency and durability targets; translate the 1,000,000/s peak into network, memory, and disk estimates while separating front-door components sized for peak spikes from downstream tiers sized for steady drain rates.
  • Buffered ingestion and log-structured storage internals: Design a partitioned streaming buffer with hot-spot-free keys and overload backpressure, and explain the on-disk mechanics of an LSM-backed wide-column store (such as Apache Cassandra)—detailing why sequential writes achieve high throughput and what trade-offs surface during reads, TTL expiry, and compaction.
  • End-to-end deduplication, channel workers, and priority isolation: Prevent duplicate deliveries across caller and worker retries via idempotency keys, a memory-bounded deduplication cache, and persisted delivery state, while handling external gateway rate caps, non-blocking retry topics, dead-letter queues, and dedicated fast lanes for critical alerts.

Step-by-step walkthrough

  1. Clarify requirements and define what a "write" is

    The scenario centers on one headline constraint—spiky traffic peaking at 1,000,000 writes per second—and leaves the surrounding product details open. Our first step is to define exactly what counts as one "write" and state clear assumptions for channels, priorities, durability, and spike duration.

    Core product and traffic assumptions

    • What counts as 1 write: One per-recipient notification accepted into the system. If an upstream service sends a batch request targeting 500 users, that counts as 500 writes. Downstream delivery-status updates (SENT, DELIVERED, FAILED) are additional database writes, but they happen at the slower provider delivery rate, not the 1M/s ingest rate.
    • Channels: Every notification is saved to an in-app inbox (100%); additionally ~70% go to mobile push (Apple APNs / Google FCM), ~5% to email, and <1% to SMS (mostly one-time security codes).
    • Priority levels and latency targets:
      • P0 (Transactional & Security — ~1% of traffic): One-time passcodes (OTPs), fraud alerts, password resets. Must reach the external provider within 5 seconds at p99 (99% of messages), even in the middle of a massive burst.
      • P1 (User Activity — ~69% of traffic): Direct replies, mentions, live-event scores. Under 60 seconds at p99 normally; allowed to lag by several minutes during a peak burst.
      • P2 (Marketing & Digests — ~30% of traffic): Promotional campaigns and daily summaries. Best-effort within hours; dropped cleanly if their expiration time passes.
    • Delivery guarantees: At-least-once processing internally combined with deduplication, so a user practically sees each notification once (never systematically duplicated, and never silently lost once accepted).
    • User controls & retention: Per-category and per-channel opt-outs, per-timezone quiet hours (P0 bypasses quiet hours), and daily frequency caps on P2 (e.g., max 3 marketing pushes/day). In-app inbox history is readable for 30 days; per-channel delivery logs are kept 7 days for debugging.
    • Traffic shape (burstiness): Average load is 100,000 writes/s (a 10:1 peak-to-average ratio). Bursts jump to 1,000,000 writes/s within seconds (faster than cloud VMs can autoscale) and last up to 10 minutes (e.g., breaking news or major live sports moments).

    Functional and non-functional summary

    • Functional: Ingest single/batch notifications with idempotency keys and priorities; enforce preferences, quiet hours, and caps; render localized templates; deliver to inbox, push, email, and SMS; serve a paginated user inbox and delivery-status lookup.
    • Non-functional: Sustain 1M writes/s ingest at 99.95% availability; zero lost accepted notifications across single-node or availability-zone failures; strict priority isolation (P1/P2 bursts never delay P0); bounded deduplication memory.
  2. Back-of-the-envelope numbers: peak vs. average sizing

    The central capacity insight here is straightforward: separate the front-door components that must absorb 1,000,000 writes/s immediately from the downstream components that can drain a buffered backlog after the burst subsides. Let's run the math carefully.

    1. Traffic Volume
       Peak ingest rate:        1,000,000 notifications/s  (P0 ~1% = ~10,000/s)
       Average ingest rate:       100,000 notifications/s  -> 100K * 86,400 s = 8.64 billion/day
       One 10-minute burst:     600 s * 1,000,000/s = 600 million notifications
    
    2. Network & Durable Buffer (Kafka)
       Payload size on wire:    ~500 bytes (IDs, template_id, params, priority, timestamps)
       Peak API ingress:        1,000,000 * 500 bytes = 500 MB/s (4 Gbit/s)
       Peak Kafka disk writes:  500 MB/s * 3 replicas = 1.5 GB/s across brokers
       24-hour Kafka storage:   8.64 billion * 500 bytes = 4.32 TB/day -> ~13 TB across 3 replicas
                                (One 10-min burst adds 600M * 500 bytes = 300 GB, or 900 GB replicated)
    
    3. User Inbox Store (Cassandra — 30-day retention)
       Total stored rows:       8.64 billion/day * 30 days = 259.2 billion rows
       Disk size (~200 B/row):  259.2 billion * 200 bytes = ~52 TB logical -> ~156 TB across 3 replicas
       Node count (~2 TB/node): ~80 nodes (keeping 50% disk free for background compaction)
       Write capacity of 80 nodes (assuming ~25,000 replica-writes/s per node for small rows):
                                80 * 25,000 = 2,000,000 replica-writes/s
                                At replication factor 3 -> ~667,000 notifications/s!
       Burst backlog math:      If routers/inbox drain at 600,000/s during a 10-min 1M/s burst:
                                Backlog = (1,000,000 - 600,000) * 600 s = 240 million notifications
                                After burst ends (ingest = 100K/s), net drain = 600K - 100K = 500K/s
                                Time to clear inbox backlog = 240M / 500K/s = 480 s = 8 minutes!
    
    4. Delivery-State Store (Separate Cassandra cluster — 7-day retention)
       External channel demand: ~76% of notifications (70% push + 5% email + <1% SMS)
       Provider send ceiling:   ~200,000/s push + ~50,000/s email/SMS = ~250,000 deliveries/s peak
       Replica ops at peak:     250K quorum reads (*2 replicas) + ~300K status writes (*3 replicas)
                                = ~1.4 million replica ops/s -> ~60 nodes (only ~14 TB disk for 7 days)
    
    5. Deduplication Cache (Redis — 1-hour sliding window)
       Keys in worst hour:      10 min (600 s) @ 1M/s + 50 min (3,000 s) @ 100K/s
                                = 600 million + 300 million = 900 million keys
       RAM (~100 bytes/key):    900 million * 100 bytes = ~90 GB RAM
       Ops at 1M/s peak:        2 Redis writes per notification (claim pending + confirm done) = 2M ops/s
       Cluster sizing:          32 Redis shards (~2.8 GB RAM & ~62,500 ops/s per shard) + 32 replicas
    

    Notice two huge architectural wins revealed by this math:

    • Retention gives us inbox write throughput nearly for free: Storing 30 days of history already requires ~80 Cassandra nodes, and 80 nodes can sustain ~667K writes/s—meaning a 10-minute 1M/s burst queues for at most 8 minutes without over-provisioning!
    • Splitting delivery_state into its own 60-node cluster prevents an overload: Delivery state is tiny on disk (14 TB vs. 156 TB) but heavy on reads and writes (1.4M replica ops/s). Putting it inside the 80-node inbox cluster would push the inbox cluster past its write ceiling right during a burst.
    Sizing Tier Components Why
    Peak (1M/s) L7 Load Balancers, Accept API (~70 stateless nodes @ ~20K/s), 32-shard Redis dedup, 24-broker Kafka Bursts ramp up in seconds; rejecting or timing out causes callers to retry and amplify the burst
    Drain (~600K/s) Stateless Routers, 80-node Inbox Cassandra Drains a 10-minute 1M/s burst from Kafka in 8 minutes
    Provider ceiling (~250K/s) Push/Email/SMS Workers, 60-node Delivery-State Cassandra External providers enforce hard rate caps anyway
  3. Notification API and deterministic IDs

    POST /v1/notifications                        (single recipient)
    POST /v1/notifications:batch                  (up to 500 recipients; each item carries its own key)
      Header: Idempotency-Key: billing-svc:inv-408:usr_19
      Body:
      {
        "recipient_id": "usr_19",
        "category": "thread_reply",
        "priority": "P1",                         // "P0" | "P1" | "P2"
        "template_id": "thread_reply_v2",
        "params": {"sender": "Elena", "thread_id": "t_84"},
        "channels": ["inbox", "push"],            // optional override
        "collapse_key": "thread:t_84",            // optional: newer replaces older pending item
        "occurred_at": "2026-11-30T14:20:00Z",    // upstream event timestamp (reused on retries)
        "expires_at":  "2026-11-30T14:30:00Z"     // optional: drop external send if past due
      }
    
    Responses:
      202 Accepted   {"notification_id": "notif_7c2e...", "duplicate": false}
      202 Accepted   {"notification_id": "notif_7c2e...", "duplicate": true}   // seen within last 1h
      409 Conflict   {"error": "in_progress"}        Retry-After: 1            // concurrent duplicate in flight
      429 Too Many   {"error": "tenant_quota"}       Retry-After: 2            // caller exceeded token bucket
      503 Overload   {"error": "shedding_p2"}        Retry-After: 30           // extreme overload: P2 shed first
    
    POST /v1/campaigns                            {"segment_id", "template_id", "priority": "P2", "max_rate": 50000}
    GET  /v1/users/{user_id}/inbox?limit=20&cursor=<opaque>
    POST /v1/users/{user_id}/inbox/read           {"read_up_to": "2026-11-30T14:21:00Z"}
    GET  /v1/notifications/{notification_id}/status
    
    • Why 202 Accepted instead of 200 OK: 202 tells the caller "your notification is durably recorded and queued, not yet delivered to the phone."
    • Deterministic notification_id: Instead of generating a random UUID on arrival, the API computes notification_id = first_16_bytes(SHA-256(tenant_id + ":" + idempotency_key)). If a retry ever slips past the Redis cache (for example after a cache failover), both copies produce the exact same notification_id, allowing Cassandra and channel workers to deduplicate them automatically without a central lookup table!
  4. Storage schemas and even-spread sharding keys

    1. Partitioned Kafka topics (durable burst buffer)

    notif.p0   (64 partitions)     partition key = recipient_id
    notif.p1   (512 partitions)    partition key = recipient_id
    notif.p2   (512 partitions)    partition key = recipient_id
    push.p0 / push.p1 / push.p2    partition key = recipient_id
    email.p0 / email.p1 / sms.p0   partition key = recipient_id
    push.retry.1m, push.retry.10m, push.dlq
    

    Partitioning by recipient_id spreads 1M writes/s evenly across all 512 partitions (~2,000 msgs/s per partition) and routes every message for user usr_19 to the same router instance in order—making per-user preference caching, frequency caps, and collapse_key merging fast local operations.

    2. Wide-column schemas in Cassandra

    -- Cluster 1: User Inbox (~80 nodes)
    CREATE TABLE inbox_by_user (
      user_id         text,
      month_bucket    text,          -- e.g. '2026-11'
      created_at      timestamp,     -- set to request's occurred_at
      notification_id text,
      category        text,
      priority        text,
      title           text,
      body            text,
      deep_link       text,
      PRIMARY KEY ((user_id, month_bucket), created_at, notification_id)
    ) WITH CLUSTERING ORDER BY (created_at DESC, notification_id DESC)
      AND default_time_to_live = 2592000   -- 30 days
      AND compaction = {'class': 'TimeWindowCompactionStrategy',
                        'compaction_window_unit': 'DAYS', 'compaction_window_size': 1};
    
    CREATE TABLE inbox_read_marker (
      user_id         text PRIMARY KEY,
      read_up_to      timestamp,
      recent_read_ids set<text>      -- individual clicks newer than read_up_to
    );
    
    -- Cluster 2: Delivery State (~60 nodes)
    CREATE TABLE delivery_state (
      notification_id     text,
      channel             text,      -- 'push' | 'email' | 'sms'
      status              text,      -- 'SENT' | 'DELIVERED' | 'FAILED' | 'SUPPRESSED' | 'EXPIRED'
      attempts            int,
      provider_message_id text,
      updated_at          timestamp,
      PRIMARY KEY ((notification_id), channel)
    ) WITH default_time_to_live = 604800;  -- 7 days
    

    3. PostgreSQL holds small, relational, read-heavy metadata: user preferences (~500M users × 200 B ≈ 100 GB), localized templates, tenant quotas, and campaign definitions.

    Three rules that prevent hot partitions and compaction stalls

    • Never partition by timestamp (day, minute) or campaign_id: During a 1M/s burst, every single write would hammer the current minute's partition on just 3 nodes! Starting every partition key with user_id or notification_id spreads bursts across all 80 nodes.
    • Bucket inbox partitions by (user_id, month_bucket): Even a heavy user receiving 1,000 notifications/day accumulates only 30,000 × 200 B ≈ 6 MB per partition—well below Cassandra's 100 MB partition health guideline.
    • Never mutate old inbox_by_user rows to mark them "read": Storing read_up_to in a separate inbox_read_marker table keeps inbox_by_user strictly append-only (we explain why in Deep Dive 2!).
  5. High-level architecture

      Upstream Services           Campaign Service (expands segments @ <= 50K/s)
              \                         /
               v                       v
      +-----------------------------------------+   1. claim pending / confirm done   +-----------------------+
      | L7 Load Balancer -> Accept API (~70x)   | <---------------------------------> | Redis Dedup Cluster   |
      | auth, tenant quota, deterministic ID    |                                     | (32 shards, ~90 GB)   |
      +-----------------------------------------+                                     +-----------------------+
               | 2. batched produce (acks=all, min.insync.replicas=2, key=recipient_id)
               v
      +-------------------------------------------------------------------+
      | Kafka Buffer:  notif.p0 (64)  |  notif.p1 (512)  |  notif.p2 (512)|   (24 brokers across 3 AZs, RF=3)
      +-------------------------------------------------------------------+
               | isolated consumer groups per priority
               v
      +-----------------------------------------+   local RAM + Redis cache   +-------------------------------+
      | Stateless Routers                       | <-------------------------> | PostgreSQL: preferences,      |
      | prefs, quiet hours, caps, render        |                             | templates, tenant quotas      |
      +-----------------------------------------+                             +-------------------------------+
               |                            \
               | 3a. append inbox row        \ 3b. emit per-channel task
               v                              v
      +-------------------------+    +-------------------------------------------------------+
      | Cassandra Inbox Cluster |    | Kafka Channel Topics: push.p0/p1/p2, email.*, sms.*   |
      | (~80 nodes, 156 TB)     |    +-------------------------------------------------------+
      +-------------------------+                      |
               ^                                       v
               |                     +-----------------------------------------+      +-------------------+
      Inbox API (GET /inbox)         | Channel Workers (isolated by priority)  | ---> | APNs / FCM        |
               ^                     | token buckets, Redis 60s claim lease,   | ---> | Email Provider    |
               |                     | quorum delivery_state check, send       | ---> | SMS Gateway       |
          User Apps                  +-----------------------------------------+      +-------------------+
                                               ^                     |
                                               |                     v (429 / 5xx -> push.retry.1m / 10m / dlq)
                                               v
                                     +-------------------------+
                                     | Cassandra Delivery State|
                                     | (~60 nodes, 14 TB)      |
                                     +-------------------------+
    

    End-to-end trace of one accepted notification

    1. Accept & Claim: The Accept API validates the request, checks the caller's tenant quota, computes the deterministic notification_id, and claims tenant:key in Redis as pending:<attempt_id> (30 s TTL).
    2. Buffer Durably: The API writes the record to notif.p1 in Kafka (acks=all). Once at least two brokers in different availability zones confirm, the API updates Redis to done (1-hour TTL) and returns 202 Accepted in single-digit milliseconds.
    3. Route & Fan-out: A P1 router reads the message, checks cached preferences/quiet hours/caps, renders the localized text, writes the row to inbox_by_user, and publishes channel tasks (e.g., to push.p1).
    4. Deliver Once: A push.p1 worker acquires a short Redis send lease, checks delivery_state in Cassandra to ensure it wasn't already sent, calls APNs/FCM with a collapse key, and writes status = 'SENT'.
    5. Read Inbox: When the user opens the app, the Inbox API reads the latest 20 rows from (user_id, current_month) plus inbox_read_marker in a few milliseconds.
  6. Deep dive 1: Absorbing 1M/s bursts — fast acknowledgement, deferred work, and backpressure

    To keep the front door responsive under a 1M/s surge, we draw a strict boundary between work required before returning 202 and work deferred asynchronously. Every extra network call before 202 multiplies the size of our peak-provisioned tier and adds a failure point during bursts:

    • Before 202 (synchronous, ~5 ms total): Authenticate caller, check local token-bucket tenant quota, validate JSON schema, compute deterministic notification_id, claim Redis dedup key (pipelined), and append to Kafka with acks=all and min.insync.replicas=2 across 3 availability zones (so surviving any single node or zone outage loses zero accepted writes).
    • After 202 (asynchronous, replayable from Kafka): Preference lookups, quiet-hour deferral, frequency-cap counting, template rendering, Cassandra inbox inserts, and external provider calls.

    Kafka buffer sizing and layered backpressure

    • 24 Kafka brokers across 3 AZs: Writing 1.5 GB/s replicated across 24 NVMe brokers is only ~62.5 MB/s per broker—leaving ample disk/network headroom for router reads and single-AZ failovers. We fix 512 partitions up front so hash(recipient_id) % 512 never remaps mid-operation.
    • How backpressure protects the system if a burst lasts longer than expected:
      1. Normal burst (≤10 min): Kafka consumer lag climbs calmly while routers drain at 600K/s; no caller sees an error.
      2. Sustained overload (Kafka produce latency rises or broker buffers fill): Accept API bounded memory buffers push back immediately rather than running out of RAM.
      3. Priority load shedding: Accept nodes first reject P2 marketing writes (503 Retry-After: 30), then throttle P1 tenants exceeding their contracted quota (429). P0 security traffic uses dedicated topic partitions and reserved API concurrency, so P0 is never shed by P1/P2 storms.
  7. Deep dive 2: Why log-structured stores (Cassandra) write fast and what reads pay

    Let's inspect the storage engine internals: why can Cassandra sustain 600K+ writes/s effortlessly while a traditional B-tree relational database struggles, and what is the trade-off on reads?

    Traditional relational databases (like PostgreSQL) store tables and indexes in B-trees on disk. Inserting rows with random user IDs updates leaf pages in place across multiple B-trees—requiring random disk reads to fetch pages into RAM, dirty-page flushes, and page splits.

    Cassandra instead uses an LSM tree (Log-Structured Merge tree, a storage engine that turns random writes into fast sequential appends and defers sorting/merging to background tasks):

    WRITE PATH ON ONE CASSANDRA REPLICA (No disk reads! Pure sequential append + RAM insert)
    
      write(user_id, created_at, ...)
         |
         +---> 1. Commit Log (on disk): append bytes sequentially to the end of an append-only file
         +---> 2. Memtable (in RAM):    insert row into an in-memory sorted tree
         |
         v
       Acknowledge replica write!
    
    BACKGROUND MAINTENANCE (Postponed work)
       - When Memtable fills (~128 MB) -> flush sequentially to an immutable SSTable (Sorted String Table) file
       - Background Compaction -> stream-merge multiple SSTables into larger sorted SSTables, dropping expired data
    

    What reads and operations pay in exchange—and how our schema neutralizes the downsides

    • Reads may check multiple SSTable files: Because a user's recent notifications might sit across the Memtable and 2–3 daily SSTables, a read checks each SSTable's Bloom filter (a compact bit array in RAM that quickly proves when a file definitely does not contain user_id, avoiding wasted disk reads) and merges matching rows. Since users open their inbox far less often than notifications arrive, touching 2–3 files on app open easily finishes in single-digit milliseconds.
    • Deletes and updates create tombstones: Because SSTables are immutable, deleting a row actually writes a tombstone (a deletion marker kept for days until compaction purges it). Scanning past thousands of tombstones cripples read latency. Our fix: We never DELETE inbox rows—30-day TTL expires them automatically—and we never UPDATE old inbox rows to mark them read (we update the tiny inbox_read_marker row instead!).
    • TimeWindowCompactionStrategy (TWCS) drops whole expired files in O(1): Grouping immutable writes into 1-day SSTable buckets means day 1's file is compacted once and never rewritten again; on day 31, Cassandra simply unlinks the entire expired file from disk with zero tombstone scanning and minimal write amplification (extra disk I/O spent rewriting data during compaction).
    • Consistency level LOCAL_QUORUM (2 of 3 replicas): A coordinator sends every write to all 3 replicas (so LOCAL_ONE does not reduce cluster disk load!) and waits for 2 replicas to confirm. Using LOCAL_QUORUM for both writes and reads guarantees every read overlaps with at least one up-to-date replica—critical when channel workers check delivery_state to prevent duplicate sends!
  8. Deep dive 3: End-to-end deduplication, channel workers, and priority isolation

    In a distributed pipeline, every network boundary can retry on timeout, and tracking 900 million recent keys requires careful memory budgeting. Let's trace every place a duplicate can originate and how each stage blocks it:

    Hop / Failure Mode How a Duplicate Happens How Our Pipeline Stops It
    1. Upstream HTTP timeout Caller times out after we accepted and retries Same Idempotency-Key hits Redis done -> returns 202 duplicate: true
    2. Upstream double-emit bug Upstream emits two events for one comment Optional 10-min category collapse_key merges pending items per user
    3. Accept API -> Kafka retry Broker ack drops on network Kafka idempotent producer (enable.idempotence=true sequence numbers)
    4. Router crashes mid-batch Kafka replays uncommitted partition offsets Deterministic (occurred_at, notification_id) overwrites the identical inbox row
    5. Channel worker crashes Worker crashes right around provider HTTP call 60s Redis claim lease + LOCAL_QUORUM delivery_state check + collapse ID
    6. Provider / network resend APNs/FCM delivers push twice to handset iOS apns-collapse-id / Android notification tag replaces banner in place

    The two-step Redis dedup handshake (pending -> done)

    Why can't the Accept API simply mark tenant:key as done before writing to Kafka? Because if the Kafka write fails a millisecond later, the caller's retry would see done, get 202 duplicate: true, and silently lose the notification forever! Instead, we use a safe two-step claim:

    1. Claim before Kafka: Execute SET dedup:<tenant>:<key> pending:<attempt_id> NX EX 30.
      • If the key already holds done:<notif_id>, immediately return 202 {"duplicate": true}.
      • If it holds another request's pending:..., return 409 Conflict (Retry-After: 1).
    2. Confirm or safely release after Kafka:
      • If Kafka confirms acks=all, overwrite the key with SET dedup:<tenant>:<key> done:<notif_id> EX 3600 (1-hour TTL) and return 202.
      • If Kafka fails, run a tiny Lua compare-and-delete script that deletes the key only if its value is still pending:<attempt_id> (so a slow stalled thread whose 30 s lease expired never accidentally deletes a newer retry's done entry!), and return 503.

    Why 1 hour (~90 GB) instead of 24 hours (~900 GB) or Paxos? Callers retry timeouts over seconds or minutes, not 12 hours later—and even if a retry arrives 2 hours later after Redis evicted the key, the deterministic notification_id overwrites the exact same Cassandra inbox key and stops at delivery_state == 'SENT'! Meanwhile, Cassandra lightweight transactions (INSERT ... IF NOT EXISTS) require multi-round Paxos consensus on every write (crushing throughput at 1M/s), and a Bloom filter has false positives that would silently drop real P0 passcodes.

    Idempotent channel workers, non-blocking retries, and priority isolation

    Channel worker loop (separate worker pools per channel & priority: push.p0, push.p1, push.p2):
      1. Acquire 60s send lease:  SET claim:<notification_id>:<channel> 1 NX EX 60
         -> If already locked by another worker: forward to push.retry.1m and move on
      2. Read delivery_state (LOCAL_QUORUM):
         -> If status in {SENT, DELIVERED, SUPPRESSED, EXPIRED}: skip (already handled!)
      3. Check expires_at, quiet hours, and daily caps:
         -> If expired or capped: write status = EXPIRED / SUPPRESSED and skip
         -> If user in quiet hours (and priority != P0): route to hourly delayed topic
      4. Draw token from local share of provider Token Bucket and call APNs / FCM with collapse ID
      5. Write delivery_state = SENT (LOCAL_QUORUM), then commit Kafka offset
    
    • What if a worker crashes at step 4.5 (after APNs returned 200 OK, before step 5 wrote SENT)? No distributed system can wrap an external HTTP API and an internal database in a shared transaction. After the 60-second claim lease expires, a retry worker sees no SENT record and sends once more—which is the right choice (P0 login codes are never lost, and P1/P2 pushes carry apns-collapse-id / Android tag so the phone replaces the existing alert instead of buzzing twice).
    • Non-blocking retries: Workers never call sleep() on 429/5xx errors (which would stall all users on that Kafka partition). Failed tasks move to push.retry.1m, then push.retry.10m, and after 5 attempts to push.dlq (dead-letter queue). Unregistered tokens (410 Gone) are deleted immediately.
    • Strict P0 isolation: P0 has its own Kafka topics (notif.p0, push.p0), dedicated routers, dedicated sender pools, and 20% of provider send quota permanently reserved (with permission to burst higher), while P2 automatically pauses whenever P1 consumer lag crosses a threshold.
  9. Scaling, failure handling, and trade-off summary

    Operational failure matrix

    Failure Scenario Impact How the System Recovers
    Accept API node crashes mid-request Caller sees socket error Caller retries with same Idempotency-Key; pending expires in ≤30 s; deterministic ID prevents dupes
    Single Kafka broker or whole AZ fails None on durability acks=all + min.insync.replicas=2 across 3 AZs preserves every accepted write
    Redis dedup shard fails over Recent seconds of cache keys lost Retries regenerate identical notification_id, hitting same inbox row and delivery_state == SENT
    Cassandra node down None Remaining 2 of 3 replicas satisfy LOCAL_QUORUM; hinted handoff & repair catch node up
    Push provider (APNs/FCM) outage Push delayed; inbox still live Tasks flow to 1m/10m retry topics; P0 OTPs can fall back to SMS after 10 s
    Poison pill (malformed template/payload) Single message fails render Router catches exception after 3 tries and routes message to DLQ without blocking partition

    Summary of core trade-offs

    • Minimal synchronous accept path vs. immediate validation: Deferring preference checks, rendering, and DB writes behind Kafka shrinks the 1M/s peak-sized tier to stateless API nodes + Redis + Kafka, trading 202 Accepted eventual delivery for massive burst resilience.
    • Drain-sized stateful tiers (~600K/s) vs. peak-sized (~1M/s): Letting Kafka hold a 240M-message buffer for 8 minutes saves ~40% of Cassandra and router hardware that would otherwise sit idle 99% of the day.
    • LSM storage (Cassandra) vs. relational B-trees: Sequential append-only writes absorb 600K+ inserts/s, paid for by multi-SSTable reads and strict schema discipline (TTL-only expiry, TWCS daily buckets, separate inbox_read_marker to avoid tombstones).
    • 1-hour Redis dedup (~90 GB) + deterministic IDs vs. 24-hour RAM (~900 GB) or Paxos: Catches 99.99% of retries at the front door in O(1) memory while relying on deterministic keys and delivery_state for rare late stragglers.

Intuition & how it works

Think of absorbing 1 million bursty notifications per second like managing stadium entry gates during a surprise ticket drop while keeping an emergency VIP lane wide open:

  • If every gate agent stopped to look up each visitor's seating preferences, print a custom booklet, file a paper copy in a cabinet, and call a taxi before letting the next person step through, the entrance would gridlock in seconds—and impatient visitors hitting "refresh" would double the crowd.
  • Instead, the gate agent (Accept API) does only what is required to accept the request safely in ~5 milliseconds: stamp a unique ticket ID in a fast memory ledger so retries aren't counted twice (Redis deduplication cache), append the stub sequentially onto a durable multi-copy tape (Kafka), and reply 202 Accepted (acknowledge immediately, drain asynchronously).
  • Behind the gates, steady worker crews (Routers and Channel Workers) read the tape at a sustainable pace, file inbox copies into sequentially appended daily drawers (Cassandra's log-structured storage), pace external calls to match Apple/Google push rate limits, and keep urgent security codes (P0) on a completely separate express lane from normal activity (P1) and marketing (P2).

Naive designs fail quickly at 1 million writes/s. Performing preference lookups, inbox writes, or push-provider HTTP calls synchronously before acknowledging ties your ingest capacity to external rate limits (~200K pushes/s) and random disk I/O, causing timeouts that trigger retry storms. Conversely, sizing every database and worker pool for 1M/s wastes up to 90% of cluster hardware when average traffic is 100K/s, and sharing one queue across priorities lets a 10-minute marketing or live-news burst delay a user's 2FA login code by 30+ minutes.

Mini concrete walkthrough

Suppose a live tournament play triggers a 1M/s surge (P1), billing-svc sends event inv-408 for user usr_19 (whose HTTP call times out and retries), and auth-svc simultaneously sends a P0 login passcode mfa-31 for usr_19:

  1. inv-408 arrives (Attempt 1): Accept API hashes billing-svc:inv-408:usr_19 into deterministic ID notif_7c2e, claims pending in Redis, writes to notif.p1 in Kafka (acks=all across 2+ availability zones), flips Redis to done (1-hour expiry), and sends 202 (which drops on the network).
  2. inv-408 retries 500 ms later (Attempt 2): Accept API checks Redis, sees done:notif_7c2e, and immediately returns 202 {"notification_id": "notif_7c2e", "duplicate": true} without touching Kafka.
  3. mfa-31 arrives (P0): Routed to dedicated topic notif.p0 and push.p0 workers with reserved APNs/FCM quota, mfa-31 bypasses the 240-million-item P1 surge backlog and reaches usr_19's phone in < 2 seconds.
  4. inv-408 drains (P1): A P1 router reads notif_7c2e from notif.p1, appends (usr_19, 2026-11, occurred_at, notif_7c2e) to Cassandra's commit log and memtable, and enqueues push.p1, where a push worker verifies delivery_state != SENT, calls APNs with apns-collapse-id = notif_7c2e, and records SENT.

Key trade-offs

  • Minimal work before 202 vs. synchronous end-to-end delivery: Putting only authentication, tenant quota checks, Redis dedup, and a durable Kafka write (acks=all, min.insync.replicas=2) before the HTTP response keeps the peak-sized 1M/s tier small and stateless. Doing more before the ack inflates peak infrastructure; doing less (such as acknowledging before Kafka replicates) risks losing accepted notifications if a node crashes.
  • Peak-sized front door vs. drain-sized stateful tiers: Because bursts ramp up in seconds while VM autoscaling takes minutes, Accept APIs, Redis dedup, and Kafka are pre-provisioned for 1M/s. Downstream routers and the 80-node inbox cluster run at ~600K/s (turning a 10-minute 1M/s burst into a 240M Kafka backlog that drains in ~8 minutes), and channel workers + the separate 60-node delivery_state cluster run at provider rate limits (~250K/s), avoiding doubling database fleets for 10-minute spikes.
  • LSM write speed vs. read and compaction costs: Cassandra uses an LSM tree (Log-Structured Merge tree, which appends writes sequentially to a disk commit log and an in-memory memtable, later flushing immutable SSTables—Sorted String Tables—and merging them in background compaction). That makes 600K+ writes/s cheap compared to random B-tree page updates, at the cost of multi-file reads and tombstones (markers left by updates/deletes that slow down reads). We neutralize those costs by keeping inbox_by_user strictly append-only with a 30-day TTL (auto-expiry), TimeWindowCompactionStrategy (dropping whole expired daily files at once), and storing read timestamps separately in inbox_read_marker.
  • 1-hour Redis dedup window (~90 GB) + deterministic IDs vs. 24-hour cache (~900 GB) or Paxos: Remembering 900M keys from the worst burst hour takes ~90 GB across 32 Redis shards using a two-step pending -> done claim. Stretching Redis to 24 hours would cost ~900 GB for almost zero extra hits, because deterministic notification_id hashes and LOCAL_QUORUM (2-of-3 replica) checks on delivery_state already block late duplicates without paying the 4-round-trip consensus penalty of Cassandra IF NOT EXISTS (Paxos).
  • At-least-once + collapse keys vs. impossible external exactly-once: No system can atomically commit an external APNs/FCM HTTP call together with an internal status write. If a worker crashes in the milliseconds right after the provider accepts a push but before delivery_state = SENT is saved, replaying after the 60-second worker claim lease expires resends the push with the same collapse key (an OS notification identifier that overwrites the earlier banner in place rather than buzzing the user twice) while guaranteeing P0 security codes are never lost.
  • Strict priority isolation vs. idle headroom: Dedicated topics, consumer groups, worker pools, and a 20% reserved push token bucket (rate-limiting allowance) for P0 leave small slices of capacity unused during quiet periods so urgent passcodes never wait behind P1/P2 traffic.

Common mistakes

  • Failing to define what counts as "1 write," mixing upstream batch HTTP calls, per-recipient notifications, and downstream delivery-status updates in the same capacity math (or using B ambiguously for both "billion" and "bytes").
  • Performing database lookups, template rendering, or provider HTTP calls synchronously before acknowledging, coupling API availability and latency to the slowest downstream dependency.
  • Partitioning Kafka or Cassandra by timestamp (minute, date) or campaign_id, funneling all 1,000,000 writes/s onto a single hot partition instead of spreading evenly by recipient_id / (user_id, month_bucket).
  • Saying "Cassandra writes fast because it's NoSQL" without explaining sequential commit-log appends, memtables, immutable SSTables, Bloom filters, compaction write amplification, and tombstone pitfalls.
  • Updating each inbox row to is_read = true or running DELETE on old rows, scattering new cells and tombstones across old SSTables and preventing TimeWindowCompactionStrategy from dropping expired daily files cleanly.
  • Setting the Redis dedup key to done before Kafka confirms (without rollback)—or deleting a failed pending key blindly without checking an attempt token, which either drops notifications on a failed Kafka produce or erases a concurrent retry's done marker.
  • Thinking LOCAL_ONE reduces Cassandra write load: All 3 replicas still execute every write; consistency levels only change how many replicas must reply before the coordinator returns, and delivery_state needs LOCAL_QUORUM reads + writes so duplicate checks never miss a just-completed send.
  • Using a Bloom filter for deduplication (whose false positives silently drop real P0 security alerts) or sleeping inside Kafka consumer threads on 429 errors (stalling an entire partition instead of forwarding to 1m/10m delay topics and a dead-letter queue).

Follow-up questions

  • Suppose a 1,000,000-write/s surge continues for 10 minutes while external push gateways enforce a much lower throughput ceiling. How does the backlog behave, and how do urgent passcodes still arrive promptly? Over 600 seconds at 1M/s (600M total notifications, 70% needing push), 420M push tasks are generated while our external push ceiling (~200K/s) sends 120M during those 10 minutes, leaving a 300M-task backlog (~90 GB) safely persisted on disk across notif.p1 and push.p1 in Kafka. Once the surge returns to the 100K/s average (~70K new pushes/s), net push drain is 200K - 70K = 130K/s, clearing the backlog in ~38 minutes worst-case—and much faster in practice because stale live-event updates pass expires_at and drop (remaining readable in the inbox), multiple updates sharing a collapse_key merge into one, and P2 marketing pauses automatically while P1 lags. Urgent P0 passcodes (~10K/s at peak, such as mfa-31) never touch that backlog: they travel through dedicated notif.p0 and push.p0 topics, dedicated routers/workers, and a reserved 20%+ slice of the push token bucket, arriving in under 5 seconds throughout the storm.
  • If a Redis deduplication shard fails over and drops recent state, which duplicate messages could still reach recipients, and how do downstream safeguards contain the impact? Because Redis replicates asynchronously to replicas, failing over a shard can lose the most recent seconds of done keys (or the whole 1-hour window if restarted empty). If an upstream caller retries a request accepted just before the failover, the Accept API misses in Redis and writes a second copy to Kafka—but because notification_id is deterministically hashed from tenant:idempotency_key and created_at = occurred_at, the router overwrites the exact same Cassandra inbox row, and the channel worker's LOCAL_QUORUM lookup on delivery_state sees SENT and skips sending! The only duplicates that can reach a device are retries whose first copy is currently mid-flight at a channel worker if both the dedup shard and the 60-second worker claim shard failed simultaneously. We minimize even that tiny window by enabling Redis appendfsync everysec persistence, placing worker claim: keys on a separate Redis cluster from dedup: keys, rehydrating recent keys from Kafka on shard recovery, and attaching OS collapse IDs to every push.
  • What storage bottlenecks make a B-tree relational engine like PostgreSQL impractical as the main notification store at this write rate? PostgreSQL uses a single write primary per shard and maintains B-tree indexes in place: every random-user insert dirties heap and index pages, writes WAL (write-ahead log, including full-page images after checkpoints), and triggers random disk reads as soon as active indexes exceed RAM, while status updates leave dead tuples that autovacuum struggles to reclaim. A well-tuned single PostgreSQL primary typically tops out around tens of thousands of indexed single-row inserts/s, so sustaining 600K–1M writes/s plus 259 billion stored rows would force us to build and rebalance dozens of manual application-sharded PostgreSQL clusters with hourly/daily partition drop cron jobs. PostgreSQL stops being practical once sustained random-key write throughput outstrips one primary's WAL and B-tree maintenance budget—though it remains ideal for our low-write relational metadata (preferences, templates, campaigns, and quotas).
  • How should the platform execute a single broadcast campaign targeting tens of millions of accounts? Never let an internal caller blast 50 million individual POST /v1/notifications calls at the Accept API. Instead, the caller submits a single POST /v1/campaigns job (P2), and the Campaign Service streams precomputed audience segments in 10,000-user chunks—checkpointing completed chunk numbers and generating deterministic IDs SHA-256(campaign_id + ":" + user_id) so worker restarts never duplicate sends—paced steadily at say 50,000 users/s (~17 minutes for 50M users). Pacing keeps 75% of our 200K/s push quota free for P0 and P1 traffic and spreads user banner taps over 17+ minutes so the app's own backend isn't crushed by a simultaneous tap wave. To save 50M Cassandra inbox writes (~10 GB logical, ~30 GB replicated) on broad announcements, the Inbox API can also use fan-out on read: store one campaign_broadcast row and merge active broadcasts into eligible users' inbox pages when they open the app.

Follow-up questions

Similar questions

More Coreweave interview questions

All 14 Coreweave questions →