Case studies

Design a notification service

One internal service that sends push, email and SMS for every team. The design work is in isolating channels, never sending twice, respecting user preferences and surviving provider failures.

Case study24 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A growing product sends notifications from everywhere. The order service calls an email provider when a parcel ships. The login service calls an SMS provider for one-time codes. The marketing team has a script that sends push notifications. Each integration was written separately, and each handles failure differently.

The problems arrive together. A user who turned off marketing email still gets marketing push, because preferences live in three places. A retry bug sends the same “your order has shipped” email four times. A promotion goes out at 3 am to users in another time zone. The SMS provider has a slow hour and the login service, which calls it synchronously, starts timing out for everyone. Nobody can answer “did this user get the message?”.

The fix is one notification service that every team calls. It looks like plumbing, which is why it is a good interview question: the interviewer finds out whether you can design an asynchronous pipeline that is reliable when third parties are not, and whether you take duplicates and user trust seriously.

Requirements

Functional

  • Internal services request a notification for a user by naming a template and supplying data.
  • Deliver by push (APNs for Apple devices, FCM for Android), email and SMS, through external providers.
  • Respect user preferences per category and channel, and quiet hours.
  • Render templates per channel and language.
  • Never deliver the same notification twice.
  • Limit how many notifications a user receives.
  • Track the status of every notification.

Out of scope unless asked: an in-app inbox, campaign audience selection, and building our own mail or SMS infrastructure.

Non-functional

  • Latency: high-priority notifications reach the provider within about 2 seconds at p99. Marketing can take minutes.
  • Reliability: an accepted notification is not lost, even if a provider is down for an hour.
  • Isolation: one channel, provider or caller failing must not affect the others.
  • Scale: 100 million users, 500 million notifications a day, with large bursts.
  • Auditability: every attempt is recorded.

Capacity estimates

Quantity Working Result
Daily volume 400M push + 90M email + 10M SMS 500 million
Average rate 500M / 86,400 about 5,800 per second
Campaign burst 50M users in 10 minutes about 83,000 per second
Delivery log 500M x 500 bytes, kept 30 days 250 GB a day, 7.5 TB
Device tokens 100M users x 1.5 devices x 200 bytes 30 GB
SMS cost 10M x about 1 US cent (varies widely by country) about $100,000 a day

The average rate is modest. The shape is the problem: a campaign is more than ten times the average, and providers will not accept it that fast anyway. So the system needs queues that absorb bursts and drain at the rate providers allow, and urgent traffic needs a path that a burst cannot block. The SMS line also tells you something: SMS is the expensive channel, so it is reserved for messages that justify the cost.

API

POST /v1/notifications
Authorization: Bearer <service-token>
Idempotency-Key: order-8812-shipped

{ "user_id": "u_123", "template": "order_shipped", "data": { "order_id": "8812", "eta": "Tuesday" },
  "category": "transactional", "priority": "normal", "ttl_seconds": 86400 }

202 Accepted
{ "notification_id": "n_01HV..." }

The response is 202 because nothing has been sent yet. The service has recorded the request and will deliver it. Callers do not choose channels by default; the router does, from the category and the user’s preferences.

Other endpoints: GET /v1/notifications/{id} returns status per channel, PUT /v1/users/{id}/preferences updates settings, POST /v1/devices registers a push token, and POST /v1/webhooks/{provider} receives delivery events from providers.

Data model

Table Key Contents
notifications notification_id user, template, data, category, priority, idempotency key, deadline
deliveries notification_id, channel, address status, attempts, provider message id, timestamps
device_tokens user_id, device_id platform, token, last seen
preferences user_id, category, channel enabled, quiet hours, time zone, language
templates template id, channel, language, version subject and body with placeholders

Preferences, tokens and templates are small and read on every notification, so they sit in a relational store behind a cache. Notifications and deliveries are a high-volume, append-mostly log read by id. A wide-column store with a 30-day TTL fits, as does a partitioned relational table at lower volume.

High-level architecture

Notification service reference architecture15 components: Internal services, Notification API, Preference store, Intake queue, Redis, Router workers, Push queue, Email queue, SMS queue, Delivery log, Channel workers, Dead-letter queue, APNs and FCM, Email provider, SMS provider. Connections: Internal services to Notification API; Notification API to Redis (idempotency key); Notification API to Intake queue (enqueue); Intake queue to Router workers; Router workers to Preference store (prefs, template); Router workers to Redis (per-user limit); Router workers to Push queue; Router workers to Email queue; Router workers to SMS queue; Push queue to Channel workers; Email queue to Channel workers; SMS queue to Channel workers; Channel workers to Delivery log; Channel workers to Dead-letter queue; Channel workers to APNs and FCM; Channel workers to Email provider; Channel workers to SMS provider.Internalservicesorders, auth, marketingNotificationAPIPreferencestoreprefs, tokens, templatesIntake queueRedisidempotency, rate limitsRouter workersprefs, limits, renderPush queuepriority lanesEmail queuepriority lanesSMS queuepriority lanesDelivery logstatus per attemptChannel workersone pool per channelDead-letterqueueAPNs and FCMEmail providerSMS provideridempotency keyenqueueprefs, templateper-user limit
Notification service reference architecture

Accept. The API authenticates the caller, validates the template and data, and claims the idempotency key in Redis. It writes the notification and puts it on the intake queue, then returns 202.

Route. Router workers load the user’s preferences and addresses, drop channels the user has turned off, and check the per-user frequency cap. They render the template for each remaining channel and place one message per channel on that channel’s queue, in the lane for its priority.

Send. Each channel has its own worker pool. A worker takes a message, checks it has not already been sent, calls the provider, and records the outcome in the delivery log. Failures are retried with backoff. After the final attempt the message goes to the dead-letter queue.

Track. Providers report later events (delivered, bounced, complained) to a webhook endpoint on the API, which updates the delivery log.

Deep dives

Isolating channels and protecting priority

A queue per channel. APNs, an email provider and an SMS provider have different latencies, different rate limits and unrelated outages. If all three shared one queue, a stalled SMS provider would fill it with messages that cannot move, and push would wait behind them. Separate queues and worker pools are bulkheads: a backlog stays inside its channel.

Priority lanes. Within a channel, a login code and a discount offer are not equal. A single queue with a priority field does not work well, because a worker that is busy with a batch of bulk sends is busy whatever arrives next, and logs such as Kafka have no priority at all. Use a separate queue per priority level, with workers reserved for the high lane and a reserved share of the provider’s rate limit. A 50-million-message campaign then fills the bulk lane while codes pass in the other.

Provider limits. Providers throttle. Workers pace themselves with a token bucket per provider (rate limiting) and treat a 429 as an instruction to slow down, not a failure to retry at once.

Limits per user. A counter in Redis per user, category and time window enforces caps such as “at most three marketing pushes a day”. Over the cap, a message is dropped or folded into a digest. Security and transactional categories are exempt. Quiet hours are handled the same way: the router computes the next allowed time in the user’s time zone and schedules the message for then.

Check late. Preferences are read in the router, not when a campaign is created. A user who unsubscribed five minutes ago should not receive a campaign that was scheduled yesterday.

Never sending twice

Duplicates appear at every hop where something can be retried:

  • The caller times out waiting for the API and sends the request again.
  • A queue redelivers a message because a worker crashed before acknowledging it. Queues give at-least-once delivery.
  • A worker’s call to a provider times out although the provider accepted it, and the worker retries.

Each needs its own defence.

At the API. The caller supplies an idempotency key derived from the business event, such as order-8812-shipped. The API claims it with an atomic set-if-absent in Redis, with a TTL of a day or more, and a unique constraint in the notification store backs that up. A repeat returns the original notification_id.

In the worker. Before calling the provider, the worker moves the delivery row from queued to sending with a conditional update. If the row is already sent, the message is a redelivery and is acknowledged without sending.

At the provider. One gap remains. If the worker crashes after the provider accepted the message and before the row is marked sent, the retry sends again. The provider call and the database write cannot be made atomic. For push, close most of the gap with a collapse identifier (apns-collapse-id on APNs, collapse_key on FCM), so that a second copy replaces the first on the device. Some email and SMS provider APIs accept an idempotency key of their own.

Where no such feature exists, choose which failure you prefer, per category. For a login code, send again: two codes are harmless and none locks the user out. For marketing, do not retry an ambiguous timeout: a missed promotion costs less than an annoyed user.

Retries, dead letters and tracking

Classify the error first. A timeout, a 429 or a 5xx is transient: retry with exponential backoff and jitter (retries and timeouts). An invalid device token, a hard-bounced address or a malformed phone number is permanent. Retrying cannot help, so mark the delivery failed and remove or suppress the address. APNs signals a dead token with 410 and the reason Unregistered, and FCM returns UNREGISTERED.

Retries have a deadline. Every notification carries a time to live. A login code is useless after a few minutes and a delivery update after a day. When the deadline passes, stop.

Dead-letter queue. A message that fails for a reason nobody anticipated, such as a template that cannot render, goes to a dead-letter queue after a few attempts. Alert on its depth. Once the cause is fixed, the messages that are still within their deadline can be replayed.

Sent is not delivered. A success response from a provider means it accepted the request. Whether the user saw anything is learned later, if at all. Email providers send webhooks for delivery, bounces and spam complaints. SMS providers pass on carrier delivery receipts, which are not available on every route. Push providers confirm acceptance only, so the app itself must report that a notification arrived or was opened. The delivery log records each state as a separate event.

Close the loop. Bounces and complaints feed a suppression list that the router checks. Continuing to mail addresses that bounce or complain damages sender reputation, and mailbox providers respond by sending more of your mail to spam.

Bottlenecks and failure modes

  • Provider outage. The channel’s queue grows. A circuit breaker stops workers hammering a dead endpoint. For SMS and email, fail over to a second provider. Messages past their deadline are expired.
  • Campaign burst. The bulk lane backs up by design. Watch queue age per lane, not total depth: the high lane’s oldest message should be under a second old.
  • Redis lost. Idempotency keys and counters vanish. The unique constraint in the notification store still stops duplicate accepts. Frequency caps should fail open for transactional messages and closed for marketing.
  • Stale device tokens. Tokens die when apps are uninstalled. Without clean-up, a growing share of push calls is wasted.
  • Quiet hours ending. Everything held overnight is released at 08:00 local time. Spread the release over several minutes.
  • One noisy caller. A bug in one service floods the API. Rate limit per calling service at the API so others are unaffected.
  • Preference store slow. The router reads it for every notification. Cache preferences for a short time, and accept that an opt-out can take a minute to apply.

Trade-offs

Decision Chosen Alternative Why
API style Asynchronous, 202 Synchronous send Callers are isolated from providers; status must be looked up later
Queues Per channel and priority One shared queue Failures and bursts stay contained; more queues to operate
Delivery guarantee At least once with deduplication At most once Nothing accepted is lost; a rare duplicate is possible
Rendering Templates inside the service Callers send final text Consistent, localised and changeable centrally; the service owns more
Preference check At routing time At request time Respects recent changes; one more read per notification

45-minute interview script

A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.

  1. 0:00 to 5:00

    Requirements 5 min

    Ask which channels, who the callers are, and whether traffic is transactional, marketing or both. Confirm preferences, templates and delivery tracking. Agree that duplicates and late one-time codes are the failures that matter most.

  2. 5:00 to 9:00

    Capacity estimates 4 min

    Derive the average rate, then a campaign burst, and show that the burst is more than ten times the average. Size the delivery log. Mention SMS cost.

  3. 9:00 to 13:00

    API 4 min

    One send endpoint that takes a template id and data, an idempotency key, a category and a priority, and returns 202. Add status lookup, preferences and provider webhooks.

  4. 13:00 to 17:00

    Data model 4 min

    Notifications, one delivery row per channel attempt, device tokens, preferences and versioned templates. Say which are relational and which are a high-volume log with a TTL.

  5. 17:00 to 25:00

    High-level design 8 min

    Draw accept, route, send, track. API and intake queue, router workers, a queue per channel, worker pools, the three kinds of provider, delivery log and dead-letter queue. Narrate one order-shipped notification.

  6. 25:00 to 32:00

    Deep dive: channel isolation and priority 7 min

    Why a queue per channel, why priority needs separate lanes with their own workers, provider rate limits with a token bucket, per-user frequency caps and quiet hours.

  7. 32:00 to 38:00

    Deep dive: duplicates 6 min

    List where duplicates come from, then the layers that stop them. Idempotency key at the API, a send-once check in the worker, collapse identifiers at the provider. Be honest about the gap that remains.

  8. 38:00 to 43:00

    Retries, tracking and failure modes 5 min

    Transient against permanent errors, backoff with a deadline, dead-letter queue, provider failover. Sent is not delivered. Feedback from bounces and invalid tokens.

  9. 43:00 to 45:00

    Wrap-up 2 min

    Summarise in three sentences and name the next features, such as digests or an in-app inbox.

Sketch this design on the whiteboard Run it as a timed mock

Key takeaways

  • Accept fast and send later. The API validates, records and enqueues, then returns 202. Everything slow happens behind queues.
  • Give each channel its own queue and workers, so a slow SMS provider cannot delay push or email.
  • Priority needs separate lanes with reserved workers. A one-time code must never wait behind a 50-million-message campaign.
  • Duplicates come from retries at every hop. Stop them with an idempotency key at the API, a send-once check in the worker, and collapse identifiers at the provider.
  • Retry transient errors with backoff until the notification's deadline. Never retry permanent errors, and remove invalid tokens and bounced addresses.
  • A provider accepting a message is not delivery. Track states separately and feed bounces and complaints back into a suppression list.
  • Check preferences and frequency caps as late as possible, at routing time, so a setting changed a minute ago is respected.

Check yourself

1. A marketing campaign to 50 million users is enqueued at 09:00. Login codes sent by SMS start arriving minutes late. What is the most likely design flaw?
2. A push worker calls APNs, the request times out, and the worker retries. The user receives two identical notifications. Which measure makes the device show only one?
3. APNs responds 410 Unregistered for a device token. What should the worker do?
4. Why does the send API accept a template id and data instead of the final message text?
5. A one-time login code is still in the retry queue ten minutes after it was requested. What should happen?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What are the four stages of a notification pipeline?

Accept (validate, deduplicate, enqueue), route (preferences, limits, template rendering, channel choice), send (per-channel workers call providers), and track (status, receipts, bounces).

Why one queue per channel?

Providers differ in speed, limits and failures. Separate queues and worker pools act as bulkheads, so an outage or backlog in one channel does not block the others.

Name three sources of duplicate notifications.

The caller retrying after a timeout, the queue redelivering after a worker crash, and a worker retrying a provider call that had in fact succeeded.

Transient versus permanent delivery errors?

Transient (timeouts, 429, 5xx) are retried with backoff until a deadline. Permanent (invalid token, hard bounce, bad number) are never retried, and the address is removed or suppressed.

What does "sent" mean, and how is it different from "delivered"?

Sent means the provider accepted the request. Delivered means the device, inbox or handset received it, which you learn later from app callbacks, email webhooks or SMS delivery receipts, and not always.

Where should user preferences and frequency caps be checked?

In the router, just before a message enters a channel queue, so recent opt-outs are respected. Security and legally required messages bypass marketing opt-outs.

Review the deck