Skip to content

Design a Notification System

Intermediate 35 min read Part 17 of 18

Design a notification platform: push, SMS, email and in-app, queue-based campaign fan-out, preferences, priorities, retries, dedupe and delivery tracking.

The Problem#

A notification system is an internal platform that other teams use to reach users. The auth service sends one-time passcodes by SMS. The payments team sends receipts by email. The social feed sends "Ann commented on your photo" as a mobile push. The marketing team sends a promotion to 20 million people at 9 a.m. None of these teams wants to integrate with Apple, Google, an SMS aggregator and an email provider, or to remember who has opted out of what. They want to hand the platform a message and a recipient, and have it delivered on the right channel, at the right time, exactly once, and never to someone who said "stop".

That makes this a platform problem. The customers are engineering teams, and the product is reliability, speed and correctness at scale. The hard parts are not "call the Apple push API". They are:

  • Surges. Daily volume may average a few thousand messages a second, but a single scheduled campaign can need 50 times that for ten minutes, while password-reset codes must still arrive within seconds.
  • Never losing or duplicating. Once the platform says "accepted", the notification must be delivered or deliberately dropped by policy, never silently lost. But retries over unreliable providers create duplicates, and duplicate SMS codes or double "your order shipped" emails are visible failures.
  • Respecting the user. Channel opt-outs, quiet hours, frequency caps and legal consent rules must be checked for every single message.
  • Unreliable third parties. Every final hop is someone else's system: Apple Push Notification service (APNs), Firebase Cloud Messaging (FCM), SMS carriers, email inbox providers. Each has its own limits, failures and feedback.

Analogy. Think of the post room of a huge company. Departments drop off letters. The post room checks each recipient's forwarding instructions ("no mail on weekends", "email instead of paper"), stamps them, sorts them into urgent and bulk bins, and hands them to couriers: a motorbike for urgent items, the postal service for bulk. It keeps a ledger of what left and what came back undeliverable. If a department drops off 20 million flyers, the post room must still get the urgent legal letter out first. That is the whole design, at internet scale.

The building blocks are covered in Asynchronous Processing and Message Queues, Idempotency and Safe Retries and Delivery Guarantees: At-Most, At-Least and Exactly-Once. This page assembles them into one design and explains each decision.

Clarifying Questions#

QuestionAssumed answerWhy it matters
Who calls the platform?Internal services (auth, payments, social, marketing tools) through an authenticated API. End users only set preferences and read the in-app inbox.It is a platform API with per-client quotas and identities. Clients are trusted but must be isolated from each other.
Which channels?Mobile push (APNs, FCM), web push, SMS, email and an in-app inbox.Each channel has different providers, limits, payload sizes, costs and feedback loops.
Immediate, scheduled, or both?Both. Send now, send at a time, or send at a local time such as "9 a.m. in each user's time zone".Scheduling needs a durable timer system. Local-time sends spread one campaign across 24+ hours.
Single messages or campaigns?Both. Single, targeted notifications ("your OTP is 4821"), and campaigns to segments of up to 50M users.Campaigns need segment resolution and fan-out, and must never starve single urgent messages.
What volume?About 500M deliveries a day on average (about 6k per second), with surges to 100k per second during campaigns and breaking events.The peak-to-average ratio of 15-50 times drives queueing, autoscaling and provider capacity.
What latency?High priority (OTP, security alerts): delivered to the provider within 5 s at p99, even during a campaign. Normal priority: within a minute. Bulk: within the campaign's window.Priorities need separate queues and reserved capacity, not just a priority field.
What delivery guarantee?Every accepted notification is attempted until it succeeds, a policy drops it, or it expires. Duplicates should be very rare, with no duplicate OTPs.At-least-once inside the platform plus deduplication: effectively once to the user.
What preferences?Per-category, per-channel opt-in and opt-out, quiet hours in the user's time zone, frequency caps, and legal consent such as SMS consent and email unsubscribe.Preference checks are on the hot path for every message, so they must be fast and cached.
Do templates belong to the platform?Yes, as a template store with versioning, localisation and per-channel variants. Rich visual authoring is out of scope.Rendering happens per recipient at send time, which is CPU at 100k per second.
Do we track delivery?Yes: per-message status (accepted, sent, delivered, failed, opened or clicked where available), queryable by the client team. Full analytics dashboards are out of scope.Tracking needs a high-write status store and provider callbacks (webhooks).
Multi-region?Active in two regions for availability. Users are served from their home region.Duplicates during failover must be avoided, so dedupe state must be region-aware.

Requirements#

Functional#

  1. Send. A client service sends a notification to one user (or a small list) on one or more channels, immediately or at a scheduled time, with an idempotency key.
  2. Campaigns. A client creates a campaign: a template plus a segment of users. It runs immediately, at a fixed time, or at a local time per user, with throttling and cancellation.
  3. Preferences. Users opt in or out per category and channel, set quiet hours and a time zone, and unsubscribe from email or SMS through standard mechanisms (unsubscribe link, STOP reply).
  4. Templates. Clients reference versioned, localised templates with variables, and per-channel variants (push title and body, SMS text, email subject and HTML).
  5. Delivery tracking. Clients query the status of a notification and receive status events. Users' devices report opens, and providers report bounces and invalid tokens.
  6. In-app inbox. Notifications can also be stored in a per-user inbox with unread counts, synced across devices.

Non-Functional#

  1. Durability. Once the API returns 202 Accepted, the notification is never lost by the platform: no single machine, zone or queue failure can drop it.
  2. Latency by priority. High priority reaches the provider in under 5 s at p99, even while a 50M campaign is running. Normal priority within 60 s, and bulk within the campaign window.
  3. Throughput. Sustain 100k deliveries per second at peak, with horizontal scaling to more.
  4. Effectively once. At-least-once processing, with deduplication so users see duplicates at a rate below about 1 in 10^5, and never for OTPs.
  5. Correctness of policy. No message is ever sent against an opt-out, consent rule or quiet-hour rule, even when caches are stale.
  6. Isolation. One client's campaign or bug cannot exhaust capacity for others. There are quotas per client and per category.
  7. Availability. 99.95% or better for the ingest API, and graceful degradation when a provider is down: queue, fail over, or expire.
  8. Observability. Every notification is traceable end to end, from the API call through each delivery attempt to the provider's response.

Capacity Estimation#

Why the average is misleading. A small version of this system sends 10M notifications a day. Spread evenly, that is about 115 per second, which is almost nothing. But clients do not send evenly. A campaign scheduled for 9 a.m. is expected to arrive at 9 a.m., not trickle out over the day. Delivering 1M messages within 5 minutes needs 3,300 per second, from one campaign. So even a small platform must be designed for surges of about 50 times the sustained rate. That ratio, not the daily total, shapes the architecture. Our larger platform has the same shape.

Volume. We plan for 500M deliveries a day. With a day ≈ 10^5 seconds, that is about 6k per second on average. The mix by channel:

  • 70% push, about 4k per second,
  • 15% in-app only,
  • 10% email, about 600 per second,
  • 5% SMS, about 300 per second, and the most expensive by far.

Peaks. Three things stack:

  1. A 50M-recipient campaign delivered over 10 minutes is 50M ÷ 600 s ≈ 83k per second.
  2. Normal transactional traffic at its daily peak of 2-3 times average is 12-18k per second.
  3. A breaking event (a security incident or a sports alert) adds a burst.

We plan for 100k deliveries per second of platform capacity. Not every downstream channel needs that. Email and SMS providers will throttle us far below it, and the design must queue against those limits.

Ingest vs delivery. A campaign is one API call that expands into 50M deliveries inside the platform. Ingest QPS is therefore low, about 2-5k API calls per second for single notifications, while the internal fan-out rate is high. The expensive parts are the per-recipient steps: preference lookup, template rendering, dedupe check, provider call and status write.

Per-delivery work at 100k per second:

  • Preference and device-token lookups. About 2 key-value reads per delivery, so 200k reads per second. That is easily served from a cache (Redis at about 100k ops per second per shard, so a few shards) with a durable store behind it.
  • Dedupe check. One SET if not exists with a TTL per delivery: 100k Redis ops per second, about 2-4 shards with headroom.
  • Rendering. About 50-200 µs of CPU per message for a compiled template. 100k per second × 100 µs = 10 CPU-seconds per second, about 10-20 cores.
  • Provider calls. Provider latency is 50-300 ms. By Little's Law, in-flight requests = rate × latency = 100k × 0.15 s ≈ 15k concurrent requests. With asynchronous HTTP/2 clients each holding about 1-2k concurrent streams, that is about 10-20 sender processes, plus headroom and per-provider pools.
  • Status writes. Each delivery writes about 2-3 status events (sent, then delivered or failed, and sometimes opened), so 200-300k small writes per second at peak. That calls for a write-optimised store such as Cassandra or DynamoDB, or an append-only log with batched writes.

Queue throughput. 100k messages per second at about 1 KB each is about 100 MB/s into the queue, roughly 300 MB/s with 3 times replication. A Kafka cluster with a dozen brokers handles this comfortably. It needs enough partitions for parallelism: for example 256 partitions on the bulk topic, so 256 consumers can work in parallel.

Storage.

  • Notification records. About 1 KB each (metadata, rendered payload reference, variables). 500M a day × 1 KB = 500 GB a day.
  • Status events. About 150 B each × 1.5B a day ≈ 225 GB a day.
  • Retention. Keeping 30 days hot is about 22 TB before replication. Older data goes to compressed columnar files in object storage for analytics, at about a tenth of the size.
  • Device tokens. 200M users × 2 devices × about 200 B ≈ 80 GB.
  • Preferences. About 200M rows × 500 B ≈ 100 GB, small enough to cache the hot part.
  • In-app inbox. 90 days for 15% of traffic, about 75M items a day × 500 B ≈ 3.4 TB.

Cost reality check. At an assumed $0.005-0.05 per SMS depending on country, 25M SMS a day is about $125k-1.25M a day. Push and in-app are nearly free. Email costs fractions of a cent per message. SMS cost alone justifies channel-routing logic: send a push first, and fall back to SMS only for critical messages that were not acknowledged.

Core Entities#

  • Client. An internal service or team with credentials, quotas, allowed categories and a sender identity (email domain, SMS sender id).
  • Notification. One logical message to one user: id, client, user, category, priority, template and version, variables, requested channels, schedule, idempotency key, expiry time (TTL) and status.
  • Delivery. One attempt to deliver a notification on one channel to one endpoint (a device token, a phone number or an email address), with provider, attempt number, provider message id and status.
  • Campaign. A template plus a segment, a schedule (now, at a time, or at a local time), throttle settings and progress counters.
  • Segment. A definition of a set of users (a query or an uploaded list) and the snapshot of user ids it resolved to when the campaign started.
  • Template. A versioned, localised message definition with per-channel variants and declared variables.
  • User preferences. Per category and channel opt-in or opt-out, quiet hours, time zone, locale, frequency caps and consent records.
  • Device. A registered push endpoint: platform (iOS, Android or web), token, app version, last seen and validity.
  • Inbox item. An in-app notification stored for a user, with read state.

API Design#

Clients call a REST or gRPC API with service credentials. All mutating calls take an idempotency key.

POST /v1/notifications
  Idempotency-Key: <client-generated key>
  {
    "user_id": "u_123",
    "category": "security_alert",          // maps to default priority + policy
    "priority": "high",                    // high | normal | bulk
    "channels": ["push", "sms"],           // or "auto" = preference-driven routing
    "template": {"id": "login_alert", "version": 7},
    "variables": {"city": "Hyderabad", "device": "Chrome on Mac"},
    "send_at": null,                       // or ISO time, or {"local_time":"09:00"}
    "expires_at": "2026-12-03T10:15:00Z",  // do not deliver after this
    "dedupe_key": "login:u_123:sess_9f2"   // optional business-level dedupe
  }
  -> 202 Accepted { "notification_id": "n_8f3...", "status": "accepted" }
 
POST /v1/campaigns           { template, segment_id, schedule, throttle_per_sec, categories }
  -> 202 { "campaign_id": "c_42", "status": "scheduled" }
POST /v1/campaigns/{id}:cancel
GET  /v1/notifications/{id}  -> { status, deliveries: [{channel, status, provider_id, at}] }
Webhook to client (optional): notification.status_changed events
 
User-facing (via the app backend):
GET/PUT /v1/users/{id}/preferences   { categories: {...}, quiet_hours, timezone }
POST    /v1/users/{id}/devices       { platform, token, app_version }
GET     /v1/users/{id}/inbox?cursor=  -> items, unread_count
POST    /v1/users/{id}/inbox:mark-read { item_ids }

Design notes:

  • Why 202 Accepted and not 200. Delivery is asynchronous. The response means "durably accepted", a promise that the platform must keep (Deep Dive 1). Clients can poll or subscribe to status changes.
  • Two different keys. The Idempotency-Key makes the API call safe to retry: the same key returns the same notification_id. The dedupe_key expresses business uniqueness, such as "one login alert per session", even across different calls (Deep Dive 3).
  • category drives policy. Users opt out of categories ("marketing", "social", "security"), not of individual templates. Each category has a default priority, allowed channels and frequency caps, so clients cannot accidentally send marketing at high priority.
  • expires_at matters for time-sensitive content. An OTP valid for 10 minutes is worthless after 10 minutes. Delivering it late is worse than not delivering it, because it confuses users and costs money.

High-Level Design#

We build the design one requirement at a time, starting with a single notification and adding components only when a requirement needs them.

1) A service can send a notification to a user, immediately or at a scheduled time#

The naive version. The API server receives the request, looks up the user's device token, calls APNs, and returns. That couples the client's latency to Apple's latency, and loses the message if the server crashes mid-call. It also offers no protection when a client suddenly sends 50,000 requests per second. Every serious notification system therefore separates accepting from delivering with a durable queue.

Accept durably, deliver asynchronously. The Notification API:

  1. Authenticates the client service (mTLS or a signed service token) and checks its quota and allowed categories.
  2. Validates the request: the template exists, the variables are present, the category is allowed, and the priority is allowed for the category.
  3. Checks the idempotency key. If the key was seen before, it returns the original notification_id without doing anything else.
  4. Persists and enqueues. It writes the notification record and publishes a message to the queue for its priority. Only when the queue write is acknowledged does it return 202 Accepted. Deep Dive 1 explains how to make this pair of writes atomic.

Workers do the rest. A pool of notification workers consumes the queue. For each message it:

  1. Loads the user's preferences and devices (from cache).
  2. Decides which channels to use, or drops the message by policy (opted out, quiet hours, expired, frequency cap).
  3. Renders the template for each channel and locale.
  4. Hands one delivery per endpoint to the channel queue for that channel.

Channel senders consume the channel queues, call the provider, and record the result. The queues let each stage scale independently. Rendering is CPU-bound, while sending is I/O-bound and limited by the provider. Per-channel queues also let one slow provider back up without blocking others.

Scheduled sends. A notification with send_at in the future is stored with its due time instead of being enqueued. A scheduler service turns due notifications into queue messages. The simple, robust design stores notifications in a table indexed by (due_minute, shard). Each scheduler instance owns some shards and, every few seconds, claims rows due now (SELECT ... WHERE due_at <= now() AND status = 'scheduled' ... FOR UPDATE SKIP LOCKED), enqueues them, and marks them enqueued. Deep Dive 4 covers scheduling at scale, time zones and quiet hours.

2) A service can send a campaign to a segment of users#

A campaign is one request that becomes millions of deliveries. Doing the expansion inside the API call would time out and overload everything downstream at once. Instead:

  1. Create the campaign with a template, a segment and a schedule. The API returns immediately with campaign_id.
  2. Resolve the segment to a snapshot. At start time, a campaign service resolves the segment ("users in India who installed in the last 30 days and opted into promotions") into a fixed list of user ids, written as ordered chunks of about 10k ids to object storage or a table. The snapshot makes the campaign reproducible and resumable: if a worker dies, the same chunk is processed again, not a re-run of a query whose results have changed.
  3. Fan out in chunks. A fan-out worker reads chunks and publishes one message per user to the bulk queue, paced by the campaign's throttle (for example 50k per second). Progress is checkpointed per chunk.
  4. The normal pipeline continues with preferences, rendering and sending, exactly as for single notifications, but in the bulk priority lane.

Pacing matters for three reasons. Providers have rate limits. Our own servers (and the app's servers, when 50M users tap the notification and open the app at once) need to survive the response. And campaigns compete with high-priority traffic, which Deep Dive 2 isolates. Deep Dive 5 covers fan-out mechanics, local-time campaigns and cancellation.

3) Users can set notification preferences#

Preferences are rules evaluated for every delivery:

  • Category opt-outs per channel: "no marketing emails", "social pushes only".
  • Quiet hours in the user's time zone: "nothing between 22:00 and 07:00 except security alerts".
  • Frequency caps: "no more than 3 promotional pushes a day".
  • Legal consent: an SMS opt-in record, email unsubscribes, and region-specific rules.

A preference service owns this data in a relational database (Postgres), keyed by user, with the hot set cached in Redis or in-process. Workers check preferences at send time, not at accept time. A user who opts out at 8:59 must not receive a campaign at 9:00 that was accepted at 8:00. Unsubscribes arriving through channels (an email unsubscribe link, an SMS "STOP" reply) are written into the same service. Deep Dive 6 covers the data model, caching and the "never violate an opt-out" guarantee.

4) Messages are delivered through each channel's provider#

Each channel has its own delivery path, and the senders encapsulate it:

  • Mobile push. The app registers with APNs (iOS) or FCM (Android) and gets a device token, which the app sends to our device registry. To notify, our push sender calls APNs over HTTP/2 or FCM's HTTP v1 API with the token and a small JSON payload (up to 4 KB for both). The provider keeps a persistent connection to each device and delivers when the device is reachable. We cannot reach the phone directly.
  • Web push. Browsers provide a push subscription (an endpoint URL plus keys). We send encrypted payloads to the browser vendor's push service using the Web Push protocol (RFC 8030), with VAPID keys identifying our server (RFC 8292).
  • SMS. We send through SMS aggregators such as Twilio, Vonage or Sinch, which connect to carriers. Throughput depends on the sender type: long codes are slow, short codes and approved toll-free or registered numbers are faster. Delivery receipts arrive later through webhooks.
  • Email. We hand messages to an email service provider (Amazon SES, SendGrid, Mailgun) or our own SMTP relays. Deliverability depends on SPF, DKIM and DMARC records, a good sender reputation, and handling bounces and complaints.
  • In-app. We write an inbox item to the user's inbox store, and if the user is online, push it in real time over the app's WebSocket or server-sent events connection.

Deep Dive 9 covers provider internals, failover between providers, and the feedback each one sends back.

5) Clients can track delivery status#

Every delivery passes through states: queued → sent → delivered (or failed, dropped_by_policy, expired), with opened or clicked where the channel reports it. Status comes from three sources:

  • Our senders record sent with the provider's message id when the provider accepts the request.
  • Provider callbacks (webhooks for SMS delivery receipts, email bounce and complaint notifications) record delivered, bounced or failed. APNs and FCM give only "accepted" at send time, plus errors such as an unregistered token.
  • Client apps report opened when the user taps the notification. This is the only reliable delivery signal for push.

All events go onto a status topic, are written to a delivery log (Cassandra or DynamoDB, partitioned by notification id) for lookups, and are streamed to analytics. Deep Dive 10 covers the tracking pipeline.

The full high-level design#

The send path, from client service to provider:

The supporting services that the workers and senders read from and write to:

Each component in one line:

  • Notification API. It authenticates clients, enforces quotas, validates templates and categories, deduplicates API retries by idempotency key, and durably accepts.
  • Notification store and outbox. Notification records plus an outbox table written in the same transaction. A relay publishes outbox rows to the queues, so "accepted" and "enqueued" can never disagree.
  • Priority queues. Separate Kafka topics (or SQS queues) for high, normal and bulk, each with its own consumer pool and capacity, so a campaign can never delay an OTP.
  • Scheduler. It holds future sends in a time-indexed table and enqueues them when due, with shard ownership and idempotent claiming.
  • Campaign service. It snapshots segments into chunks and fans them out at a throttled rate, with checkpointing, pausing and cancellation.
  • Notification workers. Stateless consumers that apply preferences, quiet hours, frequency caps and expiry, choose channels, render templates, deduplicate, and emit per-channel deliveries.
  • Channel queues and senders. One queue per channel (and sometimes per provider). Senders hold pooled HTTP/2 or SMTP connections, respect provider limits, retry with backoff, and fail over between providers.
  • Preference service. The source of truth for opt-outs, consent, quiet hours, time zones and caps, cached for the hot path. It is updated by users and by channel feedback (unsubscribe, STOP).
  • Device registry. Push tokens per user and device, updated on app start and pruned on provider "unregistered" errors.
  • Template service. Versioned templates with locales and channel variants, compiled and cached in workers.
  • Dedupe and cap store. Redis keys with TTLs for "already sent" markers and per-user counters.
  • Feedback processor. It ingests provider webhooks and device open events, updates status, disables bad tokens and addresses, and records unsubscribes.
  • Delivery log and analytics. A queryable status per notification for clients, and a long-term event stream for reporting.

Key Flows#

A high-priority push notification, end to end#

  1. The API's only synchronous work is cheap: authenticate, check quota, validate, check the idempotency key, and make the record durable. That is about 10-30 ms, dominated by the database commit and the queue acknowledgement.
  2. The message lands on the high topic, which has its own consumers, so it does not wait behind a running campaign. Typical queue latency is milliseconds.
  3. The worker checks preferences at send time. Security alerts usually bypass quiet hours by category policy, but still respect a hard opt-out where the law requires it.
  4. The dedupe marker is written before the provider call, keyed by notification, channel and endpoint. A redelivered queue message after a worker crash then skips the send. Deep Dive 3 covers the narrow window this leaves.
  5. APNs answers 200 when it has accepted the notification, not when the phone shows it. If the token is invalid, APNs returns an error such as 410 Unregistered, and the sender disables that device in the registry. End-to-end latency to the provider is about 100-300 ms at p50, well within the 5 s target.

A campaign to 20 million users#

  1. The segment is resolved once, at start time, into an immutable snapshot. 20M ids × 8 bytes is about 160 MB. It is cheap to store, and it makes retries, audits and "who received this?" questions exact.
  2. Fan-out is paced. At a 50k per second throttle, 20M messages take about 7 minutes to enqueue. For a "9 a.m. local" campaign, the fan-out instead releases each time zone's users when their local 9 a.m. arrives (Deep Dive 5).
  3. Checkpointing per chunk means a crash replays at most one chunk, about 10k messages. Duplicates from that replay are absorbed by the per-recipient dedupe key campaign_id + user_id.
  4. Cancellation has two parts. Stop publishing new chunks, and make workers check a cached "cancelled campaigns" set before sending, so messages already in the queue are dropped. Messages already handed to providers cannot be recalled. That is a property of the channels, so say it explicitly.

Data Model#

Which database for what. See Choosing a Database: A Decision Guide.

  • Notifications and outbox (accept path). Postgres, sharded by notification_id, or DynamoDB. The accept path needs a transaction covering the record, the outbox row and the idempotency-key row. That is a small, single-partition transaction, which both support. Records older than about 30 days move to object storage.
  • Delivery log. Cassandra or DynamoDB, partition key notification_id, clustering by delivery_id and time. This is a very high write rate (200-300k events per second at peak) with simple lookups ("status of n_81"), the textbook workload for a wide-column store. A second table keyed by (client_id, day) supports listing per client.
  • Preferences, templates, campaigns, clients. Postgres. These are small, relational, transactional and read-heavy, so they are cached aggressively.
  • Device registry. DynamoDB or Cassandra keyed by user_id, with a secondary lookup by token for feedback processing.
  • Inbox. Cassandra or DynamoDB with partition key user_id and clustering key created_at DESC, so "latest 50 items" is one partition read. Unread counts are kept as a separate counter (Deep Dive 11).
  • Dedupe markers, frequency counters, cancelled-campaign set. Redis with TTLs.

Indexes.

  • notification(idempotency_key, client_id), unique, so API retries resolve to one record.
  • notification(status, due_at), partial index for scheduled rows, for the scheduler.
  • device(push_token) for invalidation callbacks.

Retention. Delivery log 30-90 days hot, then archived. Idempotency keys 24-72 hours. Dedupe markers last as long as the dedupe window of each category (minutes for OTPs, a day for campaigns).

Deep Dives#

1) How do we guarantee that an accepted notification is never dropped?#

The promise is: once we return 202, the notification is delivered, or deliberately dropped by policy (opt-out, expiry, cancellation), or recorded as permanently failed. It is never silently lost. Messages get lost in three places: between the database and the queue, inside the queue, and inside workers.

Basic: write to the database, then publish to the queue, then return. If the process crashes after the database commit but before publishing, the notification sits in the database forever, accepted but never enqueued. If we publish first and the commit then fails, a worker may deliver a notification the API reported as failed, and the client retries and causes a duplicate. This dual-write problem has no fix by reordering. Two separate systems cannot be updated atomically by the application.

Better: the transactional outbox. In the same database transaction as the notification record, insert a row into an outbox table. A separate relay reads new outbox rows, by polling or by tailing the database's change log with change data capture (for example Debezium on the Postgres WAL), publishes them to the queue, and marks them published. The API returns 202 after the transaction commits.

  • If the API crashes after the commit, the relay still publishes.
  • If the relay crashes after publishing but before marking, it publishes again on restart. That is a duplicate, which downstream dedupe absorbs.

So "accepted" and "will be enqueued" are now the same fact. The relay adds about 10-100 ms of latency, which is acceptable even for OTPs. See Change Data Capture and the Outbox Pattern.

An alternative that many systems use is queue-first. Treat the replicated log (Kafka, with acks=all and min.insync.replicas=2 across three zones) as the system of record for acceptance. Return 202 once the produce is acknowledged, and let a consumer write the notification record. This is simpler and faster, but the idempotency check then needs its own store, because it cannot be in the same transaction as the publish. Either design is correct if it is stated clearly.

Inside the queue: replicate and keep messages until processed.

  • Kafka. Use a replication factor of 3 across zones, acks=all, and no unclean leader election. Consumers commit offsets only after the message is fully handled, meaning it was handed to the channel queue or dropped by policy with a status record. A crash before the commit means redelivery. That is at-least-once.
  • SQS-style queues. A message stays invisible during processing (the visibility timeout) and reappears if it is not deleted. After N failed receives, it moves to a dead-letter queue (DLQ).

Inside workers: never acknowledge before the next stage is durable. A worker handles a message, publishes deliveries to channel queues (acknowledged), writes status, then commits the offset. Every stage follows the same rule, so a crash anywhere causes reprocessing, never loss. See Delivery Guarantees: At-Most, At-Least and Exactly-Once.

Best: also prove it with reconciliation, and handle poison and expiry explicitly.

  • Poison messages. A message that crashes the worker every time, for example because of a template bug, would block a partition forever with Kafka's in-order processing. After 3-5 attempts, park it on a retry topic with delay, then a DLQ with an alert, and continue. Every DLQ entry is visible to the owning client team and can be replayed after the fix.
  • Expiry. Each message carries expires_at. A worker that sees an expired message records expired and drops it. This is a deliberate outcome, not a loss.
  • Reconciliation. A periodic job compares "accepted in the last hour" in the notification store with "has a terminal or in-progress status" in the delivery log. Anything accepted more than X minutes ago with no status is re-enqueued and counted. In a correct system that counter is zero. When it is not, it is the earliest warning of a bug.
  • Multi-zone everything. Queue brokers, databases and workers run across three zones, so a zone loss loses nothing that was acknowledged.

2) How do high-priority notifications arrive within 5 seconds during a campaign blast?#

Suppose a campaign has just put 20M messages in front of an OTP. With a single FIFO queue, the OTP waits behind them. At 50k per second, that is a 400-second wait. "Priority" has to mean separate capacity, not just a field in the message.

Basic: a priority field, sorted inside one queue. Most distributed queues (Kafka, SQS) do not support priority ordering. Even where a broker does, for example RabbitMQ priority queues, the high-priority message still competes for the same workers, the same rendering CPU and the same provider connections. A campaign that saturates the provider rate limit still delays the OTP at the sender.

Better: separate queues and separate worker pools per priority. Use three topics, high, normal and bulk, each with its own consumer group and its own autoscaled worker pool. Campaigns can only publish to bulk. The API maps categories to their allowed priorities, so marketing cannot use high. Now the OTP's queue is almost always empty, and its workers are idle and waiting. Queue latency is milliseconds. This is the single most important design choice for this requirement.

Best: isolate every shared stage, including the provider, and add admission control. Separate queues only move the contention downstream. Everything the high lane shares with bulk must be partitioned too:

  • Channel senders. Use separate send pools, or a weighted scheduler inside the sender (for example strict priority, or weighted fair queueing with 70% high, 20% normal, 10% bulk when all are busy) per provider.
  • Provider quotas. SMS and email providers enforce account-level rate limits. Reserve a slice for high priority: if our SMS provider allows 1,000 per second, bulk is capped at 700 per second, so 300 per second is always available for OTPs. Better still, use a separate sender identity or account for transactional traffic, such as a dedicated short code or a dedicated email IP pool. A promotion's spam complaints then cannot damage the reputation that OTP delivery depends on.
  • Rendering and dependencies. Size the preference cache and template cache so the high lane never waits on a cold dependency. Use separate connection pools to the preference database.
  • Admission control for bulk. The campaign service watches lag on the normal and high lanes and provider latency. If they rise, it slows its fan-out throttle automatically. This is backpressure. Campaigns trade a few minutes of delay for guaranteed latency in the critical lanes.
  • Measure what you promise. Track a p99 SLO for "time from accept to provider-accepted" per priority, and alert on it. Run a synthetic OTP canary every few seconds during every campaign.

The general principle is the bulkhead: compartments that fail or fill independently. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.

3) How do we prevent duplicate notifications on top of at-least-once delivery?#

At-least-once processing means every stage may process a message twice. Duplicate sources include:

  • client retries of the API call,
  • outbox relay re-publishing,
  • worker crashes before the offset commit,
  • campaign chunk replays,
  • sender retries after a provider timeout,
  • failover between regions.

Some duplicates are merely annoying, like two "your order shipped" pushes. Others are harmful, like two different OTP codes, where the first one no longer works, or a double charge-related SMS.

Basic: rely on the API idempotency key alone. The key makes retries of the same API call return the same notification_id. Store (client_id, idempotency_key) → notification_id with a unique constraint in the same transaction as the record, and keep it for 24-72 hours. This is necessary, but it does nothing about duplicates created inside the platform.

Better: a dedupe marker per delivery, checked right before sending. Before calling the provider, the sender (or the worker) does SET dedupe:{notification_id}:{channel}:{endpoint} 1 NX EX <window> in Redis. If the key already exists, the delivery was already attempted, so skip it. The marker is set before the call, which gives at-most-once per marker at the send step. A crash between setting the marker and the provider call loses that send. So we store the marker with a state, in_progress then sent. If a retry finds in_progress older than about 30 seconds, it consults the delivery log or the provider's message id to decide whether to resend. For most categories, a rare lost send is preferable to a duplicate. For critical ones, prefer the resend.

Add business-level dedupe with dedupe_key. "Only one login alert per session" or "only one price-drop alert per item per day" is enforced by a marker on dedupe:{client}:{dedupe_key} with the category's window. This catches upstream services that emit the same event twice with different idempotency keys, which is very common with event-driven producers.

Best: layered dedupe with clear windows, plus channel-level protections and honest limits.

LayerKeyWindowCatches
APIclient id + idempotency key24-72 hClient retries
Businessclient id + dedupe keyPer category: minutes to daysUpstream double-emits, repeated events
Campaigncampaign id + user idCampaign duration + 1 dayChunk replays, re-runs
Deliverynotification id + channel + endpoint1-24 hWorker and sender redelivery
ProviderProvider-side ids, such as apns-id or email Message-IDProvider dependentSome provider-side retries

Channel features help:

  • APNs accepts an apns-collapse-id, so a newer notification with the same id replaces an older one on the device instead of stacking. Use it for "you have 3 new messages"-style notifications, so a duplicate collapses visually.
  • FCM has a similar collapse_key.
  • Email carries a stable Message-ID header, which helps threading and debugging.
  • For OTPs, the best protection is in the auth service's design. Make codes valid for their whole TTL, and resend the same code on retries instead of generating a new one, so a duplicate is harmless.

Honest limit. Exactly-once delivery to a human over an external provider is impossible. If the provider times out, we cannot know whether it delivered. Retrying risks a duplicate, and not retrying risks a loss. We choose per category: retry for security alerts and OTPs within their TTL, and do not retry ambiguous timeouts for promotions. See Idempotency and Safe Retries.

Sizing the dedupe store. About 100k markers per second at peak, with a 24-hour window, would be up to 8.6B keys at peak rate. That is too many. In practice the average rate is 6k per second, about 520M keys a day, at about 80 bytes each ≈ 40 GB of Redis. That is feasible, but windows should be chosen per layer. Short windows for the delivery layer (1 hour ≈ 22M keys ≈ 2 GB) and longer ones only for business keys keep it small. A Bloom-filter front end can reduce memory further for "definitely not seen" checks.

4) How do scheduled sends, time zones and quiet hours work at scale?#

Basic: a cron job scans for due notifications every minute. SELECT * FROM notifications WHERE send_at <= now() AND status = 'scheduled'. This works for thousands of rows. At millions of scheduled rows, especially when a campaign schedules 20M sends for the same minute, a single scanner falls behind. Two scanners also double-send without careful locking.

Better: a sharded, time-bucketed scheduler with idempotent claims. Store scheduled items keyed by (due_bucket, shard), where due_bucket is the due minute and shard is a hash of the notification id into, say, 256 shards. Scheduler instances own shards through leases from a coordination service, or rebalance like a consumer group. Each instance:

  1. Every second, reads its shards' rows for buckets up to now.
  2. Claims them with UPDATE ... SET status='enqueued' WHERE id IN (...) AND status='scheduled', or SKIP LOCKED in Postgres.
  3. Publishes them to the priority queue through the outbox.

A claim and a publish in one transaction keep it exactly-once at this step, and the downstream dedupe covers any replay. The same design sits at the core of most job schedulers. See Pattern: Managing Long-Running Tasks. Alternatives include delay queues (SQS delay seconds, up to 15 minutes), Redis sorted sets scored by due time (ZRANGEBYSCORE then a claim), or a workflow engine timer for complex multi-step sequences (see Temporal and Workflow Engines).

Do not schedule campaigns per recipient. For a campaign, the campaign service schedules the start, and fan-out happens at start time. Writing 20M rows into the scheduler first doubles the work.

Best: make time zones, quiet hours and send-time choices first-class.

  • Local-time campaigns. "9 a.m. local" is 24 or more schedule points, one per UTC offset, plus half-hour and 45-minute offsets such as India's UTC+5:30 or Nepal's UTC+5:45. The campaign service groups the snapshot by time zone and releases each group at its local 9:00. It must use the IANA time-zone database for daylight saving transitions, not fixed offsets. A user whose time zone is unknown gets a default, such as the inferred country's main zone.
  • Quiet hours. A worker that finds a user in quiet hours does not drop a normal-priority message. It defers it, re-scheduling it for the end of the quiet window, unless that time is past expires_at, in which case it drops it with expired. Security categories bypass quiet hours by policy.
  • Thundering herds at round times. Many clients schedule at exactly :00. Spread non-urgent scheduled sends with a small random jitter of up to a few minutes, so the whole platform does not spike at each hour.
  • Send-time optimisation. For marketing, the best time is often per user, based on when they usually open the app. The campaign service can assign each user a send time within a window, which also smooths load (Deep Dive 12).

5) How does campaign fan-out work for tens of millions of recipients?#

Basic: query the segment and loop over the results, enqueuing each user. One long-running process streams a 20M-row query and publishes as fast as it can. This has four problems:

  • If it crashes at row 12M, it is not clear where to resume, and the query's results may have changed since it started.
  • It enqueues 20M messages in a few minutes, swamping downstream workers and providers.
  • It cannot be paused or cancelled cleanly.
  • The query itself can overload the user database.

Better: snapshot, chunk, checkpoint and throttle. This is the high-level design:

  1. Resolve the segment once against a replica or the analytics warehouse, not the primary user database, and write the result as immutable chunks of about 10k user ids.
  2. Process each chunk as a unit of work, with a status (pending, in_progress, done) in the campaign table. Multiple fan-out workers process different chunks in parallel. A crashed worker's chunk is retried, and campaign-level dedupe (campaign_id + user_id) absorbs the overlap.
  3. Use a token bucket shared by all fan-out workers for the campaign (a Redis counter) to enforce the campaign's send rate.
  4. Keep pause and cancel cheap, as a status flag checked between chunks and by downstream workers.

Best: shape the campaign around the downstream system, including the app itself.

  • Provider-aware pacing. The campaign's rate is the minimum of its own throttle, the bulk share of each provider quota (Deep Dive 2), and current downstream lag.
  • Protect the app's backend. A push to 20M users can cause millions of app opens within a minute, each calling the feed, product or video service. Coordinate the send rate with the receiving product team, or spread the send over 15-30 minutes. This is the notification equivalent of a thundering herd.
  • Expand late, personalise late. Keep the segment snapshot as ids only, and render per recipient in workers, so the content is in the user's locale and reflects current data such as the price at send time.
  • Pre-flight checks. Send a test to an internal seed list. Check the template renders for every locale in the segment. Estimate cost, which matters for SMS. Require a second approval for campaigns above a size threshold. A mistaken campaign to 20M people cannot be recalled.
  • Audience-level dedupe and suppression. Remove users who are globally suppressed (complaints, hard bounces, legal holds) at snapshot time, so their messages are never enqueued at all.

Very large audiences. For "everyone", 200M users, the same design scales by chunk count, about 20,000 chunks. But consider whether pushing to everyone is right. Topic-based push (FCM topics) lets the provider do the fan-out for broadcast messages, at the cost of per-user personalisation and per-user preference checks at send time.

6) How are preferences stored and enforced so that an opt-out is never violated?#

Basic: a boolean notifications_enabled per user. It is too coarse. Users who want security alerts but no marketing have to choose between missing important messages and receiving spam. They turn everything off, or worse, uninstall the app.

Better: a category × channel matrix, plus quiet hours, time zone and caps. Store per user:

user_id: u_123
timezone: Asia/Kolkata
locale: en-IN
categories:
  security:   { push: on,  email: on,  sms: on }    # some categories cannot be fully disabled
  social:     { push: on,  email: off, sms: off }
  marketing:  { push: off, email: on,  sms: off }
quiet_hours: { start: "22:00", end: "07:00", except: [security] }
frequency_caps: { marketing: { push: 2/day, email: 1/day } }
consent:
  sms:   { status: opted_in, source: signup_form, at: 2026-03-01T10:00:00Z }
  email: { unsubscribed_categories: [newsletter] }

Defaults come from the category definition, so a user row stores only overrides. That keeps rows small and lets new categories ship with sensible defaults.

Best: treat preferences as a correctness-critical service with fast reads and safe staleness.

  • Read path. Workers do about 200k preference reads per second at peak. Cache entries in Redis and in a small in-process cache with a short TTL of 30-60 s. Invalidate on change through a pub/sub message, so most changes apply within a second.
  • Fail safe on staleness. An opt-in that is a minute late is harmless. An opt-out that is a minute late violates the user's choice, and possibly the law. So writes that restrict sending (opt-out, STOP, unsubscribe) also go to a fast-propagating suppression list, a Redis set or Bloom filter per channel, that workers check synchronously. Opt-ins propagate normally.
  • Check at send time and again at the sender. The worker checks before rendering. For SMS and email, the sender re-checks the suppression list immediately before the provider call, because a message may have waited in a channel queue during a provider outage.
  • Legal and channel rules.
    • Email needs an unsubscribe link and, for bulk senders, one-click unsubscribe headers (List-Unsubscribe with List-Unsubscribe-Post, RFC 8058). Since 2024, large mailbox providers such as Gmail and Yahoo require them for bulk mail.
    • SMS needs recorded consent in many jurisdictions (for example under the US TCPA) and must honour keywords like STOP and HELP. Aggregators often enforce this too.
    • Laws such as CAN-SPAM and GDPR shape what marketing may be sent and what must be recorded.
    • Store consent with its source and time as an auditable record.
  • Unsubscribe tokens. Links contain a signed token (user, category, channel, expiry), so a click unsubscribes without login and cannot be forged to unsubscribe someone else.
  • Exposure to users. A settings page shows categories in plain language, and every notification shows "why am I getting this?" with a one-tap path to turn that category off. Good preference UX reduces uninstalls and complaints, which protects deliverability for everyone.

7) How do we apply rate limits: per client, per user and per provider?#

There are three different limits, protecting three different things:

  1. Client quotas protect the platform from its callers.
  2. User frequency caps protect users from us.
  3. Provider limits protect our accounts with third parties.

Before any limit can apply, we must identify who is calling and decide where the limiter lives. The same two decisions come up when designing any rate limiter, and they are linked.

Identifying the caller. For a platform API, the natural identity is the client service, taken from its authenticated credentials (an mTLS certificate or a service token). It is never taken from a request field the caller could fake. Within a client, limits can also be keyed by category ("marketing tool, marketing category") and, for user-triggered actions, by end-user id ("password-reset requests for user u_123"). IP addresses are useless here, because every call comes from inside the data centre. They matter only for the user-facing preference and inbox APIs, which sit behind the public gateway and use the usual user-id, API-key and IP limits there.

Where the limiter lives.

  • Inside each API server process. It is fastest, with no network hop, but each server only sees its own share, so limits are inaccurate with dozens of instances.
  • A dedicated rate-limit service or shared Redis. Counters are global and accurate, at the cost of one fast round trip, about 0.5 ms.
  • An API gateway in front of the platform. It is convenient for coarse per-client limits and keeps abusive traffic away from our servers. But the gateway lacks business context, such as category or per-user caps.

We use the gateway for coarse per-client request limits, and a shared Redis-backed limiter inside the platform for category, user and provider limits.

Basic: one global request limit per client at the API. It stops a runaway client, but a client within its limit can still send 50 marketing pushes to one user in an hour.

Better: per-client, per-category quotas plus per-user caps evaluated in workers.

  • Client quotas. For example "marketing tool: 10k campaign recipients per second, 100M per day". These are token buckets in Redis keyed by client:category. Over-quota single sends get 429 at the API. Over-quota campaign fan-out is simply paced.
  • User frequency caps. For example "no more than 2 marketing pushes per user per day". These are counters keyed by cap:{user}:{category}:{channel}:{day} with a TTL, incremented atomically when a send is committed. A message over the cap is dropped with capped (for marketing) or deferred (for digests). Transactional and security categories are never capped.
  • Global caps across categories. For example "at most 5 pushes per user per day in total, excluding security". These need a total counter. The reference treats them as optional.

Best: provider-aware limiting with feedback, and fairness between clients.

  • Provider limits are hard external constraints:
    • SMS aggregators and carriers limit messages per second per sender number and per account. Long-code numbers are typically only about one message per second, so high-volume SMS needs short codes, toll-free or registered sender types, and pools of numbers.
    • Email providers set sending quotas per account and per IP.
    • Mailbox providers throttle senders whose reputation is new or poor, so new IPs must be warmed up, sending gradually more each day.
    • Senders keep a token bucket per provider, account and sender identity, sized just below the contracted limit. They slow down when the provider returns 429 or "throttled" errors, an additive-increase, multiplicative-decrease response similar to TCP congestion control.
  • Fair sharing between clients. When a provider is the bottleneck, bulk traffic from many clients shares it by weighted fair queueing, so one team's 20M campaign cannot block another team's 1M campaign for an hour.
  • Budget limits. Per-client daily cost budgets for SMS stop a bug from spending a fortune overnight.

See Rate Limiting and Throttling for algorithms.

8) How do templates, localisation and personalisation work?#

Basic: clients send the final text. It is simple, but every team re-implements formatting and localisation. Content is not reviewed. Users get English messages in Hindi-language apps. And changing a typo means redeploying the client service.

Better: a template service with versioned, per-channel, per-locale templates. A template has:

  • An id and a category, for example login_alert, category security.
  • Declared variables with types, for example city: string, device: string, time: datetime. The API validates requests against them.
  • Channel variants. A push title of about 50 characters and a body of about 150. SMS text, kept within one or two segments: 160 GSM-7 characters per single segment, or 70 with Unicode, since non-Latin scripts and emoji force UCS-2 encoding and multiply SMS cost. An email subject, preheader, HTML and plain-text part. An in-app title, body and deep link.
  • Locales, with a fallback chain, for example hi-IN → en-IN → en.
  • Immutable versions. A notification records template_id and version, so what was sent is always reproducible. Publishing a new version needs review for high-volume categories.

Workers render with a logic-less template language (Mustache or Handlebars style) that escapes variables by default. HTML-escape variables for email, never allow raw user input into links, and encode URLs. Compiled templates are cached in the worker, so rendering is a fast in-memory operation of about 50-200 µs.

Best: treat templates as code, with safety, testing and personalisation at send time.

  • Preview and test. Render every variant and locale with sample data in CI. Check push lengths, SMS segment counts and email HTML size (some mail clients clip messages above about 100 KB). Send test messages to seed devices and inboxes.
  • Safe failure. If a variable is missing or rendering fails, do not send a broken message. Send the notification to the DLQ with an alert to the template owner. A broken template must fail closed, never Hello {{first_name}}.
  • Personalisation at send time. Variables can be resolved by the worker from internal services at send time, such as "current price" or "unread count". That keeps campaign payloads small and content fresh, but adds a dependency on the hot path, so cache those lookups and set timeouts with fallbacks.
  • Rich content. Push notifications can include images and actions. iOS uses a notification service extension to download media on the device. Keep media on a CDN with short URLs, and never put large binaries in the payload, which is limited to about 4 KB.
  • Experimentation. Template variants can be A/B tested per campaign, with assignment recorded per notification so open rates can be compared.

9) How do the channel providers work, and what happens when one fails?#

How a push actually reaches a phone.

  1. When the app starts, it asks the operating system for a push token. iOS gets one from APNs, Android from FCM.
  2. The app sends the token to our backend with the user id, platform and app version. We store it in the device registry and refresh it on every app start, because tokens change after reinstalls, restores and OS updates.
  3. To notify, our push sender sends an authenticated request to the provider.
    • APNs uses HTTP/2 with either a token-based credential (a signed JWT from a .p8 key) or a TLS certificate. Each request carries the device token, a JSON payload, and headers such as apns-priority, apns-push-type, apns-expiration and apns-collapse-id.
    • FCM's HTTP v1 API uses OAuth 2 service-account credentials, and the message includes the registration token, a notification and data payload, and options such as priority, time to live and collapse key.
  4. The provider holds a long-lived, encrypted connection to each device, managed by the OS, so apps do not each keep their own connection and drain the battery. It delivers the message when the device is reachable. If the device is offline, the provider stores the message for a while, with only the latest collapsible message kept, and delivers it later or discards it after the expiration.
  5. The OS displays the notification, or wakes the app for a silent data message, within OS limits.

So our "delivered" for push really means "accepted by APNs or FCM". The only end-to-end signal is the app reporting that it received or opened the notification.

Error handling that keeps the registry clean.

  • APNs 410 Unregistered, 400 BadDeviceToken and FCM UNREGISTERED or NOT_FOUND mean the token is dead. Mark it invalid and stop sending to it. Sending to dead tokens wastes capacity and can count against you.
  • 429 or quota errors mean slow down.
  • 5xx errors are transient: retry with backoff and jitter.
  • Payload or authentication errors are bugs: send them to the DLQ and alert.

Basic: one provider per channel and simple retries. If our only SMS aggregator has an outage, OTPs stop, and users cannot log in.

Better: retries with exponential backoff and jitter, plus a circuit breaker per provider.

  • Retries cover transient errors, for example 1 s, 2 s, 4 s, ... capped, and bounded by expires_at. Retry budgets prevent a retry storm when the provider is struggling.
  • A circuit breaker opens when a provider's error rate or latency crosses a threshold. While it is open, the channel queue holds messages rather than hammering a failing provider, and a probe request tests recovery.

Queued messages wait durably. When the provider recovers, the backlog drains at the provider's rate limit, oldest first, with expired messages dropped. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.

Best: multi-provider routing with health scoring, and cross-channel fallback.

  • For SMS and email, contract two or more providers and route between them by health (error rate, delivery receipt rate, latency), cost per destination country, and per-country quality. Many SMS routes are better through one aggregator in one country and another elsewhere. On a breaker trip, shift traffic to the secondary within seconds. Sender identities (short codes, email domains and IPs) must be provisioned on both in advance. A failover that requires a new number registration in the middle of an outage is no failover.
  • Push has no alternative provider: APNs is the only way to reach iOS. So the fallback is a different channel. For critical messages, if push is not opened or acknowledged within N minutes, or the user has no valid token, fall back to SMS or email according to the category policy. This "escalation ladder" is usually push → in-app → email → SMS, ordered by cost and intrusiveness.
  • Keep credentials safe. APNs keys, FCM service accounts and provider API keys live in a secrets manager, are rotated, and are scoped per environment. A leaked push key lets anyone notify all your users.
  • Email deliverability is a system of its own.
    • Authenticate with SPF, DKIM and DMARC.
    • Separate IPs and subdomains for transactional and marketing mail.
    • Warm up new IPs.
    • Process bounces: suppress hard bounces immediately, retry soft bounces a few times.
    • Process complaints from feedback loops: suppress and investigate.
    • Keep the spam-complaint rate low. Large mailbox providers publish thresholds, for example Gmail's guidance to stay below 0.3%.

10) How is delivery tracked, and how does feedback flow back?#

Basic: write a status column on the notification row. Several channels per notification, several attempts per channel, and asynchronous callbacks arriving minutes later, all updating one row at 300k events per second, cause contention and lost updates.

Better: an append-only event log of status transitions per delivery. Every stage emits an event: accepted, dropped_by_policy (with reason), rendered, sent (with provider message id), delivered, bounced, failed (with error), opened, clicked, expired. Events go to a status topic and are written to the delivery log, partitioned by notification id. The current status is the latest event by a fixed precedence order, so out-of-order arrival does not matter. A late delivered after opened does not regress the status.

Feedback mapping. Provider callbacks carry the provider's message id. The sender stores a mapping provider_message_id → (notification_id, delivery_id) with a TTL of a few days, so the feedback processor can attach receipts to the right delivery. Webhook endpoints must be authenticated with provider signatures, be idempotent (providers retry webhooks), and quickly acknowledge then process asynchronously, because providers time out slow webhook receivers.

Best: close the loop into preferences, the registry, quality metrics and clients.

  • Feedback changes future sends. Hard bounces and complaints add the address to the suppression list. An SMS "STOP" reply opts the number out. Dead push tokens disable devices. All of this happens within seconds.
  • Clients see what happened. The status API returns per-delivery history, and optional status webhooks to client services let, for example, the auth service offer "send by email instead" if an SMS bounced.
  • Quality metrics per provider, country, template and category: acceptance rate, delivery-receipt rate, open rate and time-to-deliver percentiles. These feed provider routing (Deep Dive 9) and catch silent failures, such as one carrier dropping messages while still returning 200.
  • Opens and clicks. Push opens come from the app. Email opens come from tracking pixels, which are unreliable because of image proxies and privacy features such as Apple Mail Privacy Protection, so prefer clicks. Clicks come from redirect links. Respect privacy settings and regulations: tracking is a product and legal decision, not just a technical one.

Cross-channel coordination uses the same events. A single notification often has a primary channel and a delayed fallback, for example "push now, email in 30 minutes if not seen". The tracking events decide whether the fallback still runs:

  1. When the notification is accepted, the router writes the push delivery and also a scheduled fallback job for the email, with send_at 30 minutes later and a condition: "only if no opened or read event exists for this notification".
  2. If the user taps the push, or reads the item in the in-app inbox on any device, the open event arrives on the status topic. The feedback processor marks the notification as seen, so the condition no longer holds.
  3. When the fallback job fires, the scheduler re-checks the condition against the current status. If the notification was seen, it records dropped_by_policy: already_seen and sends nothing.

Two details matter. First, the check happens at fire time, not only when the job was created, because the open may come seconds before the deadline. Second, the "seen" signal is imperfect: a user can read the push text on the lock screen without tapping, which produces no event. So the fallback delay should be long enough for normal engagement, and categories decide whether the extra email is acceptable. For security alerts, sending both is right. For social updates, one channel is enough. The same mechanism implements "reminder if not acted on", such as "your cart is waiting", and "cancel if the condition changed", such as "do not send the shipping-delay email if the parcel has already been delivered". The condition is evaluated against the producer's domain state through a lightweight check API, not against stale data copied into the job.

11) How do the in-app inbox and badge counts work across devices?#

The in-app channel is the only one we fully own. There is no third party and no per-message cost, and it keeps a history the user can scroll. It has two parts: a durable inbox (the notification centre list) and a live signal that updates open screens and badge counts.

Basic: an inbox table in the main relational database, queried with SELECT ... ORDER BY created_at DESC LIMIT 20 and SELECT COUNT(*) WHERE read = false on every app open. It works for thousands of users. At 75M in-app items per day and tens of thousands of app opens per second, the count query scans more and more rows, and the table becomes the hottest in the database.

Better: a wide-column store partitioned by user, plus a stored unread counter.

  • Inbox rows go in Cassandra, ScyllaDB or DynamoDB with partition key user_id and clustering key created_at DESC, notification_id. The common query, "latest 20 for this user", is a single-partition, sequential read that takes a few milliseconds whatever the total size. A TTL (for example 90 days) keeps partitions bounded, and a cap (keep the newest 500) protects against users with huge histories.
  • The unread count is a separate counter per user, in Redis or a counter column, incremented when an item is inserted and reset or decremented on "mark read". Counting rows on every open is replaced by one key read.
  • Counters drift: a lost decrement or a double increment shows "3" when nothing is unread. So reconcile periodically, or when the user opens the inbox, by recomputing from the partition and overwriting. Users notice a stuck badge more than a slightly late one.

Best: a "read cursor" instead of per-item read flags, a live channel, and sync across devices.

  • Read cursor. Most users "read everything up to here". Store a per-user last_seen_at. Unread = items newer than the cursor, which is bounded by the cap and cheap to count in the partition. Per-item read flags are kept only for items the user explicitly opens. This turns "mark all as read" from N writes into one write.
  • Live updates. While the app or web page is open, a connection gateway holds a WebSocket or Server-Sent Events connection per session (see Polling, Long Polling, SSE, WebSockets and Webhooks). The in-app sender writes the inbox row, then publishes "new item for user U" to a pub/sub channel. The gateway nodes holding U's sessions push it to the client. If the user is offline, nothing is lost: the inbox row is the source of truth and the client fetches it when it next connects. The live signal is only an optimisation. See Pattern: Pushing Realtime Updates for routing user → gateway node.
  • Multi-device sync. When the user reads on the phone, the laptop's badge should clear too. "Mark read" writes the cursor, then publishes a read_state_changed event to all of the user's sessions. For devices that are not connected, a silent push (a data-only message) can update the app icon badge on iOS, where the badge number is set by the payload. Note the race: a push sent with badge: 5 just before the user reads everything shows a stale 5. The next sync corrects it. That is acceptable, but design for it.
  • Ordering and idempotency. Insert with notification_id as part of the key so a retried write overwrites rather than duplicates. Clients deduplicate by id when merging live events with fetched pages.

Numbers: 75M items per day ≈ 870 writes/s on average, a few thousand per second at peak. That is easy for a small Cassandra cluster. Reads are the larger load: if 50M daily users open the inbox or fetch the badge 10 times a day, that is 500M reads per day ≈ 6k/s average and perhaps 30k/s at peak, served mainly from the counter cache.

12) How do we avoid notification fatigue: batching, digests and relevance?#

Sending more notifications does not mean more engagement. Every irrelevant push teaches the user to ignore you or turn notifications off, and on iOS turning them back on is rare. So the system must sometimes decide not to send, or to combine.

Basic: send every event as it happens, with per-user frequency caps. "Alice liked your photo", "Bob liked your photo", "Carol liked your photo" arrive as three pushes in a minute. Caps cut off the fourth but do not choose the best one.

Better: aggregation windows and digests.

  • Aggregation (collapsing). For aggregatable categories (likes, comments, follows), the first event opens a short window, for example 5–15 minutes, keyed by (user, category, object). Further events within the window are added to the group, not sent. When the window closes, one notification is rendered: "Alice, Bob and 3 others liked your photo". Store the window state in Redis with a TTL and a delayed "flush" task in the scheduler (Deep Dive 4). If the first event should be sent right away, send it, then roll later ones into an update that replaces the earlier notification using the collapse id.
  • Digests. Lower-priority events are not sent at all in real time. They are written to a per-user digest buffer, and a scheduled job builds one email or push per day or week: "Your weekly summary". The digest job is a campaign over users with non-empty buffers, running at each user's local preferred time.
  • Category-level choices. Preferences let users pick "instant", "daily digest" or "off" per category. This respects the user and reduces volume.

Best: relevance scoring and a per-user notification budget. This is how large consumer apps approach it, and the same thinking appears in news-recommendation designs, where a "should we notify about this story" step ranks candidates before sending.

  1. Candidate generation. Events produce candidate notifications for a user instead of immediate sends. A news app produces candidates from breaking stories, topics the user follows and local news.
  2. Scoring. A model estimates the value of each candidate to this user, for example P(open) times content value, minus a fatigue penalty based on how many notifications they received recently and whether they ignored the last ones. Features include past open rate by category, time since last notification, relationship strength (a close friend's comment versus a stranger's like), and freshness.
  3. Budget and threshold. Each user has a daily budget (for example, at most 3 marketing-type pushes) that adapts: users who engage get more, users who ignore get fewer. Only candidates above a threshold within the budget are sent. The rest go to the inbox or the digest.
  4. Send-time optimisation. For non-urgent messages, choose the hour when this user historically opens notifications, within their local waking hours. This is a per-user send_at computed by the scheduler.
  5. Guardrails. Transactional and security categories are never ranked or budgeted: OTPs, receipts and fraud alerts always go. Ranking applies only to engagement and marketing categories. Measure with holdout experiments: does the change increase long-term retention and keep opt-out rates flat, not just today's open rate?

The architecture cost is small: a ranking service between the event consumers and the send API, plus feature stores of per-user engagement history built from the delivery and open events of Deep Dive 10. The notification platform stays the same. Ranking decides whether and when. The platform still decides how.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Campaign of 20M floods shared queuesOTPs and alerts wait behind marketing, logins failSeparate priority topics and worker pools, campaign pacing, reserved provider quota for high priority (DD2, DD5)
Notification service writes DB, then crashes before enqueueAccepted notification never sentTransactional outbox with CDC relay, or queue-first with acks=all, plus reconciliation of stuck rows (DD1)
Worker retries after send but before ackDuplicate push or SMSIdempotency key per delivery in Redis with in-progress state, provider collapse ids, accept rare duplicates (DD3)
SMS aggregator outageOTPs fail, users locked outTwo or more providers, health-based routing, circuit breaker, pre-provisioned sender ids on both (DD9)
APNs or FCM throttling or errorsPush backlog growsPer-provider concurrency limits, AIMD backoff, durable channel queue, drain oldest first, drop expired (DD7, DD9)
Dead device tokens accumulateWasted sends, provider penaltiesHandle 410 and UNREGISTERED immediately, refresh tokens on app start, prune devices unseen for months (DD9)
Preference or suppression lookup slowEvery send waits, throughput dropsCache preferences per user with short TTL and invalidation on change, batch lookups in campaign workers (DD6)
Scheduler hot bucket at 09:00Many jobs due in the same secondShard time buckets, jitter non-urgent sends, spread local-time campaigns by zone (DD4)
Status events storm, 300k per secondStatus DB write contention, slow dashboardsAppend-only event log partitioned by notification id, aggregate metrics in a stream processor, not in OLTP (DD10)
Bad template version deployedBroken or wrong text to millionsImmutable versions, preview and test sends, fail closed on missing variables, canary percentage before full campaign (DD8)
Email spam complaints riseDomain reputation falls, mail goes to spam for everyoneSeparate transactional and marketing domains and IPs, honour unsubscribes fast, suppress complainers, watch complaint rate (DD6, DD9)
Inbox unread counter driftsWrong badge, user confusionRead cursor model, periodic recount and overwrite, idempotent inserts keyed by notification id (DD11)

What Interviewers Expect#

Mid-level#

  • Clarify the channels, scale and priorities, then draw the basic pipeline: API → notification service → queue → per-channel workers → APNs, FCM, SMS and email providers.
  • Explain why a queue sits between accepting a request and calling providers: absorbing spikes, retries, and isolating slow providers.
  • Store device tokens and preferences, check opt-outs before sending, and retry failures with backoff.
  • Know the basics of each channel: push tokens, SMS cost, email deliverability.

Senior#

  • Separate priorities into different queues and worker pools, and explain why a campaign must never delay an OTP.
  • Handle the dual-write problem with an outbox or queue-first design, and explain at-least-once delivery plus idempotency keys for dedupe.
  • Design campaign fan-out with snapshots, chunked jobs and pacing, and scheduling with time buckets and local time zones.
  • Cover rate limits at several levels (per client, per user, per provider), templates with versions and localisation, and delivery tracking with provider callbacks.
  • Discuss provider failure: circuit breakers, multi-provider SMS and email, fallback across channels.

Staff+#

  • Treat the platform as a product for many internal teams: client identities, quotas and budgets, categories with policies, self-service templates and campaigns, and clear SLOs per priority (for example 99% of high-priority sends handed to the provider within 5 s).
  • Reason about end-to-end guarantees honestly: "delivered" means accepted by a provider, duplicates cannot be fully ruled out across a provider boundary, and the design chooses where to accept which risk.
  • Bring in compliance and trust: one-click unsubscribe, consent records, quiet hours, regional data rules, and the reputation of sender domains and numbers as a shared resource to protect.
  • Think about relevance and fatigue: aggregation, digests, ranking and budgets, measured with holdouts against long-term retention and opt-out rates.
  • Plan operations: capacity by channel, cost (SMS dominates spend), multi-region failover, game days that simulate provider outages, and dashboards per provider, country and template.
Deep Dive: The mathematics of queues, priorities, retries, dedupe memory and costShow

Little's Law everywhere. Little's Law says that in a stable system the average number of items inside equals the arrival rate times the average time each item spends inside: L = λ × W. John Little published the proof in 1961, and it holds for any queueing discipline. It answers three sizing questions in this design.

  • Concurrency to providers. At 100k sends/s and 150 ms provider latency, about 15k requests are in flight. If provider latency doubles to 300 ms during an incident, the same throughput needs 30k in flight. If the sender pool's concurrency is capped at 15k, throughput halves to 50k/s and the backlog grows. Size concurrency for the slow case, and treat rising provider latency as an early warning.
  • Queue length. If the push-high lane receives 2k/s and each message waits 0.5 s on average before a worker picks it up, about 1,000 messages sit in that lane. A lag of 100,000 messages at the same rate means each new message waits about 50 s. That breaks a 5 s target. So alert on lag in seconds (lag divided by the consumption rate), not raw message counts, because the same count means different things at different rates.
  • Inbox gateway connections. If 50M users open the app on average for 20 minutes a day, average concurrent sessions = 50M × 20 / 1440 ≈ 700k, with peaks perhaps 2–3 times higher. That sets the WebSocket gateway fleet size.

Why a shared queue destroys priority latency. In the simplest single-server queue model (M/M/1: random arrivals, random service times, one server), the average waiting time is Wq = ρ / (μ − λ), where λ is the arrival rate, μ the service rate and ρ = λ/μ the utilisation. As a multiple of the service time, the wait is ρ / (1 − ρ). That is 1× at 50% utilisation, 9× at 90% and 99× at 99%. Real systems are not M/M/1, but the shape is universal: waiting time explodes as utilisation approaches 1. A campaign pushes the shared pool to full utilisation by design, because it is trying to send as fast as allowed. So any OTP in the same FIFO waits behind the whole backlog. Concretely, 20M campaign messages enqueued at once, drained at 20k/s, take 1,000 s, about 17 minutes. An OTP arriving one second after the campaign waits about 17 minutes.

With separate lanes, the high lane's utilisation depends only on high-priority traffic. If it runs at 30% utilisation with 50 ms service, the M/M/1 wait is about 0.43 × 50 ms ≈ 21 ms. The same message waits milliseconds instead of minutes. This is the quantitative argument for Deep Dive 2. Strict priority within a single pool can also work, but only if workers always pick high before normal and the provider connection is not saturated by in-flight bulk requests. That is why reserved provider quota is also needed.

Backlog after an outage. Suppose the push provider is down for 10 minutes while 6k/s arrive. The backlog is 6k × 600 = 3.6M messages. When it recovers, if senders can do 10k/s, the spare capacity is 10k − 6k = 4k/s, so the backlog drains in 3.6M / 4k = 900 s = 15 minutes. Total impact is 25 minutes, not 10. Two lessons follow. First, spare capacity determines recovery time: running at 90% utilisation leaves almost no room to recover. Second, drop or reprioritise what has expired. Messages past expires_at should be discarded during the drain, and the high lane drains first.

Retries: helpful when failures are independent, dangerous when they are correlated.

  • If each attempt fails independently with probability p, then k attempts fail with probability p^k. With p = 1% transient errors, 3 attempts give 1 in a million. That is why a few retries make random errors disappear.
  • During an outage, failures are correlated: every attempt fails, and retries only add load. With 3 retries at each of 2 layers (for example the worker and an HTTP client library underneath it), one request can become (1 + 3) × (1 + 3) = 16 attempts. A provider at its limit receives 16 times the traffic at exactly the worst time.
  • The defences are to retry at one layer only, use exponential backoff with full jitter (sleep a random time between 0 and min(cap, base × 2^attempt), which spreads synchronised clients), and set a retry budget (for example retries may add at most 10% extra load per provider). Above the budget, stop retrying and let the circuit breaker hold messages in the queue.

Dedupe memory. Assume 600M deliveries a day (500M notifications, some with several channels).

  • Exact keys in Redis. About 100 bytes per key, including overhead, with a 24-hour TTL: 600M × 100 B = 60 GB. That is a modest Redis cluster. With a 1-hour TTL, which covers almost all retries, it falls to about 2.5 GB.
  • A Bloom filter with n = 600M and a 0.1% false-positive rate needs m = −n ln p / (ln 2)² ≈ 600M × 6.91 / 0.48 ≈ 8.6 Gbit ≈ 1.1 GB, with k ≈ 10 hash functions. But a false positive here means dropping a real notification, which is the wrong failure direction for an OTP. Use a Bloom filter only as a fast "definitely new" check, and confirm "maybe seen" answers against the exact store.

Cost model. With the planned mix of 500M a day:

ChannelVolume per dayAssumed unit costCost per day
Push350Mnearly zero, compute onlysmall
In-app75Mstorage and gateway computesmall
Email50M$0.0001–0.001$5k–50k
SMS25M$0.005–0.05$125k–1.25M

SMS is 5% of the volume and well over 90% of the spend. Every 1% of SMS volume moved to push saves about $25k–250k a day at these assumptions. That is why the routing policy (push first, SMS only as a fallback for critical unacknowledged messages), dedupe of SMS in particular, and SMS segment length (Deep Dive 8: a 161-character GSM-7 message bills as two segments) are worth engineering effort. The unit costs above are assumptions for estimation. Real prices vary by provider, contract and country.

Fan-out throughput. A campaign of 20M users at a pacing limit of 20k/s takes 1,000 s. Split into chunks of 10k users, that is 2,000 chunk jobs. With 200 campaign workers each processing one chunk in about 5 s (preference lookups batched, rendering cached), the fan-out stage could produce 400k/s. So the bottleneck is always the deliberate pacing and the provider limits, not the fan-out stage. The pacing is the dial that protects everything else.

Deep Dive: How the real platforms and protocols shaped this designShow

APNs.

  • Apple's provider API moved from a custom binary protocol to HTTP/2 in 2015. The binary interface was later retired, in 2021.
  • HTTP/2 matters because one TLS connection multiplexes many concurrent requests, each with its own status code. The old binary protocol reported errors asynchronously and closed the connection on a bad token, so senders had to replay everything sent after the failure.
  • Token-based authentication with a .p8 signing key replaced per-app certificates for most providers. One key can sign for several apps and does not expire every year, which removed a classic outage: the forgotten certificate renewal.
  • Payloads are limited to 4 KB for regular remote notifications. That is why we send ids and short text, never documents.

FCM.

  • Firebase Cloud Messaging succeeded Google Cloud Messaging, which Google shut down in 2019.
  • In 2023 Google deprecated FCM's legacy HTTP and XMPP APIs in favour of the HTTP v1 API, with short-lived OAuth 2 tokens instead of a static server key, and required migration in 2024.
  • The design lesson is that provider APIs change on the provider's schedule. Keep each provider behind an adapter in the channel sender, so a migration touches one component.
  • FCM distinguishes normal and high-priority messages. High priority can wake a device from Android's Doze power-saving mode, but Android may deprioritise an app that sends high-priority messages without showing a notification. So priority on the wire must match user-visible urgency. That is one more reason to tie priority to categories, not let each caller choose.

The operating systems decide the last mile.

  • Android 8.0 added notification channels: per-category settings the user controls in the OS. Android 13 made posting notifications a runtime permission the user must grant.
  • iOS 15 added interruption levels (passive, active, time-sensitive and critical) and the scheduled notification summary, which can batch non-urgent notifications into a digest at times the user chooses.
  • Our categories should map onto OS channels and interruption levels. The OS will apply its own batching anyway, so a platform that spams loses the user at the OS level, not just in our preference centre.

Web Push is an open standard:

  • RFC 8030 defines the protocol to a browser's push service.
  • RFC 8291 defines end-to-end encryption of the payload, so the push service cannot read it.
  • RFC 8292 (VAPID) identifies the application server with a signed JWT.

The browser gives our page a subscription endpoint URL plus keys. We store these like device tokens and receive 404 or 410 when the subscription is gone.

SMS runs over a chain: our platform → an aggregator's HTTP API → carrier connections, often over the SMPP protocol → the carrier's SMS centre → the handset.

  • Each hop can delay or drop. Delivery receipts come back along the same chain, and their quality varies by carrier and country.
  • Regulation also varies. Some countries require registered sender ids or templates. In the US, application-to-person messaging on ordinary long numbers requires registration (10DLC), and short codes have their own approval process.

This is why serious senders use several aggregators and route by country.

Email.

  • Mailbox providers judge senders by authentication (SPF, DKIM, DMARC), complaint rates, bounce rates and engagement.
  • Gmail and Yahoo's 2024 bulk-sender requirements made authentication, one-click unsubscribe (RFC 8058) and low complaint rates mandatory for large senders.
  • Apple's Mail Privacy Protection (2021) pre-fetches images through proxies, which made open-pixel tracking unreliable. Many teams switched to clicks and conversions as the engagement signal.

Managed building blocks.

  • Cloud providers offer pieces of this platform as services. Amazon SNS can fan out to mobile push endpoints, SMS and email, and Amazon SES sends email. Twilio offers SMS and, through SendGrid, email.
  • Open-source projects such as Novu offer notification infrastructure (workflows, preferences, an in-app inbox) on top of these providers.

The decision is the usual build-versus-buy one. Buying covers channels and deliverability expertise quickly. Building makes sense when volume makes per-message fees significant, or when priorities, ranking and policy are core to the product.

Lessons from large consumer platforms. LinkedIn has described a central system, which it called Air Traffic Controller, that decides for each member which notifications and emails to send, through which channel and how often. It applies the frequency, aggregation and relevance ideas of Deep Dive 12 in one place, instead of leaving each product team to decide on its own. Netflix has written about RENO, its event notification system, which pushes events to devices so they can refresh state, using priority-based queues and a hybrid of push and pull. The common lesson is centralise the decision to interrupt a user. Many teams sending independently is how users end up with ten notifications an hour.

Deep Dive: Evolving, operating, securing and testing the platformShow

Evolve it in stages, and measure before each step. Do not build the final architecture on day one. The safe loop is: benchmark with realistic load, profile to find the real bottleneck, fix that one thing, and repeat. A typical path:

  1. One service, synchronous provider calls. A request handler calls SendGrid or Twilio directly. This is fine for thousands of messages a day. It breaks when a provider is slow, because request threads block and callers time out, or when a burst arrives.
  2. Add a queue and workers. Accept, store, enqueue and return 202 Accepted. Workers send asynchronously with retries. This one step absorbs spikes, isolates provider latency and makes retries safe. It is the most important change in the whole design.
  3. Split by channel. Separate queues and worker pools for push, SMS, email and in-app, because each has different latency, rate limits and failure modes. One slow channel no longer stalls the others.
  4. Split by priority. Add the high and low lanes, reserved provider quota and campaign pacing, once marketing campaigns exist. In practice this is often triggered by the first incident where a campaign delayed login codes.
  5. Centralise policy. Preferences, suppression, quiet hours, caps and templates move into the platform, so every caller gets the same rules.
  6. Multi-provider, multi-region and relevance. These come last, when volume, availability targets and fatigue justify them.

Autoscaling.

  • Scale senders on queue lag in seconds and in-flight concurrency, not CPU. Senders spend most of their time waiting on network I/O, so CPU stays low while the backlog grows.
  • Also scale on a schedule. Campaigns cluster at known times, such as 9 a.m. local time and before big events, so pre-warm workers and provider connections before the scheduled start. Reactive scaling alone lags behind a 20M burst by minutes.
  • Know the ceiling. Adding workers beyond the provider's rate limit only adds 429 responses. The limit on throughput is the provider quota, not our fleet.

Monitoring and alerting.

  • Metrics per lane: acceptance rate, lag in seconds, send rate, error rate by provider error code, and time from accept to provider acceptance (p50, p99).
  • Metrics per provider and country: delivery-receipt rate, bounce and complaint rates, latency, breaker state.
  • Business metrics: opt-out rate per category, open rate per template.
  • Alert on SLO burn, for example "high-priority p99 over 5 s for 5 minutes", and on sudden drops. A drop in delivery receipts from one carrier, with a 200 from the API, is a silent failure that only these metrics catch.
  • Page on-call through a tool such as PagerDuty. Send exceptions to an error tracker such as Sentry. Trace each notification by id across the API, queues and senders (see Observability: Logs, Metrics and Traces).
  • Keep a "why didn't I get it" tool for support staff. Given a user and a time range, it shows every notification, the policy decision (sent, dropped because opted out, deferred for quiet hours) and the provider response. Most notification support tickets are answered by this tool, not by engineers.

SLOs and error budgets per priority. One "99.9% delivered" target hides the differences that matter. Define targets per lane and measure them at the boundary we control, the provider handoff:

  • High (OTP, security): 99% handed to the provider within 5 s, 99.9% within 30 s, and zero accepted messages lost.
  • Normal (transactional, social): 99% within 60 s.
  • Low (campaigns, digests): completed within the campaign window, for example 20M recipients within 2 hours, with no SLO on individual messages.

An error budget turns this into decisions. If the high lane has burned most of its monthly budget, risky changes to the high-lane senders pause until reliability recovers, while the campaign tooling can keep shipping features. Track a separate correctness SLO for policy, such as "zero sends to suppressed or opted-out addresses", because a single violation can be a legal problem. Treat any breach as an incident, whatever the volume. Finally, report the end-to-end signals (delivery receipts, opens) as indicators, not SLOs. They depend on carriers, devices and users we do not control, but sudden changes in them are often the first sign of a problem on our side.

Security.

  • Only the API gateway is public. Workers, queues and databases live in private network segments (a VPC with private subnets) and reach providers through controlled egress.
  • Provider credentials (APNs keys, FCM service accounts, SMS and ESP API keys) sit in a secrets manager with rotation and least-privilege access.
  • Client services authenticate with service credentials, and each is authorised only for its own categories and templates. A compromised internal service must not be able to send "Your account is locked, click here" to every user, which is a perfect phishing channel.
  • Templates are escaped by default. Links go through an allow-listed redirect domain.
  • Personal data in payloads is minimised (lock-screen previews are visible to anyone holding the phone), encrypted at rest, and deleted by retention policy.
  • See Security Fundamentals for System Design.

Testing.

  • Provider simulators. A fake APNs, FCM, SMS and ESP that return configurable latencies, errors, 429 responses and delayed receipts. Load tests and failure tests run against them, never against real providers or real users.
  • Load tests at campaign scale: 20M recipients at full pacing while high-priority traffic is measured. The pass condition is the high-lane SLO, not raw throughput. See Capacity Planning and Load Testing.
  • Fault injection and game days.
    • Kill a provider, and check that breakers open, failover routes traffic and the backlog drains.
    • Kill workers in the middle of a send, and count duplicates.
    • Partition Redis, and check that dedupe fails in the designed direction.
    • Delay the clock, and check that the scheduler neither double-fires nor skips.
  • Contract tests for provider webhooks: replayed, out-of-order and forged callbacks must be handled idempotently and rejected when unsigned.
  • Canary campaigns. Every campaign first goes to an internal audience, then to a small percentage of users, with automatic halt if error or opt-out rates spike.

Multi-region.

  • Run the accept path active-active in two or more regions, so callers can always hand off a notification. Each region has its own queues and senders.
  • A notification is processed in the region that accepted it. Dedupe keys must therefore be checked where the send happens. Otherwise a client that retries to another region during a failover can cause a duplicate. Accept that rare risk for push, and use a globally replicated dedupe store for SMS OTPs if the cost justifies it.
  • Preferences and suppression lists are replicated to all regions. An opt-out must be honoured everywhere within seconds, and suppression is safety-critical, so replicate it with the highest priority.
  • Scheduled jobs and campaigns are owned by one region at a time, with failover through leases, so they never fire twice.

See Multi-Region and Global Data and Disaster Recovery and Backups.

Deep Dive: Variants: an OTP delivery service and a breaking-news broadcastShow

The same platform serves two very different extremes. Working through both shows which parts of the design are general and which are tuned for one shape of traffic.

Variant A: a one-time-password (OTP) service. The auth service needs a 6-digit code delivered by SMS (or voice call, or email) within seconds, for login and payment confirmation.

  • Volume and value. Volume is modest, perhaps 1–5% of all notifications. But every failure is a user who cannot log in, and every message costs money. Latency matters more than throughput: the target is "handed to the carrier within 1–2 s, on the handset within 10–20 s in most countries".
  • Design changes from the general platform:
    • A dedicated lane end to end, with its own sender pool, reserved quota at each aggregator, and dedicated sender ids or short codes. It is never shared with marketing, because carriers filter marketing traffic and the filtering can hit the shared sender.
    • Short expiry. The code is valid for, say, 5 minutes, so expires_at is 5 minutes, and an undelivered message is dropped rather than delivered late.
    • Fast failover. If the primary aggregator does not return a delivery receipt within a short window (for example 10–20 s, tuned per country), the user's "resend" goes through the secondary aggregator. Even better, the platform tracks per-country receipt rates and shifts routes before users notice.
    • Strict dedupe and abuse control. Rate-limit per phone number, per IP and per account: for example at most 3 codes per number per 10 minutes and a daily cap. Attackers abuse OTP endpoints to send expensive SMS to premium-rate numbers they own. This is known as SMS pumping or toll fraud. Defend with caps, country allow-lists, anomaly detection on traffic to unusual country codes, and CAPTCHA on suspicious flows.
    • Content. The message is short, in the GSM-7 alphabet where possible so it fits one segment. On iOS and Android, a standard format lets the OS offer the code for autofill (on the web, the WebOTP format binds the code to the domain), which also helps users spot phishing.
  • What the platform does not do. It does not generate or verify the code. The auth service owns the secret, stores a hash with an expiry and an attempt counter, and verifies. The notification platform only delivers text. Keeping the secret out of notification logs is a security requirement, so OTP templates mark the code variable as sensitive and logs redact it.

Variant B: breaking news to 100M devices within a minute. A news app wants every subscriber to a topic, say "World news", to receive an alert as fast as possible. The pacing that protects a marketing campaign is now the enemy.

  • The arithmetic. 100M devices in 60 s is about 1.7M sends/s. That is far beyond the 100k/s peak we planned, and far beyond what our own sender fleet and provider quota can sustain for a burst.
  • Option 1: let the provider fan out. FCM supports topic messaging. Devices subscribe to a topic, and we send one request to the topic. FCM fans out on its own infrastructure. This trades control (per-user preferences, quiet hours, ranking and per-device tracking are lost or reduced) for speed and simplicity. It fits "everyone subscribed gets the same alert".
  • Option 2: pre-compute and pre-shard. Keep subscriber lists per topic, already split into shards of device tokens grouped by platform and region, and already filtered by preferences. When news breaks, a broadcast job hands each shard to a sender, in parallel across many senders and many provider connections. Preference checks and rendering happen beforehand, so at send time the work is only "send this one payload to these tokens". The per-message path is as short as it can be.
  • Payload and server load. The payload is the same for everyone, so render once. Expect the "thundering herd" when millions tap at once: the article page and its API must be cached at the CDN before the alert goes out, and alerts can be staggered over a few minutes by region to spread the load on our own servers. Faster than the backend can serve is not a win.
  • Local relevance and fatigue. A breaking alert overrides normal budgets only for categories the user opted into. Editorial rules limit how many breaking alerts a day are allowed, because frequent "breaking" alerts teach users to disable them. This is the relevance problem of Deep Dive 12 again.

What stayed the same in both variants: durable acceptance, idempotency keys, the preference and suppression check, provider adapters with error handling, the delivery event log, and the monitoring. What changed: lane isolation, expiry, pacing, where the fan-out happens, and whether a policy is evaluated per send or precomputed. Interviewers often change the scenario midway ("now make it OTPs", "now 100M in a minute"). Showing which knobs move is the senior-level answer.

Key Takeaways#

  • Accept fast, deliver asynchronously. Validate, store durably, enqueue and return 202 Accepted. Workers per channel call the providers with retries. The queue between "accepted" and "delivered" absorbs spikes and isolates slow providers. See Asynchronous Processing and Message Queues.
  • Never lose an accepted notification. Avoid the dual-write problem with a transactional outbox and CDC relay, or with a queue-first design using durable acknowledgements. Add DLQs, expiry and reconciliation for anything stuck. See Change Data Capture and the Outbox Pattern.
  • Priority is isolation, not a field. OTPs and security alerts get their own topics, worker pools, provider quota and sender identities. Campaigns are paced and slowed by backpressure. A shared FIFO turns a 20M campaign into a 17-minute delay for a login code.
  • Delivery is at-least-once, so dedupe deliberately. Use idempotency keys at the API, a dedupe record per delivery with an in-progress state, and provider collapse ids. Be honest that a crash between "provider accepted" and "recorded" can still duplicate, and choose the safer failure per category. See Idempotency and Safe Retries and Delivery Guarantees: At-Most, At-Least and Exactly-Once.
  • Fan-out is a snapshot, chunks and pacing. Freeze the audience, split it into chunk jobs, check preferences in batches, and send at a controlled rate that respects provider limits. Support cancellation that actually stops in-flight chunks.
  • Policy lives in the platform. Preferences per category and channel, suppression lists, quiet hours in the user's time zone, frequency caps, one-click unsubscribe and consent records are applied to every send, by every team, the same way.
  • Rate limits exist at every layer: per client, per user, per provider and per country, with AIMD backoff on provider throttling and retry budgets to prevent retry storms. See Rate Limiting and Throttling and Resilience Patterns: Timeouts, Retries and Circuit Breakers.
  • Templates are versioned code. Immutable versions, localisation with fallbacks, channel-specific variants (SMS segments, push 4 KB limits, email HTML and text), escaping, and failing closed on missing variables.
  • Providers fail, so route around them. Use multiple SMS and email providers with health-based routing and circuit breakers, and fall back across channels for push, ordered by cost and intrusiveness. Treat dead tokens, bounces and complaints as feedback that updates the registry and the suppression list within seconds.
  • Tracking is an event log, not a status column. Append-only status events with precedence ordering, provider-id mapping for callbacks, signed and idempotent webhooks, and metrics per provider, country and template that catch silent failures.
  • The in-app inbox is ours. Store it in a wide-column store partitioned by user, with a read cursor and a cached unread counter that is periodically reconciled. Add live updates over WebSockets or SSE. See Pattern: Pushing Realtime Updates.
  • The best notification is sometimes none. Aggregation windows, digests, relevance ranking, per-user budgets and send-time optimisation protect the user's attention. That attention is the scarce resource the whole platform depends on.
  • Cost and scale drivers: SMS is a small share of volume but most of the spend. Throughput is bounded by provider quotas, not by our fleet. Little's Law sizes concurrency, lag in seconds drives alerts and autoscaling, and spare capacity determines how fast the platform recovers from an outage. See Capacity Planning and Load Testing.