Skip to content

Lesson 28 of 38Case studies

Design a Notification System

Design a multi-channel notification service with preferences, templates, per-channel queues, retries, dedupe, and rate limits.

18 min read0/4 questions

Every product eventually sends "your order shipped", "Sam replied to you", and "your password was changed", through push, email, and SMS. Done badly, users get the same alert three times at 3 a.m. and switch notifications off for good. Done well, it is a shared platform that every other team calls with one line of code. Interviewers like it because it is all about queues, retries, and respecting the user.

Requirements

Functional

  • Other services send a notification for a user with one API call: order_shipped for user 42.
  • Channels: push (iOS and Android), email, SMS, plus an in-app inbox.
  • Users control which notification types they get on which channel, and quiet hours.
  • Templates per notification type and language.
  • Scheduled sends ("remind me tomorrow at 9") and digests.

Non-functional

  • At-least-once delivery for important messages (security alerts, receipts), and no duplicates that the user can see.
  • Soft real time: most notifications go out within seconds; marketing can take minutes.
  • A slow or broken provider (say, the SMS vendor) must not delay other channels.
  • Protect users from spam: per-user rate limits.

Out of scope: building our own email servers or SMS carriers (we use providers like Amazon SES and Twilio), campaign design tools, A/B testing.

Back-of-the-envelope numbers

QuantityMathResult
Notifications1 billion a day / 86,400about 11,500/s average
Peaka marketing blast to 50M users in 10 minutesabout 83,000/s
Split70% push, 25% email, 5% SMSSMS is the smallest and by far the most expensive
Notification log1B × 300 bytesabout 300 GB a day (keep 30–90 days)

Peaks are spiky and driven by campaigns, so the system must buffer. That points straight at queues.

API

POST /v1/notifications
Idempotency-Key: order-8812-shipped
{
  "user_id": "u_42",
  "type": "order_shipped",
  "data": { "order_id": "o_8812", "eta": "Thursday" },
  "channels": ["push", "email"],        // optional; defaults come from the type
  "send_at": null,                      // or an ISO time for scheduling
  "priority": "high"
}
202 Accepted  { "notification_id": "n_5512" }
 
GET  /v1/users/u_42/preferences
PUT  /v1/users/u_42/preferences  { "order_shipped": { "push": true, "email": false }, "quiet_hours": ["22:00", "07:00"] }

202 Accepted means "queued", not "delivered". The caller never waits for Apple or Twilio.

Data model

  • preferences: (user_id, type, channel) → enabled, plus quiet hours and time zone. Read on every send, so cached.
  • devices: (user_id, device_token, platform, last_seen). One user may have several phones.
  • templates: (type, channel, locale, version) → subject, body with placeholders like {{eta}}.
  • notifications log: (notification_id, user_id, type, channel, status, attempts, provider_id, timestamps). Status goes queued → sent → delivered (or failed), and powers the in-app inbox and debugging.

High-level design

Notification service
Queue + workers per channelProvidersServices: orders, chatServicesorders, chatRedis: dedupe, limitsRedisdedupe, limitsScheduler: send_atSchedulersend_atNotify APINotify APIPreferencesPreferencesTemplatesTemplatesPush queuePush queueEmail queueEmail queueSMS queueSMS queuePush senderPush senderEmail senderEmail senderSMS senderSMS senderAPNs / FCMAPNs / FCMEmail (SES)Email (SES)SMS vendorSMS vendoreventdue

The order service calls POST /v1/notifications with type order_shipped, the user, the data, and an idempotency key.

1/7
Quick check
Why a separate queue and worker pool per channel, instead of one queue for everything?
Need a nudge? A hint rules out a wrong answer.

The pipeline for one notification

Every notification passes through the same stages. The cheap checks come first, so we never render or send something we are about to drop.

Notification pipeline
  1. Validate requestknown type, user exists
  2. Dedupeidempotency key seen? drop
  3. Preferences + quiet hoursopted out? delay or drop
  4. Rate limit per usermax N per hour per channel
  5. Render templatelocale, placeholders
  6. Enqueue per channelpush / email / SMS / in-app
  7. Send with retriesbackoff, dead-letter queue
  8. Track statussent, delivered, opened, failed

Reject bad input and duplicates first. A retried order_shipped with the same key stops here.

1/4

Deep dive 1: retries with exponential backoff

Providers fail in two ways. Retryable errors (timeouts, 429 Too Many Requests, 5xx) might work later. Permanent errors (invalid phone number, an uninstalled app's dead device token) never will: retrying them wastes money, so mark them failed and clean up (delete the dead token).

For retryable errors, wait longer each time: 1 s, 2 s, 4 s, 8 s, up to a cap. That is exponential backoff. Add jitter (randomness) so 10,000 messages that failed in the same second do not all retry in the same second and knock the provider over again. After a maximum number of attempts, the message goes to a dead-letter queue (DLQ) for inspection.

Pythonbackoff.py
import random random.seed(7) def backoff_delays(attempts: int, base: float = 1.0, cap: float = 60.0) -> list[float]: # "Full jitter": pick a random delay between 0 and the exponential ceiling. return [round(random.uniform(0, min(cap, base * 2 ** n)), 2) for n in range(attempts)] def send_with_retries(provider_results: list[str], max_attempts: int = 5) -> str: delays = backoff_delays(max_attempts) for attempt, result in enumerate(provider_results[:max_attempts], start=1): if result == "ok": return f"delivered on attempt {attempt}" if result == "invalid_token": return "permanent failure: remove device token, no retry" print(f" attempt {attempt}: {result}, waiting {delays[attempt - 1]}s") return "gave up: moved to dead-letter queue" print(send_with_retries(["503", "timeout", "ok"]))print(send_with_retries(["invalid_token"]))print(send_with_retries(["503"] * 6))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
The SMS vendor returns 400 Invalid phone number for a user. What should the sender do?
Need a nudge? A hint rules out a wrong answer.

Deep dive 2: dedupe, rate limits, and quiet hours

Duplicates come from everywhere: a caller retries after a timeout, a queue redelivers a message (queues are at-least-once), a worker crashes after sending but before acknowledging. Defences at two levels:

  • At the API: an idempotency key per logical notification (order-8812-shipped), stored in Redis with SET NX and a 24-hour expiry. A second request with the same key is dropped.
  • At the sender: before calling the provider, record (notification_id, channel) as sent. A redelivered queue message finds it and skips.

Rate limits protect users: at most, say, 5 push notifications per hour per user, except critical ones. Quiet hours delay non-urgent sends to the morning, in the user's time zone.

TypeScriptshould-send.ts
type Req = { key: string; userId: string; critical: boolean; hourLocal: number }; const seen = new Set<string>();const sentThisHour = new Map<string, number>();const LIMIT = 3; function decide(r: Req): string { if (seen.has(r.key)) return "drop: duplicate"; seen.add(r.key); if (!r.critical && (r.hourLocal >= 22 || r.hourLocal < 7)) return "delay: quiet hours, send at 07:00"; const n = sentThisHour.get(r.userId) ?? 0; if (!r.critical && n >= LIMIT) return "drop: rate limited"; sentThisHour.set(r.userId, n + 1); return "send";} const reqs: Req[] = [ { key: "a1", userId: "u42", critical: false, hourLocal: 14 }, { key: "a1", userId: "u42", critical: false, hourLocal: 14 }, { key: "a2", userId: "u42", critical: false, hourLocal: 23 }, { key: "a3", userId: "u42", critical: false, hourLocal: 15 }, { key: "a4", userId: "u42", critical: false, hourLocal: 15 }, { key: "a5", userId: "u42", critical: false, hourLocal: 15 }, { key: "a6", userId: "u42", critical: true, hourLocal: 3 },];for (const r of reqs) console.log(r.key, "->", decide(r));
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

What does this print?

const LIMIT = 2;
let sent = 0;
const out = [];
for (const id of ["n1", "n2", "n3"]) {
if (sent >= LIMIT) { out.push("drop"); continue; }
sent++;
out.push("send");
}
console.log(out.join(" "));
Need a nudge? Hints walk you through it.

Deep dive 3: priorities and scheduling

A password-reset email must not wait behind 50 million marketing emails. Give each channel two queues: high priority (transactional) and low (marketing), with most workers reading high first. Marketing blasts are also throttled at the source so they never exceed what providers allow.

For scheduling, store future notifications in a table indexed by send_at. A scheduler polls WHERE send_at <= now() AND status = 'scheduled' every few seconds, claims rows (FOR UPDATE SKIP LOCKED lets several scheduler instances share work without double-sending), and feeds them into the normal pipeline. Digests ("5 new replies today") are a scheduled job that groups a user's pending low-priority items into one message.

Put it in order5 steps

Order the checks for an incoming notification, cheapest and most decisive first.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Bottlenecks, failures, and 10x scale

  • Provider outage. Its queue grows; nothing else is affected. Alert on queue age. For critical messages, fail over to a second provider (two SMS vendors, two email providers).
  • Provider rate limits. APNs, SES, and SMS vendors cap your send rate. Workers use a token bucket per provider so they never exceed it.
  • Dead device tokens. Uninstalled apps return "unregistered"; delete those tokens or you waste work on every send.
  • Campaign spikes. Queues absorb the burst; autoscale workers on queue depth.
  • 10x (10 billion a day): partition queues (Kafka partitions by user_id keep a user's notifications ordered), scale stateless workers horizontally, shard the notification log by user_id and expire old rows. Preferences stay in a cache because they are read on every send.
Key terms
exponential backoff
Waiting twice as long after each failed attempt, up to a cap, so a struggling service can recover.
jitter
Randomness added to retry delays so many clients do not retry at the same moment.
dead-letter queue
Where messages go after exhausting their retries, for humans or tools to inspect.
bulkhead
Isolating resources (a queue and workers per channel) so one failure cannot spread to the rest.
at-least-once delivery
Messages are retried until acknowledged, so they may arrive more than once; consumers must dedupe.