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) toDISPATCHED(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
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 -> enfallback). - 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_attimestamps (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:
criticalalerts (login.passcode,session.invite) reach the external provider (ACCEPTED -> DISPATCHED) in < 1 second at p99;lowurgency digests/promotions can take minutes. - Urgency ownership: Callers pass a
category(such aslogin.passcodeorbuild.broken), not a raw priority. A platform-owned category registry maps each category to its urgency (critical,high,normal,low), message type (transactionalvs.promotional), and channel timing policy. That prevents a bulk digest job from labeling itselfcritical. - Critical override:
criticaltransactional 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.
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 GBTwo immediate takeaways from the math:
- 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.
- 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.
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 originalnotification_idinstead 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 callbacksWhy these API choices matter:
202 Acceptedmeans 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
POSTreturning per-channel outcomes, notDELETE: Cancellation is a race. Push may already beDISPATCHEDwhile email is stillSCHEDULED; returningcancelledandtoo_latelists tells the caller the exact truth. channelscan 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.
Data model and delivery state machine
We store operational state in PostgreSQL sharded by
user_idacross 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_idusing 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 everynotification_id(ntf_0812-...) anddelivery_id(dlv_0812-...) with its 4-digit bucket number. That gives us two big wins:- 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.
- Lookups by
notification_idordelivery_id(such as status queries and incoming provider webhooks) know which shard to hit immediately from the ID prefix, without needinguser_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, bodyWhy keep
idempotency_keysanddeliveriesunpartitioned? In Postgres, aUNIQUEindex on a partitioned table must include the partition column (created_at). Ifidempotency_keyswere 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 instantDROP TABLE.Per-channel delivery state machine
Once the API saves the parent notification as
ACCEPTED, the router creates onedeliveriesrow 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, EXPIREDHigh-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 ] -> PostgresWhy 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.criticalwith 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
ACCEPTEDnotifications (andQUEUEDdeliveries) older than their lane's current consumer lag plus 5 seconds and republishes them. DownstreamUNIQUE (notification_id, channel)constraints and atomic worker claims make duplicate Kafka messages completely harmless.End-to-end latency budget for a
< 1 scritical 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 p99Deep 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 deliveriesfollowed byif state == 'QUEUED': send_email(). Between theSELECTandsend_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
UPDATEmilliseconds 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_at90 minutes out, quiet-hour deferrals, or retry backoffs)? They all use the exact same mechanism: a row inSCHEDULEDorRETRY_WAITwithdue_at. Once per second per shard, scheduler workers runSELECT ... WHERE state IN ('SCHEDULED', 'RETRY_WAIT') AND due_at <= now() ORDER BY due_at LIMIT 500 FOR UPDATE SKIP LOCKED(SKIP LOCKEDlets multiple scheduler workers share the table without blocking each other), flipstateto'QUEUED', and publish to Kafka. Because timers live in the samedeliveriesrow, cancelling a 90-minute scheduled send is just the same single-rowUPDATEabove!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:
- Inbound key (
(user_id, client_id, Idempotency-Key)): ProtectsPOST /v1/notifications. When an internal caller retries after a gateway timeout,INSERT INTO idempotency_keys ... ON CONFLICT DO NOTHINGcatches the duplicate inside the user's shard transaction. If the request payload hash matches, we return the existingnotification_id; if the caller accidentally reused a key for a different payload, we return422. - Outbound key (
delivery_id): ProtectsDispatcher -> 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 appendattempt(dlv_123_attempt_2), because that would look like a brand-new message on retry! Passing the stabledelivery_idlets 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 (
SENDINGlease expires) and the vendor doesn't deduplicate? A background lease sweeper spotsstate = '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 bydelivery_idif supported; otherwise resend once. promotional(digest.weekly): Never blind-resend—spamming users twice erodes trust. MarkUNKNOWN(a late delivery webhook can still promote it toDELIVERED).
Handling out-of-order webhooks (
DELIVEREDarriving beforeDISPATCHED): A fast vendor can deliver an SMS and fire itsDELIVEREDwebhook in 80 ms, reaching our Status Writer before the Dispatcher finishes recording the HTTP200response (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 returns200 OKin a few milliseconds so vendors never time out. We passdelivery_idin the outbound request's custom metadata or callback URL so the webhook identifies our row directly without waiting forprovider_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-messageDELIVEREDwebhooks. Push stops atDISPATCHEDunless our mobile app SDK explicitly pings a receipt endpoint when a background notification wakes the app.)- Inbound key (
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 at08:00:00sharp in major time zones). Ifexpires_atis earlier thanwake_utc, the row is markedSUPPRESSED (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_704too much today?" (e.g., max 4 pushes/hour, 20 alerts/day)Atomic counter cap:{user_id}:{channel}:{hour}checked right beforeQUEUED -> SENDINGclaimcriticalbypasses;normaldefers to next window;lowbecomesSUPPRESSED (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_WAITif all vendors are saturatedWhy 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
Rtokens/second up to capacityB. After an idle second, a bucket can burstBstored tokens plusRnewly refilled tokens in one second—so settingB = 100could send 200 SMS in 1 second and trigger vendor429rejections! KeepingB = 30limits bursts, and requiringstandard/bulkworkers to leave at least 20 tokens untouched reserves instant headroom forcriticalpasscode 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.Scaling, failure modes, and trade-off summary
Failure scenario Impact Recovery mechanism API crashes after DB commit, before Kafka publish Row sits in ACCEPTEDLag-aware sweeper republishes after consumer_lag + 5 s;UNIQUE (notification_id, channel)prevents duplicatesDispatcher crashes after calling vendor Row stuck in SENDINGpast 10 s leaseLease sweeper resolves per category (resend passcode, lookup transactional, mark promo UNKNOWN)Postgres shard primary fails 1/16 of users see 503for ~20–30 sSynchronous cross-AZ replica promotes with zero data loss; callers safely retry with same Idempotency-KeyRedis 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...) inRETRY_WAITup toexpires_at—zero dropped alertsKey operational metrics to page on: -
ACCEPTED -> DISPATCHEDp99 latency oncriticallanes (page if> 1 sfor 5 minutes). -DISPATCHED -> DELIVEREDconversion rate per vendor (catches silent carrier filtering or broken sender reputation even when HTTP calls return200). - Count of expiredSENDINGleases,too_latecancellations, 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
UPDATEstate 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 scritical 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):
- t = 0 s (Ingest): The CI build service calls
POST /v1/notificationswithIdempotency-Key: "bld-618". The API storesntf_9(ACCEPTED) and key"bld-618"inusr_42's database shard, publishes tonotif.highin Kafka (a durable distributed message queue), and returns202 Acceptedin 20 ms. - t = 0.04 s (Route): A router worker reads
usr_42's cached preferences and creates two rows indeliveries:dlv_inbox(QUEUEDnow) anddlv_email(SCHEDULEDwithdue_at = +10 min).dlv_inboxwrites toinbox_itemsand pushes live over WebSocket (DELIVERED). - t = 3 min (Read & Cancel): User
usr_42clicks the in-app banner (POST /me/inbox/ntf_9:read). In a single local database transaction, we setread_aton the inbox row and runUPDATE deliveries SET state = 'CANCELLED' WHERE notification_id = 'ntf_9' AND state IN ('SCHEDULED', 'QUEUED', 'RETRY_WAIT'), cancellingdlv_email. - t = 10 min (Schedule check): When +10 minutes arrives, the scheduler only picks up rows still in
SCHEDULED, sodlv_emailis cleanly skipped andusr_42's email inbox stays clutter-free.
Key trade-offs
- Postgres sharded by
user_idvs. a managed NoSQL key-value store. Sharding Postgres (splitting rows across 16 independent databases by hashinguser_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 SQLUPDATEstatements. - 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.criticalvs.deliver.email.bulk) adds operational overhead (more topics and consumer groups to monitor) but guarantees< 1 slatency 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
criticalalerts 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
criticalpasscodes prioritizes reachability, whereas marking timed-outpromotionalsends asUNKNOWNavoids spamming users twice. - Forward-only status merges vs. last-write-wins. Allowing state updates only to advance forward (for example,
SENDING -> DELIVERED, neverDELIVERED -> 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 indelivery_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 atomicUPDATE ... 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_2to the outbound provider key defeats deduplication on retries. Use(user_id, client_id, Idempotency-Key)inbound and the per-channeldelivery_idoutbound. - 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:00instead 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
DELIVEREDwebhooks: 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 OKimmediately.
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_appasQUEUEDimmediately while creatingpush(saydue_at = +60 s) andemail(due_at = +10 min) asSCHEDULEDrows on the sameuser_idPostgres 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 setsread_atoninbox_itemsand executesUPDATE 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 reachedDISPATCHED, 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;criticalpasscodes bypass caps,normalalerts defer to the next window, andlowalerts becomeSUPPRESSED. 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 forcriticallanes so passcode spikes always claim primary capacity, whilestandardandbulklanes spill over to a backup SMS vendor (or enterRETRY_WAITbackoff) 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_idto the outbound vendor request's custom metadata or callback URL so incoming webhooks locate thedeliveriesrow directly without waiting forprovider_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 theDELIVEREDwebhook lands while the row is stillSENDING, the status writer advancesSENDING -> DELIVEREDand recordsdelivered_atbecause delivery confirmation proves handoff succeeded. Moments later, when the dispatcher saves its HTTP200result, itsUPDATEusesCOALESCE(dispatched_at, :ts)to backfill the missing handoff timestamp and aCASE WHEN state IN ('SENDING', 'UNKNOWN') THEN 'DISPATCHED' ELSE state ENDguard soDELIVEREDis never downgraded; duplicate callbacks are deduplicated viaprovider_event_id.
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?
- 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?
- What prevents state corruption when an external vendor's 'DELIVERED' callback reaches your webhook endpoint before the sending worker finishes persisting 'DISPATCHED'?
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System