Almost every product needs to reach users outside the app: login codes by SMS, order updates by push, receipts and newsletters by email. A notification system is the shared platform that accepts these requests from every team, respects each user's preferences, renders localized content, and delivers it through third-party providers such as APNs, FCM, Twilio and Amazon SES. The interesting problems are reliability (never lose an OTP, never send it twice), isolation (a marketing blast must not delay a login code) and politeness (rate limits, opt-outs and quiet hours).
Think of it like
A post office sorting hall
Letters arrive from every business in town. Clerks check each recipient's forwarding instructions and 'no junk mail' sticker, translate the address label, and drop each item into the right outgoing bin: a red express bin for registered letters and a big bulk bin for flyers. Couriers (APNs, Twilio, SES) take it from there. Undeliverable mail goes to a dead-letter office instead of being thrown away, and every parcel has a tracking number so nothing is delivered twice.
1. Requirements
Functional
- Send push (iOS and Android), SMS and email (in-app inbox optional)
- One API for every internal producer: auth, orders, social, marketing
- Per-user preferences: opt-outs by category and channel, quiet hours
- Templates with localization and versioning
- Scheduled sends, batching and digests
- Track delivery, bounces, opens and clicks
Non-functional
- No lost notifications, and no duplicate sends (effectively once)
- OTPs and security alerts delivered in seconds (p99 < 5 s to provider)
- Marketing can be delayed but must never slow critical traffic
- Absorb campaign spikes of 10× normal volume
- Stay within provider rate limits and per-user frequency caps
- Compliance: unsubscribe, consent and opt-in rules (CAN-SPAM, TCPA, GDPR)
| In scope | Out of scope (mention, then park) |
|---|---|
| Push, SMS, email and a simple in-app inbox | Building our own SMS carrier links or mail servers (we buy delivery from providers) |
| Preferences, templates, scheduling, digests | Campaign authoring UI, A/B testing and audience segmentation logic |
| Retries, deduplication, rate limits, tracking | ML ranking of which notification to send (we expose hooks for it) |
| Device token lifecycle and suppression lists | Chat-style real-time delivery to an open app (see Real-time Communication) |
2. Back-of-the-envelope estimation
Assume a consumer app with 100 million daily active users. Per day we send about 500 million push notifications, 100 million emails and 5 million SMS messages. Each delivery record (ids, channel, state, timestamps, provider id) is roughly 1 KB. See Back-of-the-Envelope Estimation for the method.
Average throughput
~7,000 /s
605M ÷ 86,400 s
Campaign peak
~70,000 /s
10× average for a few minutes
Delivery log
~55 TB
605 GB/day kept 90 days
SMS spend
~$40k /day
5M × ~$0.008 (US rates)
3. API design
POST /v1/notifications HTTP/1.1
Host: notify.internal
Content-Type: application/json
Idempotency-Key: otp-login-7f3a9c
{
"recipients": { "userIds": ["u_42"] },
"templateId": "login_otp",
"category": "security",
"priority": "critical",
"channels": ["sms"],
"data": { "code": "481 902", "ttlMinutes": 10 },
"sendAt": null
}
HTTP/1.1 202 Accepted
Content-Type: application/json
{ "notificationId": "ntf_8Hq2", "status": "queued" }| Field | Values | Why it exists |
|---|---|---|
recipients | userIds or a segmentId | A segment is expanded by a fan-out job, so one call can target millions of users |
category | security, transactional, social, marketing | Decides which opt-outs, quiet hours and consent rules apply |
priority | critical, high, normal, low | Selects the lane (topic and worker pool) |
channels | optional list | If omitted, the router picks channels from preferences and cost |
sendAt | ISO time, local:09:00 or null | Per-timezone sends spread a campaign across the day |
GET /v1/notifications/ntf_8Hq2
-> 200 { "deliveries": [{ "channel": "sms", "state": "delivered", "attempts": 1 }] }
PUT /v1/users/u_42/preferences
{ "marketing": { "email": true, "push": false }, "quietHours": "22:00-07:00", "timezone": "Europe/Berlin" }
-> 204 No Content
POST /v1/users/u_42/devices
{ "platform": "ios", "token": "a1b2...", "appVersion": "8.4.0" }
-> 201 Created- 202 Accepted, not 200: the API only promises that the request is durably queued. Delivery happens asynchronously and is observable through the status endpoint or a callback.
- Idempotency-Key is mandatory. Producers retry on timeouts, and without the key every retry would send another OTP. See Idempotency & Delivery Guarantees.
- Producers send data, not text. The platform owns templates, so copy changes and translations never require a deploy of the auth or order service.
4. Data model
| Table | Key | Important columns | Store |
|---|---|---|---|
notifications | notification_id, unique idempotency_key | producer, template_id, category, priority, data, send_at | Postgres (sharded by id) |
deliveries | (notification_id, user_id, channel, target) | state, attempts, lease_until, provider_message_id, timestamps | Cassandra or DynamoDB (write-heavy, TTL) |
user_preferences | (user_id, category, channel) | enabled, quiet_hours, timezone, locale | Postgres + Redis cache |
device_tokens | (user_id, token) | platform, app_version, last_seen_at | Postgres |
templates | (template_id, channel, locale, version) | subject, body, status (draft or live) | Postgres + in-process cache |
suppressions | (channel, address) | reason (hard bounce, spam complaint, SMS STOP) | Postgres + Redis set |
inbox_items | (user_id, created_at desc) | notification_id, rendered title/body, read_at | Cassandra or DynamoDB (one partition per user) |
The split follows the access patterns. Requests, preferences, tokens and templates are small, relational and need unique constraints (idempotency keys, one row per token), so a relational database fits. Deliveries and inbox items are append-heavy, read by a single key, and expire, which is exactly what a wide-column store with TTLs is built for. See SQL vs NoSQL Databases.
5. High-level architecture
The design is a pipeline of small stateless services connected by Kafka topics. The API validates and deduplicates, the router applies preferences and templates, and one topic per channel and priority feeds dedicated worker pools that talk to the providers. Press play on a flow to follow a message.
6. Deep dive: preferences, templates and localization
The preference matrix
Preferences are a matrix of category × channel, plus quiet hours and a timezone. The router evaluates them before rendering anything, so a user who opted out costs us almost nothing.
| Category | Push | SMS | Opt-out allowed | Quiet hours | |
|---|---|---|---|---|---|
security (OTP, new login) | on | on | on | No | Ignored |
transactional (order shipped) | on | on | off | Per channel | Ignored |
social (new follower) | on | digest | off | Yes | Respected |
marketing (promotions) | off | on | off | Yes; SMS needs explicit opt-in | Respected |
type Category = "security" | "transactional" | "social" | "marketing";
type Channel = "push" | "sms" | "email";
interface Prefs {
timezone: string; // IANA name, e.g. "Europe/Berlin"
quietHours?: { start: number; end: number }; // local hours, e.g. 22 -> 7
optOuts: Set<string>; // "marketing:sms", "social:push", ...
}
function localHour(timezone: string, now: Date): number {
const hour = new Intl.DateTimeFormat("en-US", {
timeZone: timezone,
hour: "numeric",
hourCycle: "h23",
}).format(now);
return Number(hour);
}
export function decide(
category: Category,
channel: Channel,
prefs: Prefs,
now: Date = new Date(),
): "send" | "drop" | "defer" {
if (category === "security") return "send"; // OTPs: no opt-out, no quiet hours
if (prefs.optOuts.has(`${category}:${channel}`)) return "drop";
if (category === "transactional") return "send"; // receipts ignore quiet hours
const q = prefs.quietHours;
if (q) {
const h = localHour(prefs.timezone, now);
const quiet = q.start < q.end ? h >= q.start && h < q.end : h >= q.start || h < q.end;
if (quiet) return "defer"; // reschedule for q.end local time
}
return "send";
}Templates and localization
Templates are keyed by (template_id, channel, locale, version). Each channel needs its own variant: push needs a 40-character title, SMS needs plain text, email needs a subject plus HTML and text bodies. Use ICU MessageFormat so translators can express plurals and dates correctly in every language.
{
"templateId": "order_shipped",
"channel": "push",
"locale": "en",
"version": 7,
"title": "Your order is on its way",
"body": "{itemCount, plural, one {# item} other {# items}} shipped. Arrives {eta, date, medium}."
}- Locale fallback: try
pt-BR, thenpt, then the defaulten. Never fail a delivery because one translation is missing. - Pin the version when a notification is accepted, so a template edited mid-campaign does not mix two versions in one send.
- SMS length depends on the alphabet: GSM-7 fits 160 characters per message (153 per part when concatenated), but any non-GSM character switches to UCS-2 with only 70 (67 per part). A Hindi or Chinese OTP can cost twice as much as an English one.
- Payload limits: APNs and FCM cap notification payloads at 4 KB, so long content becomes a short teaser plus a deep link.
7. Deep dive: retries, DLQs and no duplicate sends
Kafka and the providers give at-least-once delivery: a message can be processed twice after a crash, a rebalance or a retry. We turn that into effectively once by making every hop idempotent. Duplicates can enter at three places, and each needs its own guard.
| Where duplicates come from | Guard |
|---|---|
Producer retries POST /notifications after a timeout | Unique idempotency_key on notifications; replay returns the stored response |
| Kafka redelivers a message (consumer crashed before committing its offset) | Delivery state machine: a worker atomically claims pending → sending; sent is terminal |
| Router fans out the same notification twice | Deterministic delivery_id = hash(notification_id, user, channel, target) with a unique key |
Worker crashes after the provider accepted but before saving sent | Unavoidable tiny window. A lease on sending limits it; accept a rare duplicate for push and email, and use short OTP lifetimes |
claim(delivery_id) finds the delivery already sent and skips it. Then pick "Worker crashes after sending": SES takes no idempotency key, so a crash between SES accepting the email and mark_sent still sends it twice, the window this section calls unavoidable.Classify errors before retrying
| Response | Meaning | Action |
|---|---|---|
429 or throttling error | We exceeded the provider's rate | Retry with backoff; honor Retry-After; slow the lane down |
5xx or timeout | Provider-side transient failure | Retry with exponential backoff and jitter |
400 invalid payload | Our bug (bad template, oversized payload) | No retry; send to DLQ and alert |
APNs 410 or FCM UNREGISTERED | App uninstalled or token rotated | Delete the token; no retry |
| Email hard bounce or spam complaint | Address invalid or user objects | Add to suppression list |
| SMS to a landline or invalid number | Cannot be delivered | Mark failed; optionally fall back to email |
Retries must not block the main topic: a consumer that sleeps on one failing message stalls its whole partition. Instead, failed messages move to delay topics with increasing wait times, and finally to a dead-letter queue (DLQ). This is the pattern Uber described for reliable reprocessing on Kafka.
8. Deep dive: rate limits and priority lanes
Two different limits apply. Per-user caps protect people (and our SMS bill): no more than 3 marketing pushes a day, no more than 5 OTPs an hour. Per-provider quotas protect our sender reputation: every provider account has a maximum send rate, and exceeding it produces throttling errors or, for email, spam-folder placement. Both are token buckets in Redis shared by all workers. See Rate Limiting.
| Lane | Examples | Target latency | Preferences | Isolation |
|---|---|---|---|---|
critical | OTP, password reset, fraud alert | seconds | Bypassed | Own topic, own consumers, reserved provider quota |
high | Order shipped, payment receipt | < 1 minute | Channel opt-outs apply | Own topic |
normal | Likes, comments, mentions | minutes | Respected; eligible for digests | Own topic |
low | Marketing campaigns | hours | Respected; opt-in required | Own topic, smallest quota share |
9. Deep dive: scheduling, batching and digests
- 1
Store the send time
Scheduled deliveries are rows with
send_at. For 'every user at 9:00 local time', the fan-out job computes a differentsend_atper user from their timezone, which also spreads the load across 24+ hours. - 2
Claim due work safely
Schedulers poll an index on
(state, send_at)and claim rows withFOR UPDATE SKIP LOCKEDor a lease column. Queue delay features rarely suffice on their own (SQS caps delays at 15 minutes). - 3
Digest low-priority events
Instead of 20 'X liked your photo' pushes, buffer
socialevents per user for a window (say 30 minutes) and send one summary: 'Ana and 19 others liked your photo'. - 4
Collapse stale messages on the device
APNs
apns-collapse-idand FCMcollapse_keyreplace an older undelivered notification with the newest one, so a phone that was offline sees one live score update, not fifty. - 5
Batch provider calls
Bulk APIs cut overhead: the Firebase Admin SDK sends to up to 500 tokens per multicast call, and SES bulk templated email accepts up to 50 destinations per request.
10. Deep dive: tracking delivery and engagement
Each delivery moves through a small state machine. Providers report different subsets of these states, so the tracking service normalizes their webhooks into one event stream.
- queued → sending → sent
- Internal states.
sentmeans the provider accepted the message, not that a human saw it. - delivered
- SMS delivery receipts from the carrier (via Twilio status callbacks) and SES delivery events. APNs gives no delivery receipt, so for push the app's SDK reports receipt itself.
- opened / clicked
- Push opens are reported by the app. Email opens come from a tracking pixel (inflated by privacy features that prefetch images, so treat opens as approximate); clicks come from wrapped redirect links and are more reliable.
- bounced / complained / failed
- Terminal failures. Hard bounces and spam complaints feed the suppression list; mailbox providers expect complaint rates well under 0.3%.
11. Scaling, bottlenecks and failure handling
- Stateless everywhere: API, router and workers scale horizontally; autoscale workers on consumer lag per lane, not CPU.
- Partition by
user_id: keeps per-user ordering and lets one consumer own a user's caps and digest buffer. See Sharding & Partitioning. - Multiple providers per channel: for example Twilio plus a second SMS vendor, with a circuit breaker per provider. Fail over only on errors that prove the first provider did not accept the message, or you risk duplicates.
- Cache hot reads: preferences, templates and suppression lists are read on every message, so serve them from Redis or in-process caches with short TTLs. See Caching.
- Write-optimized delivery log: billions of status updates per month suit Cassandra or DynamoDB with a 90-day TTL; aggregate older data into analytics.
- Observability: per-lane lag, provider error rates, delivery and open rates, and cost per channel, with alerts on OTP latency. See Observability.
| Failure | What users would see | Mitigation |
|---|---|---|
| SMS provider outage | OTPs stop arriving | Circuit breaker opens; fail over to a second vendor for new deliveries only; offer email or authenticator fallback in the login UI |
| Kafka broker lost | Nothing, if replicated | Topics with replication factor 3 and min.insync.replicas=2; producers use acks=all |
| Redis (caps and quotas) down | Over-sending or stalls | Fail closed for SMS caps (cost and fraud risk), fail open with conservative local limits for push |
| Router bug renders a broken template | Garbled messages to millions | Template validation and preview at publish time, canary sends to a small percentage, a global kill switch per template |
| Campaign floods 50M messages | Slow likes and comments | Low lane has its own consumers and quota, so critical and high lanes keep their latency |
| Whole region down | Delayed notifications | Active-passive region with replicated topics; idempotency keys make replay after failover safe |
Implementation
Claims a delivery atomically, sends it, and routes failures to a delay topic or the DLQ. The store's `claim` is a conditional update, so redelivered messages are skipped.
import random
import time
from dataclasses import dataclass, replace
from typing import Any, Literal, Optional, Protocol
MAX_ATTEMPTS = 6
BASE_S = 1.0
CAP_S = 600.0
@dataclass(frozen=True)
class DeliveryMessage:
delivery_id: str # hash(notification_id, user_id, channel, target)
attempt: int
payload: dict[str, Any]
@dataclass(frozen=True)
class SendResult:
kind: Literal["ok", "retryable", "permanent"]
provider_message_id: Optional[str] = None
error: Optional[str] = None
retry_after_s: float = 0.0
class DeliveryStore(Protocol):
def claim(self, delivery_id: str, lease_s: float) -> bool: ...
def mark_sent(self, delivery_id: str, provider_message_id: str) -> None: ...
def mark_retrying(self, delivery_id: str, error: str) -> None: ...
def mark_failed(self, delivery_id: str, error: str) -> None: ...
class Bus(Protocol):
def publish(self, topic: str, msg: DeliveryMessage, not_before: Optional[float] = None) -> None: ...
def backoff_s(attempt: int) -> float:
return random.uniform(0, min(CAP_S, BASE_S * 2 ** attempt)) # full jitter
def handle(msg: DeliveryMessage, store: DeliveryStore, bus: Bus, send) -> None:
if not store.claim(msg.delivery_id, lease_s=120):
return # already sent, failed, or owned by another worker
result: SendResult = send(msg.payload)
if result.kind == "ok":
store.mark_sent(msg.delivery_id, result.provider_message_id)
elif result.kind == "permanent" or msg.attempt >= MAX_ATTEMPTS:
store.mark_failed(msg.delivery_id, result.error or "unknown")
bus.publish("notifications.dlq", msg)
else:
store.mark_retrying(msg.delivery_id, result.error or "unknown")
delay = max(result.retry_after_s, backoff_s(msg.attempt))
bus.publish("notifications.retry", replace(msg, attempt=msg.attempt + 1),
not_before=time.time() + delay)Key takeaways
- Accept requests with
202 Acceptedand an idempotency key; everything after the API is asynchronous and queue-driven. - One topic and consumer pool per channel and priority keeps OTPs fast no matter how large a campaign is.
- Delivery is at-least-once; make every hop idempotent (request key, deterministic delivery id, atomic claim) to get effectively-once sends.
- Classify provider errors: retry transient ones with backoff and jitter via delay topics, never retry permanent ones, and park the rest in a DLQ.
- Apply preferences, suppressions and per-user caps in the router, before any money is spent on a provider call.
sentonly means a provider accepted the message; delivery and engagement come back later through webhooks and app events.
Common pitfalls
- Putting OTPs and marketing on one queue, so a campaign backlog delays login codes by minutes.
- Retrying inside the consumer loop with
sleep, which stalls the whole Kafka partition behind one bad message. - Failing over to a second provider after a timeout, which can deliver the same SMS twice because the first provider may have accepted it.
- Ignoring dead device tokens, bounces and complaints; providers throttle or block senders with poor hygiene.
- No per-user cap on OTP sends, leaving the system open to SMS pumping fraud and a huge bill.
Interview tips
- Separate transactional from promotional traffic early; it justifies priority lanes, different consent rules and different latency targets.
- Walk through one OTP end to end, naming the idempotency guard at each hop, then explain what happens when the SMS provider is down.
- Quantify cost: SMS at roughly $0.008 versus nearly free push explains channel selection and why rate limits protect the business, not just users.
Real-world applications
- Uber published its Kafka pattern of tiered retry topics plus a dead-letter queue, the same ladder used in this design.
- LinkedIn has described a central service (Air Traffic Controller) that decides whether, when and on which channel to notify a member, to avoid over-notifying.
- Netflix has described RENO, an event-driven notification system that pushes updates to devices with priority-based queues.
- Slack shared a well-known flowchart for deciding whether a message should trigger a notification, a reminder that preference logic is product logic.
- Managed platforms such as Amazon SNS, AWS End User Messaging (which carries on Amazon Pinpoint's SMS and push channels after Pinpoint's end of support in October 2026), Firebase Cloud Messaging, Twilio and SendGrid provide the provider layer that a platform like this wraps.
Test yourself
Why do notification platforms use separate topics and consumer pools per priority instead of one queue with a priority field?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.