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.
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_shippedfor 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
| Quantity | Math | Result |
|---|---|---|
| Notifications | 1 billion a day / 86,400 | about 11,500/s average |
| Peak | a marketing blast to 50M users in 10 minutes | about 83,000/s |
| Split | 70% push, 25% email, 5% SMS | SMS is the smallest and by far the most expensive |
| Notification log | 1B × 300 bytes | about 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, bodywith placeholders like{{eta}}. - notifications log:
(notification_id, user_id, type, channel, status, attempts, provider_id, timestamps). Status goesqueued → sent → delivered(orfailed), and powers the in-app inbox and debugging.
High-level design
The order service calls POST /v1/notifications with type order_shipped, the user, the data, and an idempotency key.
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.
Reject bad input and duplicates first. A retried order_shipped with the same key stops here.
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.
Press Run (⌘ Enter) to see what happens.400 Invalid phone number for a user. What should the sender do?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 withSET NXand 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.
Press Run (⌘ Enter) to see what happens.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(" "));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.
Order the checks for an incoming notification, cheapest and most decisive first.
- Tap the steps below in the right order.
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_idkeep a user's notifications ordered), scale stateless workers horizontally, shard the notification log byuser_idand expire old rows. Preferences stay in a cache because they are read on every send.
- 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.