Multi-Channel Alerting and Notification Delivery Platform

Medium · System Design · Software Engineer · Onsite

Prompt

Cloud coding environments and real-time team collaboration suites rely on a centralized alerting backbone to reach users across in-app, email, SMS, and mobile push. Events range from urgent one-time sign-in passcodes (login.passcode) and live coding session invites (session.invite) to CI build failures (build.broken) and weekly product summaries (digest.weekly). Each event must reach the right surfaces quickly without violating recipient consent, local sleep windows, or rate ceilings.

Architect an end-to-end notification delivery service that ingests producer events, resolves recipient settings and localized templates, dispatches messages through external channel vendors, and tracks every delivery target across its full lifecycle:

  • Channel fan-out & recipient controls: Map a single logical alert to one or more channels (in_app, email, sms, push) according to event urgency and user settings, enforcing per-channel toggles, category opt-outs, time-zone-aware quiet hours, and per-user frequency caps.
  • Localized templating: Populate channel-specific payloads from versioned templates parameterized by recipient locale and structured event fields.
  • Explicit delivery states: Track distinct milestones from ACCEPTED (durably persisted by our API) to DISPATCHED (handed off to an external vendor), DELIVERED (confirmed via vendor callback), and terminal non-delivery outcomes.
  • Future scheduling, cancellation, & deduplication: Support deferred delivery timestamps (for instance, sending 90 minutes from now), cancel pending secondary deliveries before handoff (such as aborting email or push once the user opens the alert in-app), and guarantee idempotency across caller or worker retries.
  • Scale, latency, resilience, & compliance: Serve 10M daily active users and 50M notifications per day (~600 requests/s average, 5,000 requests/s peak burst). Hand off critical alerts (passcodes, live session invites) to downstream providers in under 1 second, while digests and promotional sends may complete within minutes. Absorb vendor outages without dropping alerts via exponential backoff retries and fallback paths, retain audit trails for transactional messages, and strictly honor promotional unsubscribes.

Scope & Expectations

  • External & internal APIs: Specify endpoints and semantics for submitting notifications, querying per-channel delivery progress, and cancelling pending sends.
  • System topology & message flow: Walk through request intake, preference and template resolution, queue isolation, worker dispatch, and third-party vendor integrations.
  • Storage schema: Define the data model for parent notifications, per-channel delivery state machines, user preferences/consent, templates, and audit history.
  • Concurrency & failure edge cases: Address race conditions around last-millisecond cancellations and out-of-order vendor webhooks, alongside provider rate-limit enforcement and fallback routing.

Step-by-step walkthrough

  1. Clarify requirements and edge-case rules

    At 5,000 requests per second at peak, raw traffic volume is not the hardest part of this design—a handful of stateless web servers can parse 5,000 JSON requests per second easily. The real challenge is correctness across asynchronous steps:

    • A developer opens an alert inside the workspace IDE at the exact millisecond a worker is about to send the matching email.
    • A downstream SMS gateway times out, and retrying blindly could text the user twice—or not retrying could drop a sign-in passcode.
    • A vendor's "DELIVERED" webhook (an HTTP callback from the provider) arrives over the network before our own worker finishes saving "DISPATCHED" to the database.
    • A recipient clicks "unsubscribe" today on a promotional digest that was scheduled yesterday.

    Clarifying these rules up front shapes every table, queue, and worker in the system.

    Functional requirements

    • Multi-channel routing: Internal services (live coding sessions, CI builds, authentication, billing, growth) submit one logical notification for a recipient. The platform selects one or more channels (in_app, email, sms, push) based on event urgency and user settings.
    • Preferences and consent: Respect per-channel toggles, per-category opt-outs, local-time quiet hours, and per-user frequency caps (limits on how many non-urgent alerts a user receives per hour or day).
    • Templating and localization: Render channel-specific messages in the user's preferred language (es-MX -> es -> en fallback).
    • Clear delivery lifecycle: Track ACCEPTED (durably received by our API), DISPATCHED (accepted by the external provider), DELIVERED (confirmed by provider webhook), and terminal non-delivery states (UNDELIVERED, FAILED, CANCELLED, SUPPRESSED, EXPIRED).
    • Scheduling and cancellation: Support future send_at timestamps (for example, 90 minutes ahead), explicit API cancellation, and automatic cross-channel cancellation (opening an in-app alert cancels pending push or email copies).
    • Idempotency (safe retries): Ensure upstream caller retries and internal worker retries never send duplicate notifications.

    Non-functional requirements and design assumptions

    • Scale: 10M daily active users (DAU), 50M notifications/day (~580–600 requests/s average, 5,000 requests/s peak).
    • Latency: critical alerts (login.passcode, session.invite) reach the external provider (ACCEPTED -> DISPATCHED) in < 1 second at p99; low urgency digests/promotions can take minutes.
    • Urgency ownership: Callers pass a category (such as login.passcode or build.broken), not a raw priority. A platform-owned category registry maps each category to its urgency (critical, high, normal, low), message type (transactional vs. promotional), and channel timing policy. That prevents a bulk digest job from labeling itself critical.
    • Critical override: critical transactional messages (like sign-in passcodes) bypass opt-outs, quiet hours, and frequency caps so users cannot lock themselves out, though they still require a verified phone number or email.
    • Fault tolerance and compliance: Survive external vendor outages via exponential backoff retries, secondary providers, and cross-channel fallback. Retain operational status for 30 days and immutable transactional audit logs for 2 years.
  2. Back-of-the-envelope capacity estimates

    Walking through the numbers reveals where the real bottlenecks sit—and proves early that we cannot rely on a single SMS vendor.

    1. Incoming notification requests
       50M / 86,400 seconds/day     = ~580 requests/s average (~600/s rounded)
       Peak burst (given)           = 5,000 requests/s (~8.6x average)
    
    2. Channel fan-out (~1.6 channel deliveries per notification on average)
       in_app   45.0M/day   ~520/s avg    ~4,500/s peak
       push     20.0M/day   ~230/s avg    ~2,000/s peak
       email    13.5M/day   ~160/s avg    ~1,350/s peak
       sms       1.5M/day    ~17/s avg      ~150/s peak  (~90/s passcodes + ~60/s urgent alerts)
       -----------------------------------------------------------------------------------
       Total    80.0M/day   ~930/s avg    ~8,000/s peak deliveries
    
    3. Database writes at peak (counting every table write)
       notifications inserts                    5,000/s
       idempotency_keys inserts                 5,000/s
       inbox_items inserts (in-app channel)     4,500/s
       deliveries (insert + ~3 state updates)  32,000/s  (4 x 8,000/s)
       delivery_events (append-only history)   32,000/s
       -----------------------------------------------------------------------------------
       Total row writes at peak               ~78,500 row writes/s (~42,000 transactions/s)
       Across 16 Postgres shards              ~2,600 transactions/s (~4,900 row writes/s) per shard
    
    4. Storage
       Operational hot data (30 days):
         notifications (50M x 1 KB)     =  50 GB/day
         deliveries (80M x 500 B)       =  40 GB/day
         delivery_events (320M x 150 B) =  48 GB/day
         Total = 138 GB/day x 30 days   = ~4.1 TB primary (~8.3 TB with 1 synchronous replica)
       In-app inbox (90 days):
         45M/day x 90 x 300 B           = ~1.2 TB across 16 shards
       Transactional audit archive (60% of deliveries, 2 years in object storage):
         48M/day x 4 events x 200 B     = ~38 GB/day raw (~14 TB/year raw, ~3.5 TB/year compressed)
    
    5. Redis memory
       Preferences cache (10M DAU x 1 KB)                      = ~10 GB
       Frequency-cap counters (10M x 3 channels x 2 windows)   = ~5 GB
    

    Two immediate takeaways from the math:

    1. Postgres can handle the state machine comfortably: ~2,600 small local transactions per second per shard is well within the capacity of modern NVMe-backed Postgres instances.
    2. External vendor quotas are the tightest bottleneck: Peak SMS demand is ~150 messages/s, whereas a standard commercial SMS trunk (for example, a 100 SMS/s carrier tier) caps out at 100 messages/s. A secondary SMS provider and priority capacity reservation are mandatory from day one.
  3. API design

    Every write endpoint requires an Idempotency-Key—a unique request ID generated by the caller for that specific logical event (for example, "build-broken-bld_618"). If the caller times out and sends the exact same request again, our API returns the original notification_id instead of creating a duplicate.

    Internal Producer API (authenticated via service-to-service mTLS)
    -----------------------------------------------------------------
    POST /v1/notifications
      Headers:  Idempotency-Key: <unique caller event key>   (required)
      Body:     {
                  "user_id": "usr_704",
                  "category": "build.broken",
                  "params": {"workspace": "checkout-service", "build_id": "bld_618"},
                  "send_at": "2026-12-02T19:30:00Z",         // optional; omit for immediate
                  "expires_at": "2026-12-02T21:30:00Z",      // optional; defaults per category
                  "channels": ["in_app", "email"],           // optional; can only narrow policy
                  "group_key": "build:bld_618"               // optional; collapses rapid bursts
                }
      Responses:
        202 Accepted   {"notification_id": "ntf_0812-01K...", "status": "ACCEPTED"}
        200 OK         same body when replaying an already-accepted Idempotency-Key
        422 Unprocessable  IDEMPOTENCY_KEY_REUSED (same key, different payload) | UNKNOWN_CATEGORY
        429 Too Many Requests  caller service exceeded its quota (includes Retry-After)
    
    POST /v1/notifications:batch
      Up to 500 notifications, each carrying its own idempotency_key; returns per-item status.
    
    GET /v1/notifications/{notification_id}
      200 OK  {
                "notification_id": "ntf_0812-01K...",
                "status": "ACCEPTED | ROUTED | COMPLETED | CANCELLED | SUPPRESSED",
                "deliveries": [
                  {"delivery_id": "dlv_0812-01K...", "channel": "in_app", "state": "DELIVERED", ...},
                  {"delivery_id": "dlv_0812-02L...", "channel": "email",  "state": "SCHEDULED",
                   "scheduled_for": "2026-12-02T18:10:00Z", "attempts": 0}
                ]
              }
    
    POST /v1/notifications/{notification_id}:cancel
      Body:  {"channels": ["email", "push"], "reason": "viewed_in_app"}
      200 OK {"cancelled": ["email"], "too_late": [{"channel": "push", "state": "DISPATCHED"}]}
    
    User & Provider Endpoints
    -----------------------------------------------------------------
    GET  /v1/me/inbox?cursor=...                     fetch paginated in-app alerts
    POST /v1/me/inbox/{notification_id}:read         marks read AND cancels pending sibling channels
    GET | PUT /v1/me/preferences                     manage channel toggles, opt-outs, quiet hours
    POST /v1/unsubscribe?token=...                   RFC 8058 one-click signed unsubscribe
    POST /v1/webhooks/{provider}                     HMAC-verified delivery status callbacks
    

    Why these API choices matter:

    • 202 Accepted means durable, not delivered: Calling an external SMS or email vendor inside the HTTP handler would tie our API availability and latency to third-party outages.
    • Cancel is a POST returning per-channel outcomes, not DELETE: Cancellation is a race. Push may already be DISPATCHED while email is still SCHEDULED; returning cancelled and too_late lists tells the caller the exact truth.
    • channels can only narrow, never force: A caller can restrict an alert to ["in_app"], but cannot force SMS onto a user who opted out of SMS.
  4. Data model and delivery state machine

    We store operational state in PostgreSQL sharded by user_id across 16 shards (each shard runs a primary and one synchronous replica in another availability zone so a machine failure loses zero committed rows).

    Why shard by user_id using virtual buckets? Every user hashes to one of 4,096 logical buckets (hash(user_id) mod 4096), and a tiny lookup map assigns buckets to the 16 physical shards. We prefix every notification_id (ntf_0812-...) and delivery_id (dlv_0812-...) with its 4-digit bucket number. That gives us two big wins:

    1. Creating a notification, inserting its in-app inbox row, or cancelling its pending email/push when the user opens the inbox item is a single local ACID transaction on one shard—no distributed two-phase commits.
    2. Lookups by notification_id or delivery_id (such as status queries and incoming provider webhooks) know which shard to hit immediately from the ID prefix, without needing user_id.
    Shard Tables (16 Postgres shards, co-located by user_id bucket)
    -----------------------------------------------------------------
    notifications (daily partitions on created_at; dropped after 30 days)
      notification_id ("ntf_<bucket>-<ULID>"), user_id, client_id, category, urgency,
      type (transactional | promotional), params (JSONB), send_at, expires_at,
      group_key, status (ACCEPTED | ROUTED | ...), created_at
    
    idempotency_keys (unpartitioned; trimmed after 7 days in small background batches)
      PRIMARY KEY (user_id, client_id, idempotency_key)
      notification_id, body_hash, created_at
    
    deliveries (one row per notification x channel; unpartitioned, trimmed after 30 days)
      delivery_id ("dlv_<bucket>-<ULID>"), notification_id, user_id, channel, provider,
      state, reason, attempts, lease_until, due_at, template_version, provider_message_id,
      accepted_at, scheduled_for, queued_at, dispatched_at, delivered_at, finished_at
      UNIQUE (notification_id, channel)
      INDEX (due_at) WHERE state IN ('SCHEDULED', 'RETRY_WAIT')
      INDEX (lease_until) WHERE state = 'SENDING'
    
    delivery_events (append-only history; daily partitions dropped after 30 days)
      delivery_id, occurred_at, event, source (worker | webhook | api | scheduler),
      provider_event_id, details
    
    inbox_items (in-app channel; 90-day retention)
      PRIMARY KEY (user_id, notification_id), title, body, deep_link, created_at, read_at
    
    Preferences & Templates (dedicated Postgres, cached in Redis)
    -----------------------------------------------------------------
    preferences:    user_id, timezone ("America/Toronto"), locale ("en-CA"),
                    quiet_hours {"start": "22:00", "end": "08:00"},
                    channels {"email": true, "push": true, "sms": false},
                    category_opt_outs ["digest.weekly"], version
    contact_points: user_id, channel, address_or_token, verified
    consent_log:    append-only legal log of every opt-in / opt-out / STOP / hard bounce
    suppressions:   address, reason (hard_bounce | spam_complaint), created_at
    templates:      (template_id, channel, locale, version) -> subject, body
    

    Why keep idempotency_keys and deliveries unpartitioned? In Postgres, a UNIQUE index on a partitioned table must include the partition column (created_at). If idempotency_keys were partitioned by day, a retry crossing midnight would bypass uniqueness and send a duplicate! Keeping those two tables unpartitioned preserves global uniqueness per user/notification, and deleting expired rows in small batches costs only ~95 row deletes/s per shard (~58 deliveries/s + ~36 keys/s). Append-only tables (notifications, delivery_events) use daily partitions so 30-day cleanup is an instant DROP TABLE.

    Per-channel delivery state machine

    Once the API saves the parent notification as ACCEPTED, the router creates one deliveries row per target channel and drives it through an explicit state machine:

                          +--- due_at reached ---> QUEUED --- atomic claim ---> SENDING
                          |                          ^                             |
      (future send_at,    |                          | (backoff due)               +--> 2xx ---------> DISPATCHED --> DELIVERED
       quiet hours, or -> SCHEDULED             RETRY_WAIT <-- 429 / 5xx / net ----+                      \---------> UNDELIVERED
       escalation delay)                             |                             +--> 4xx permanent -> FAILED
                                                     |                             \--> crash/timeout -> UNKNOWN (or safe resend)
      From SCHEDULED, QUEUED, or RETRY_WAIT:
        - user read / API :cancel  --> CANCELLED
        - opt-out / cap exceeded   --> SUPPRESSED
        - now > expires_at         --> EXPIRED
    
      Terminal states (never change once reached):
        DELIVERED, UNDELIVERED, FAILED, CANCELLED, SUPPRESSED, EXPIRED
    
  5. High-level architecture and the sub-second fast lane

    We decouple fast synchronous request intake from variable-speed external channel delivery using Apache Kafka (a distributed, durable append-only message broker) partitioned into isolated lanes by urgency and channel.

     Caller Services
           | POST /v1/notifications (with Idempotency-Key)
           v
     [ Ingestion API ] -- 1. local TX: insert notification + idempotency_key --> [ Postgres (16 shards) ]
           | 2. publish after commit (sweeper catches rare publish crashes)               ^
           v                                                                              |
     [ Kafka Ingestion Topics: notif.critical | notif.high | notif.normal | notif.low ]   |
           |                                                                              |
           v                                                                              |
     [ Router Workers (one pool per urgency) ] -- read cached prefs/templates ----------->+
           |  insert deliveries rows (UNIQUE notification_id, channel)                    |
           +-----------------------------------+------------------------------------------+
           | immediate (due now)               | delayed (send_at, quiet hours, escalation)
           v                                   v
     [ Kafka Delivery Lanes ]             [ SCHEDULED / RETRY_WAIT rows in Postgres ]
       deliver.sms.critical                    |  polled every 1 s (FOR UPDATE SKIP LOCKED)
       deliver.push.standard   <---------------+  by per-shard Scheduler Workers
       deliver.email.bulk
           |
           v
     [ Dispatcher Workers (per channel + lane) ]
       1. render template + re-check consent & user frequency cap (Redis)
       2. acquire vendor rate-limit token (Redis)
       3. atomic DB claim: QUEUED -> SENDING
       4. call vendor API with Idempotency-Key = delivery_id
           |
           +---> [ SMS A | SMS B ]   [ Email A | Email B ]   [ APNs | FCM ]   [ Inbox + WebSocket ]
                       |
                       | async status webhooks
                       v
              [ Webhook Receiver ] --> [ Kafka: provider-events ] --> [ Status Writer ] -> Postgres
    

    Why split queues by both urgency and channel? A Kafka partition is strictly first-in, first-out (FIFO). If a 5-million-user weekly digest shared a queue with sign-in passcodes, passcodes would sit behind millions of digest emails and miss the 1-second SLA. Isolating notif.critical -> deliver.sms.critical with dedicated consumer pools guarantees that bulk traffic never blocks urgent alerts, and an email vendor outage never stalls push or SMS workers.

    How we publish safely without slowing down the critical path: The Ingestion API commits to Postgres first and then publishes to Kafka. What if the API server crashes in the millisecond between the Postgres commit and the Kafka publish? A lightweight sweeper job scans for ACCEPTED notifications (and QUEUED deliveries) older than their lane's current consumer lag plus 5 seconds and republishes them. Downstream UNIQUE (notification_id, channel) constraints and atomic worker claims make duplicate Kafka messages completely harmless.

    End-to-end latency budget for a < 1 s critical passcode alert:

    Ingestion API (auth, validate, Postgres commit across AZ, Kafka publish) :  15 - 30 ms -> return 202
    Router (consume notif.critical, Redis prefs lookup, insert delivery, pub):  15 - 35 ms
    Dispatcher (consume deliver.sms.critical, render, token, DB claim)       :  10 - 20 ms
    --------------------------------------------------------------------------------------
    Total internal platform latency                                          :  40 - 85 ms typical (< 250 ms p99)
    External SMS provider HTTP call (strict socket timeout)                  : <= 700 ms
    --------------------------------------------------------------------------------------
    Total ACCEPTED -> DISPATCHED                                             : < 950 ms at p99
    
  6. Deep dive 1: atomic claim and cross-channel cancellation

    Suppose a teammate sends a live coding invite (session.invite) or a build breaks (build.broken). If we fire the in-app alert, mobile push, and email at the exact same millisecond, cross-channel cancellation is impossible—the push and email are already gone before the recipient can even click the in-app banner!

    Step 1: Deliberate escalation delays in the category policy. Each category defines when secondary channels fire so the user has a window to view the alert in-app first:

    Category          Urgency    Channel Escalation Policy
    ---------------------------------------------------------------------------------------
    login.passcode    critical   SMS immediately; email fallback at +30 s if SMS fails
    session.invite    high       in_app immediately; push at +60 s if unread & user offline
    build.broken      high       in_app + push immediately; email at +10 min if still unread
    digest.weekly     low        email within send window (respecting quiet hours)
    

    Also, our WebSocket gateway maintains an online presence flag in Redis (online:usr_704, refreshed every 30 s with a 60 s TTL). If the user is actively connected in the workspace browser, the router can hold or skip push while waiting to see if they open the live banner.

    Step 2: Atomic state check immediately before calling the provider. Never write worker code that does SELECT state FROM deliveries followed by if state == 'QUEUED': send_email(). Between the SELECT and send_email(), the user might open the in-app alert and cancel the notification, causing a race where our API reports "cancelled" and the user still gets the email.

    Instead, the dispatcher performs all slow preparation first (template rendering, consent re-check, acquiring a vendor rate-limit token) and then executes one atomic conditional UPDATE milliseconds before the network call:

    -- Dispatcher: atomically claim the delivery right before calling the external vendor.
    -- Under Postgres row locking, if a concurrent cancel runs at the same instant,
    -- one statement wins and the other matches 0 rows.
    UPDATE deliveries
       SET state = 'SENDING',
           attempts = attempts + 1,
           lease_until = now() + interval '10 seconds'
     WHERE delivery_id = :delivery_id
       AND state = 'QUEUED'
    RETURNING attempts;
    
    -- Inbox read / Cancel API (runs in the same local shard transaction as setting read_at):
    UPDATE deliveries
       SET state = 'CANCELLED',
           reason = :reason,
           finished_at = now()
     WHERE notification_id = :notification_id
       AND channel IN ('email', 'push')
       AND state IN ('SCHEDULED', 'QUEUED', 'RETRY_WAIT')
    RETURNING channel;
    

    Walk through both race timings on build.broken (ntf_0812-...):

    Case A: User opens in-app alert at +3 min (email due at +10 min)
      1. Email row is sitting in Postgres with state = 'SCHEDULED'.
      2. POST /me/inbox/{id}:read sets read_at AND updates email to 'CANCELLED' in 1 transaction.
      3. At +10 min, the scheduler queries WHERE state IN ('SCHEDULED', 'RETRY_WAIT') — skips it!
    
    Case B: User opens in-app alert at +10 min 00.050 s (email already pushed to Kafka)
      1. Cancel transaction commits state = 'CANCELLED' at 00.050 s.
      2. Dispatcher finishes rendering at 00.055 s and runs UPDATE ... WHERE state = 'QUEUED'.
      3. Postgres returns 0 rows updated -> dispatcher drops the job without calling the email vendor!
    

    What about deferred messages (send_at 90 minutes out, quiet-hour deferrals, or retry backoffs)? They all use the exact same mechanism: a row in SCHEDULED or RETRY_WAIT with due_at. Once per second per shard, scheduler workers run SELECT ... WHERE state IN ('SCHEDULED', 'RETRY_WAIT') AND due_at <= now() ORDER BY due_at LIMIT 500 FOR UPDATE SKIP LOCKED (SKIP LOCKED lets multiple scheduler workers share the table without blocking each other), flip state to 'QUEUED', and publish to Kafka. Because timers live in the same deliveries row, cancelling a 90-minute scheduled send is just the same single-row UPDATE above!

  7. Deep dive 2: dual idempotency keys and out-of-order webhooks

    Retries happen at two separate network boundaries, so we maintain two distinct idempotency keys:

    1. Inbound key ((user_id, client_id, Idempotency-Key)): Protects POST /v1/notifications. When an internal caller retries after a gateway timeout, INSERT INTO idempotency_keys ... ON CONFLICT DO NOTHING catches the duplicate inside the user's shard transaction. If the request payload hash matches, we return the existing notification_id; if the caller accidentally reused a key for a different payload, we return 422.
    2. Outbound key (delivery_id): Protects Dispatcher -> External Provider. One incoming notification fans out into multiple channels, so we cannot pass the caller's key to every vendor—and we must never append attempt (dlv_123_attempt_2), because that would look like a brand-new message on retry! Passing the stable delivery_id lets providers that support idempotency (such as Postmark, SendGrid custom args, or SMS client references) deduplicate retries after a network timeout.

    What if a worker crashes or times out mid-call (SENDING lease expires) and the vendor doesn't deduplicate? A background lease sweeper spots state = 'SENDING' AND lease_until < now(). Because we cannot know whether the vendor sent the message before the connection dropped, we resolve the ambiguity based on business impact:

    • critical (login.passcode): Resend immediately (switching to secondary SMS provider B if A is timing out). Receiving two identical passcodes is harmless; receiving zero locks the user out.
    • Other transactional (build.broken, billing receipt): Query the vendor's message-lookup API by delivery_id if supported; otherwise resend once.
    • promotional (digest.weekly): Never blind-resend—spamming users twice erodes trust. Mark UNKNOWN (a late delivery webhook can still promote it to DELIVERED).

    Handling out-of-order webhooks (DELIVERED arriving before DISPATCHED): A fast vendor can deliver an SMS and fire its DELIVERED webhook in 80 ms, reaching our Status Writer before the Dispatcher finishes recording the HTTP 200 response (DISPATCHED). Worse, providers retry webhooks if our endpoint blinks.

    First, our Webhook Receiver verifies the vendor's cryptographic signature, pushes the raw payload onto Kafka (provider-events), and returns 200 OK in a few milliseconds so vendors never time out. We pass delivery_id in the outbound request's custom metadata or callback URL so the webhook identifies our row directly without waiting for provider_message_id.

    Second, both the Dispatcher and Status Writer follow two strict database rules—states only move forward and timestamps fill in, never overwrite:

    -- 1. Status Writer applying a 'DELIVERED' webhook (arrives first at t = 120 ms):
    UPDATE deliveries
       SET state = 'DELIVERED',
           delivered_at = :webhook_ts,
           finished_at = :webhook_ts,
           provider_message_id = COALESCE(provider_message_id, :provider_msg_id)
     WHERE delivery_id = :delivery_id
       AND state IN ('SENDING', 'DISPATCHED', 'UNKNOWN');
    
    -- 2. Dispatcher recording its HTTP 2xx response (arrives late at t = 150 ms):
    --    COALESCE keeps existing timestamps; CASE refuses to downgrade 'DELIVERED' back to 'DISPATCHED'!
    UPDATE deliveries
       SET provider_message_id = COALESCE(provider_message_id, :provider_msg_id),
           dispatched_at = COALESCE(dispatched_at, :dispatched_ts),
           state = CASE
                     WHEN state IN ('SENDING', 'UNKNOWN') THEN 'DISPATCHED'
                     ELSE state
                   END
     WHERE delivery_id = :delivery_id;
    
    Mini-trace of out-of-order arrival:
      t = 050 ms : Dispatcher claims row -> state = 'SENDING'
      t = 120 ms : Webhook 'DELIVERED' arrives first -> allowed from 'SENDING'!
                   Row becomes: state = 'DELIVERED', delivered_at = 115 ms, dispatched_at = NULL
      t = 150 ms : Dispatcher finishes HTTP response -> CASE sees state = 'DELIVERED', keeps 'DELIVERED',
                   and fills in dispatched_at = 095 ms! Final row is 100% complete and accurate.
    

    (Note on mobile push: standard APNs and FCM APIs confirm handoff to Apple/Google—DISPATCHED—but do not send per-message DELIVERED webhooks. Push stops at DISPATCHED unless our mobile app SDK explicitly pings a receipt endpoint when a background notification wakes the app.)

  8. Deep dive 3: preferences, time-zone quiet hours, rate limits, and fallback

    Time-zone-aware quiet hours Storing quiet hours as fixed UTC offsets (like UTC-5) breaks twice a year whenever daylight saving time shifts! Instead, we store the user's IANA time zone name (such as "America/Toronto") and evaluate local wall-clock time:

    from datetime import datetime, time, timedelta, timezone
    from zoneinfo import ZoneInfo
    
    
    def quiet_hours_end(
        now_utc: datetime,
        tz_name: str,
        quiet_start: time,
        quiet_end: time,
    ) -> datetime | None:
        """Return the UTC timestamp when quiet hours end if now_utc falls inside them, else None."""
        user_tz = ZoneInfo(tz_name)
        local_now = now_utc.astimezone(user_tz)
        local_clock = local_now.time()
    
        # Case 1: Same-day window (e.g., 13:00 to 15:00)
        if quiet_start <= quiet_end:
            is_quiet = quiet_start <= local_clock < quiet_end
        # Case 2: Overnight window crossing midnight (e.g., 22:00 to 08:00)
        else:
            is_quiet = local_clock >= quiet_start or local_clock < quiet_end
    
        if not is_quiet:
            return None
    
        # If it is 23:30 in an overnight window, quiet hours end tomorrow morning at 08:00.
        wake_date = local_now.date()
        if quiet_start > quiet_end and local_clock >= quiet_start:
            wake_date = wake_date + timedelta(days=1)
    
        wake_local = datetime.combine(wake_date, quiet_end, tzinfo=user_tz)
        return wake_local.astimezone(timezone.utc)
    

    When a non-critical push or SMS lands inside quiet hours, the router schedules it for wake_utc + random(0, 15 minutes) (adding random jitter prevents a thundering herd of millions of notifications firing at 08:00:00 sharp in major time zones). If expires_at is earlier than wake_utc, the row is marked SUPPRESSED (QUIET_HOURS_EXPIRED) instead.

    Two separate rate limiters for two separate problems

    Limiter Question it answers Redis structure What happens when full
    Per-user frequency cap "Have we annoyed usr_704 too much today?" (e.g., max 4 pushes/hour, 20 alerts/day) Atomic counter cap:{user_id}:{channel}:{hour} checked right before QUEUED -> SENDING claim critical bypasses; normal defers to next window; low becomes SUPPRESSED (FREQ_CAP)
    Vendor throughput quota "Can SMS Provider A accept another request this second?" (e.g., 100 SMS/s contract) Token bucket per vendor account refilled at 100 tokens/s, max capacity 30 tokens Overflow routes immediately to secondary Provider B, or enters RETRY_WAIT if all vendors are saturated

    Why cap the 100/s vendor token bucket at 30 tokens with a 20-token reserve? A token bucket is a counter that refills steadily at R tokens/second up to capacity B. After an idle second, a bucket can burst B stored tokens plus R newly refilled tokens in one second—so setting B = 100 could send 200 SMS in 1 second and trigger vendor 429 rejections! Keeping B = 30 limits bursts, and requiring standard/bulk workers to leave at least 20 tokens untouched reserves instant headroom for critical passcode spikes. At peak (~90/s passcodes + ~60/s alert SMS), passcodes take ~90/s on Provider A, alert SMS takes the remaining ~10/s on A, and the other ~50/s alert SMS automatically spill over to Provider B.

    Circuit breakers, fallback, and strict compliance Each vendor adapter wraps calls in a circuit breaker—a safety switch that trips "open" when >50% of calls fail over 20 seconds (minimum 20 calls), routing new attempts straight to the backup vendor and probing recovery with a few test calls every 30 seconds. If SMS as a whole cannot deliver a sign-in passcode within 30 seconds, the router triggers channel fallback by creating an email delivery row. Finally, dispatchers re-check user consent right before claiming (using cached preferences invalidated within seconds by unsubscribe/STOP events), ensuring a promotional digest scheduled yesterday is marked SUPPRESSED (UNSUBSCRIBED) today.

  9. Scaling, failure modes, and trade-off summary

    Failure scenario Impact Recovery mechanism
    API crashes after DB commit, before Kafka publish Row sits in ACCEPTED Lag-aware sweeper republishes after consumer_lag + 5 s; UNIQUE (notification_id, channel) prevents duplicates
    Dispatcher crashes after calling vendor Row stuck in SENDING past 10 s lease Lease sweeper resolves per category (resend passcode, lookup transactional, mark promo UNKNOWN)
    Postgres shard primary fails 1/16 of users see 503 for ~20–30 s Synchronous cross-AZ replica promotes with zero data loss; callers safely retry with same Idempotency-Key
    Redis cluster unavailable Prefs cache, caps, and token buckets unreachable Read preferences from Postgres read replicas; bypass frequency caps for transactional, pause promotional; fall back to static per-worker vendor rate shares
    All vendors for a channel down Deliveries cannot dispatch Exponential backoff with jitter (10 s, 30 s, 2 m, 10 m...) in RETRY_WAIT up to expires_at—zero dropped alerts

    Key operational metrics to page on: - ACCEPTED -> DISPATCHED p99 latency on critical lanes (page if > 1 s for 5 minutes). - DISPATCHED -> DELIVERED conversion rate per vendor (catches silent carrier filtering or broken sender reputation even when HTTP calls return 200). - Count of expired SENDING leases, too_late cancellations, and consumer lag per lane.

    Core trade-offs in one view: - Sharded Postgres vs. NoSQL key-value store: Sharding requires bucket management, but gives local multi-row transactions and single-query conditional UPDATE state transitions. - Per-urgency and per-channel Kafka lanes vs. a single topic: More topics and worker pools to operate, in exchange for strict latency and fault isolation for < 1 s critical traffic. - Deliberate escalation delays vs. simultaneous fan-out: Non-critical emails wait a few minutes so in-app reads can cancel them cleanly, drastically cutting notification fatigue.

Intuition & how it works

Think of a multi-channel notification platform like a hospital paging desk. When a doctor needs to be reached, the desk first logs the request in a permanent ledger (ACCEPTED). Depending on urgency, it doesn't blindly blast the overhead loudspeaker, text pager, and home phone all at once: for a routine chart note, it drops a message in the doctor's inbox and sets a 10-minute timer to send an email only if the note stays unread; for a Code Blue emergency (critical), it takes the express lane straight to the pager immediately. Right before dialing any external line, the operator checks the ledger one last time to verify the alert wasn't cancelled a split-second earlier.

A naive implementation—validating the request, rendering templates, and calling email, SMS, and push APIs synchronously inside the POST /notifications HTTP handler—breaks down immediately in production. First, if an external SMS vendor slows down or goes offline, your API threads hang and callers time out and retry, sending duplicate texts and emails. Second, a 5-million-message weekly digest clogs the exact same workers needed for sub-second sign-in passcodes. Third, firing every channel simultaneously makes cross-channel cancellation ("don't email me if I already opened it in the app") physically impossible.

Walk through a concrete 4-event trace for notification ntf_9 (build.broken for user usr_42):

  1. t = 0 s (Ingest): The CI build service calls POST /v1/notifications with Idempotency-Key: "bld-618". The API stores ntf_9 (ACCEPTED) and key "bld-618" in usr_42's database shard, publishes to notif.high in Kafka (a durable distributed message queue), and returns 202 Accepted in 20 ms.
  2. t = 0.04 s (Route): A router worker reads usr_42's cached preferences and creates two rows in deliveries: dlv_inbox (QUEUED now) and dlv_email (SCHEDULED with due_at = +10 min). dlv_inbox writes to inbox_items and pushes live over WebSocket (DELIVERED).
  3. t = 3 min (Read & Cancel): User usr_42 clicks the in-app banner (POST /me/inbox/ntf_9:read). In a single local database transaction, we set read_at on the inbox row and run UPDATE deliveries SET state = 'CANCELLED' WHERE notification_id = 'ntf_9' AND state IN ('SCHEDULED', 'QUEUED', 'RETRY_WAIT'), cancelling dlv_email.
  4. t = 10 min (Schedule check): When +10 minutes arrives, the scheduler only picks up rows still in SCHEDULED, so dlv_email is cleanly skipped and usr_42's email inbox stays clutter-free.

Key trade-offs

  • Postgres sharded by user_id vs. a managed NoSQL key-value store. Sharding Postgres (splitting rows across 16 independent databases by hashing user_id) requires maintaining a bucket-to-shard map, whereas a managed store like DynamoDB partitions automatically. In exchange, co-locating all of one user's data on one Postgres shard lets us create a notification with its deliveries—or mark an in-app item read and cancel its pending email/push—inside a single local ACID transaction (an all-or-nothing database operation), and enforce state transitions with simple conditional SQL UPDATE statements.
  • Separate Kafka topics per urgency and channel vs. one shared queue. A Kafka partition processes messages strictly first-in, first-out (FIFO), so putting weekly digests and sign-in passcodes in the same queue lets a bulk send delay login codes by minutes. Running separate lanes (deliver.sms.critical vs. deliver.email.bulk) adds operational overhead (more topics and consumer groups to monitor) but guarantees < 1 s latency isolation and prevents an email provider outage from stalling SMS or push workers.
  • Publish-after-commit with a lag-aware sweeper vs. a transactional outbox. Writing to a transactional outbox (a database staging table tailed by a separate relay process) guarantees every committed row reaches Kafka, but adds an extra polling/log-tailing hop on the hot path. Publishing directly to Kafka right after commit shaves tens of milliseconds off the 1-second critical budget, while a background sweeper republishes any row stranded by a rare mid-request crash.
  • Deliberate escalation delays vs. simultaneous multi-channel delivery. Holding push for 60 seconds and email for 10 minutes gives active users time to view the in-app banner and cancel redundant pings. The trade-off is slightly slower email delivery when the user is away from the app, which is why critical alerts never wait.
  • Category-specific handling of unknown timeouts vs. a single retry rule. When a vendor HTTP call times out without confirming receipt, retrying risks a duplicate send while not retrying risks dropping the alert (unless the vendor supports outbound idempotency). Resending critical passcodes prioritizes reachability, whereas marking timed-out promotional sends as UNKNOWN avoids spamming users twice.
  • Forward-only status merges vs. last-write-wins. Allowing state updates only to advance forward (for example, SENDING -> DELIVERED, never DELIVERED -> DISPATCHED) makes out-of-order webhooks safe without distributed locks, at the minor cost that if a vendor emits two conflicting terminal webhooks, the first terminal state recorded wins (while both raw callbacks remain in delivery_events).

Common mistakes

  • Read-then-send cancellation races: Reading state == 'QUEUED' in application memory and then calling the SMS/email API leaves a race window where a user's cancellation succeeds and the message still goes out. Always claim the row with an atomic UPDATE ... SET state = 'SENDING' WHERE state = 'QUEUED' immediately before the network call.
  • Reusing one idempotency key everywhere (or adding attempt counters): Passing the caller's request key across multiple channels collides if channels share a vendor, while appending _attempt_2 to the outbound provider key defeats deduplication on retries. Use (user_id, client_id, Idempotency-Key) inbound and the per-channel delivery_id outbound.
  • Blindly retrying or failing over on HTTP timeouts: A socket timeout does not prove the external provider rejected the message—it may already be on its way to the user's phone. Only fail over immediately on explicit pre-acceptance rejections (connection refused, 429, 5xx), and handle timeouts via idempotent resends or category-specific unknown-outcome rules.
  • Evaluating quiet hours with fixed UTC offsets: Storing -05:00 instead of an IANA zone like "America/Toronto" shifts quiet hours by an hour during daylight saving time transitions.
  • Checking unsubscribe consent only at ingestion time: If a promotional digest is scheduled 24 hours ahead and the user unsubscribes 2 hours later, only checking preferences at routing time violates compliance. Re-check consent right before the dispatcher claims the delivery.
  • Assuming push providers send DELIVERED webhooks: Standard Apple (APNs) and Google (FCM) send APIs confirm acceptance (DISPATCHED), not handset delivery; tracking push delivery requires client-side app receipts.
  • Processing webhooks synchronously against the database: Slow database writes inside the webhook HTTP handler cause external vendors to time out and retry aggressively, amplifying load during incidents. Verify the signature, enqueue to Kafka, and return 200 OK immediately.

Follow-up questions

  • How can the platform reliably abort pending email or mobile push deliveries the moment a recipient views the alert inside the web or desktop app? First, give cancellation a window to succeed: the category's escalation policy inserts in_app as QUEUED immediately while creating push (say due_at = +60 s) and email (due_at = +10 min) as SCHEDULED rows on the same user_id Postgres shard, and skips queuing push altogether if a Redis WebSocket presence flag shows the recipient is actively online. When the user views the alert (POST /v1/me/inbox/{id}:read), a single local shard transaction sets read_at on inbox_items and executes UPDATE deliveries SET state = 'CANCELLED' WHERE notification_id = :id AND state IN ('SCHEDULED', 'QUEUED', 'RETRY_WAIT'). Even if a dispatcher worker already pulled the email job from Kafka, its pre-send atomic claim (UPDATE ... WHERE state = 'QUEUED') matches zero rows and aborts cleanly; if push already reached DISPATCHED, we can optionally send a silent background push instructing the mobile client to clear the banner.
  • How would you design rate limiting so it enforces per-recipient message caps alongside hard external provider throughput ceilings such as 100 SMS per second? Split them into two separate Redis primitives because they answer different questions: recipient caps decide whether to send, while vendor quotas govern how fast we send. For per-recipient caps, store atomic window counters (cap:{user_id}:{channel}:{window}) evaluated via a small Lua script (an atomic server-side Redis script) right before the dispatcher claims a row; critical passcodes bypass caps, normal alerts defer to the next window, and low alerts become SUPPRESSED. For external provider ceilings (such as 100 SMS/s), maintain a Redis token bucket per vendor account refilled at 100 tokens/s with a tight burst ceiling (for example, 30 tokens so an idle bucket cannot fire 200 messages in one second), and let workers lease 5–10 tokens per call to keep Redis QPS low. Reserve the bottom 20 tokens strictly for critical lanes so passcode spikes always claim primary capacity, while standard and bulk lanes spill over to a backup SMS vendor (or enter RETRY_WAIT backoff) whenever fewer than 20 tokens remain.
  • What prevents state corruption when an external vendor's 'DELIVERED' callback reaches your webhook endpoint before the sending worker finishes persisting 'DISPATCHED'? Enforce forward-only state transitions and non-destructive timestamp fills in SQL so arrival order never corrupts the record. Attach our delivery_id to the outbound vendor request's custom metadata or callback URL so incoming webhooks locate the deliveries row directly without waiting for provider_message_id (for vendors that only return their own ID, hold unmatched callbacks in a short retry queue until the dispatcher saves the ID). When the DELIVERED webhook lands while the row is still SENDING, the status writer advances SENDING -> DELIVERED and records delivered_at because delivery confirmation proves handoff succeeded. Moments later, when the dispatcher saves its HTTP 200 result, its UPDATE uses COALESCE(dispatched_at, :ts) to backfill the missing handoff timestamp and a CASE WHEN state IN ('SENDING', 'UNKNOWN') THEN 'DISPATCHED' ELSE state END guard so DELIVERED is never downgraded; duplicate callbacks are deduplicated via provider_event_id.

Follow-up questions

Similar questions

More Replit interview questions

All 1 Replit questions →