1. Functional requirements
- Send a notification to a user over push, SMS or email through one API.
- Set channel preferences per notification type, including opt-out.
- Query a notification’s delivery status.
Below the line: templates and localization, scheduling, digests, in-app inbox, campaign tooling.
Scale: 10M notifications a day, about 120/s; bursts of 50K/s when one service fans out to every user; providers accept about 1K sends/s each. Throughput is bursty, not large. The design is driven by never losing a notification and never sending one twice while a provider rate-limits or goes down.
2. Non-functional requirements
- No notification lost: at-least-once to the provider
- No duplicate sends: idempotent end to end
- Bursts of 50K/s absorbed without delaying time-sensitive sends
- Preferences and opt-outs always respected
3. Core entities
- Users
- Devices
- Preferences
- Notifications
- Deliveries: queued → sent → delivered | failed
4. API routes
Auth is a header on all three: service auth on send and status, user auth on preferences.
Send
POST /notifications Idempotency-Key header, one per event
body: type, userIds, payload, channels, priority
returns: notificationId
Status
GET /notifications/:notificationId
returns: deliveries[] with userId, channel, status
Preferences
PUT /users/:userId/preferences
body: type, push, sms, email, quietHours
returns: ok
5. High-level design
The simplest system that satisfies the three routes. Two kinds of client, one gateway, one service, one database, and the providers called in the request. The deep dives change this picture.
Boxes, drawing order: calling services and the user app · gateway · notification service · Postgres · push, SMS and email providers on the right.
Data model:
Device userId, platform, pushToken
Preference userId, type, push, sms, email, quietHours
Notification id, type, payload, idempotencyKey
Delivery id, notificationId, userId, channel, status, attempts
Postgres, one primary: one transaction for the notification, its deliveries and the outbox row; unique constraints for the idempotency key and for (notificationId, userId, channel). The burst lands in the queue, not in the database.
6. Deep dives
Order in the room: 6.1 must · 6.3 if time · 6.2 and 6.4 one line each, only if asked. Each deep dive opens with three spoken sentences: Problem, Pick, Cost. Everything under them is what you say when the interviewer digs.
6.1 Never lose a send: persist first, send from a queue
Problem. Providers are called inside the request: a crash after the insert loses the notification, a slow provider fails the caller, and a caller retry sends twice. Pick. Commit the notification, its deliveries and an outbox row first, return 202, then send from a Kafka topic per channel with retries and a dead-letter queue. Cost. A 202 and asynchronous status instead of an inline result, plus a relay and workers to operate. Rejected: calling providers in the request, because a commit can never lose a send and a request can.
Draw: an outbox beside Postgres, a relay, three topics, channel workers in front of the providers.
Flow
- One transaction: insert
notification, onedeliveryper user per channel asqueued, and an outbox row. Return202withnotificationId. - A relay publishes each delivery to Kafka, topics
push,sms,email, keyuserIdso one user’s messages stay in order. - Channel workers consume, call the provider, set
sentandproviderMessageId. A failure goes to a retry topic with backoff, 5 tries, thenfailedand the DLQ, which alerts. - Provider webhooks (delivered, bounced) move the delivery to
deliveredorfailed.
Follow up: a worker crashes after the provider accepted the send but before it marked the delivery sent. Does the user get it twice?
Answer: Kafka redelivers the message to another worker, so the worker has to be idempotent. It claims the delivery first with a conditional update queued → sending and passes deliveryId to the provider as its idempotency key; APNs collapse ids, Twilio and SES accept client reference ids. The replayed message finds the row in sending with a fresh timestamp and skips it. If the claim is older than a minute it resends with the same key and the provider drops the duplicate. Worst case is one repeat at a provider that does not dedupe, never a lost send.
6.2 No duplicates: one idempotency key end to end
Problem. Callers retry on timeouts, Kafka is at-least-once, and a user with three devices could get the same push three times.
Pick. The caller’s Idempotency-Key checked in Redis at the edge with SET NX EX 86400, unique indexes in Postgres on the key and on (notificationId, userId, channel) as the backstop, and workers that dedupe on deliveryId.
Cost. One Redis round trip per send and a 24-hour key window. A race past Redis dies on the index, so correctness never depends on the cache.
6.3 Bursts and provider failures: workers sized to the provider
Problem. A 50K/s burst hits providers that accept about 1K/s, push tokens expire, and one provider outage would stall every send on that channel.
Pick. A worker pool per topic sized to its provider, a token bucket per provider in Redis, a second provider per channel behind a circuit breaker, and push-high and sms-high topics so security codes never wait behind a marketing blast.
Cost. More topics and a fallback contract per channel to operate, and a failed-over send may arrive from a different sender id. Rejected: one queue for everything, because a slow SMS provider must not delay push.
Draw: a token bucket and a breaker between each worker pool and its provider, a second provider box per channel, a high-priority topic beside each channel topic.
Flow
- Before each send the worker increments
rate:{provider}:{sec}; over the limit it waits for the next second, the queue holds the rest. - Push workers look up the user’s device tokens;
Unregisteredfrom APNs or FCM deletes the device row. - A breaker per provider opens at 50% failures over 30 s and routes sends to the fallback (Twilio → SNS, SES → SendGrid); a probe every minute closes it again.
push-high,sms-hightopics with their own workers carry security codes, so a code never waits behind a marketing blast.
Follow up: the SMS provider is down for an hour. What does the user experience?
Answer: The breaker opens within a minute and SMS traffic fails over to the second provider, so most users notice nothing. Sends that cannot fail over retry with backoff and land in the DLQ after five tries; consumer lag and DLQ depth are the two alerts. Nothing is lost, because every delivery is a row in Postgres and a message in Kafka. Time-sensitive codes also fall back across channels, push after SMS, once a short deadline passes. When the provider recovers the probe closes the breaker and the on-call replays the DLQ.
6.4 Preferences respected: filter before the queue
Problem. Preferences are read from Postgres per user, so a 1M-user fanout is 1M queries, and nothing enforces quiet hours or a per-user cap.
Pick. A preference filter in front of the outbox reading a write-through Redis preference cache and a per-user daily counter; a delivery that would break a preference is written as suppressed and never enqueued.
Cost. A cache that can lag up to a day, bounded by write-through, so opt-outs for SMS and email are re-checked in the worker before sending.
Final design
Trade-offs, the two to say:
- Outbox and Kafka over calling providers in the request: a commit can never lose a send; the cost is a 202 and asynchronous status.
- At-least-once with idempotent workers over exactly-once: exactly-once across Kafka and a third party does not exist; the cost is a claim step and provider idempotency keys.
Study only, not for the room: full flows for 6.2 and 6.4.
6.2 flow
POST /notifications→SET idem:{key} NX EX 86400in Redis. Already set → return the storednotificationId, nothing written.- Insert with
notification.idempotencyKeyunique; a duplicate insert fails and returns the existing id. - Deliveries are unique on
(notificationId, userId, channel), so a user with three devices gets one push delivery that fans out to the devices. - Workers dedupe on
deliveryId(6.1).
6.4 flow
- Preferences live in Redis as
prefs:{userId}, write-through onPUT /preferences, TTL 1 day; a fanout reads them pipelined. - Per-user cap:
INCR ratelimit:{userId}:{type}:{day}; over the cap (say 5 marketing a day, none for transactional) the delivery is written assuppressedfor the audit trail and not enqueued. - Quiet hours: non-urgent deliveries get
sendAt= end of the window, released by a scheduler into the normal topics. - Opt-out for SMS and email is re-checked in the worker before sending, since a stale cache must never cause a send.