InterviewDryRun
Lesson 6 · 22 min video · free

Design a Notification System

Every product sends push notifications, emails and text messages, from dozens of internal teams. This lesson designs the shared service they all call: one API in, the right message out on the right channel, respecting preferences and quiet hours, surviving slow providers, and never sending the same message twice. It covers the full 45-minute interview answer.

What you will learn

  • Separate accepting a notification from delivering it with a durable queue in between.
  • Check preferences, quiet hours and per-user limits before anything is queued for delivery.
  • Give each channel its own queue and workers, so a slow email provider never delays push.
  • Retry with backoff and failover between providers; idempotency keys stop duplicates.
  • Priorities let a login code jump ahead of a marketing campaign.
  • Track every state change so producers and support can answer what happened to a message.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The API for producers
  5. Step 4: The high-level design
  6. Step 5: Preferences, quiet hours and limits
  7. Step 6: Channels, providers and retries
  8. Step 7: At least once, but not twice
  9. Step 8: Priorities and fairness
  10. Step 9: Scheduled and delayed notifications
  11. Step 10: Templates and tracking
  12. Step 11: Storing everything
  13. Step 12: The follow-up questions
  14. Recap

Short on time? Read the answer outline for design a Notification System.

Practice this question with Max

The question

Welcome to lesson six of the InterviewDryRun system design course. Today we design a notification system: the shared service that sends push notifications to phones, emails, and text messages, on behalf of every team in a company.

Think of all the messages a large product sends. Your order has shipped. Someone replied to your comment. Here is your login code. Your weekly summary is ready. Each of those comes from a different team, and without a shared service, every team would build its own integration with email and text providers, its own retry logic, and its own way of respecting the user's settings. The results are duplicated effort and annoyed users, who get the same message twice or a marketing email at three in the morning.

Max asks

“Design a service that sends push, email and SMS notifications to users from many internal producers.”

That is how Max, our AI interviewer, asks it. Two phrases matter. Many internal producers: this is a platform used by other teams, so its API and its fairness between teams matter. And push, email and SMS: three channels with very different providers, costs and speeds, which is the core of the design challenge.

The plan: requirements, numbers and the API. Then the high-level design, which centres on separating accepting a notification from delivering it. Then deep dives on preferences, channel queues and providers, retries and duplicates, priorities and rate limits, templates, and tracking. Then the follow-up questions.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    Three channelsMobile push, email, SMS; in-app later
  2. 02
    Many producersAny internal service can send
  3. 03
    User preferencesOpt out per channel and per category
  4. 04
    TemplatesProducers send data, not finished text
  5. 05
    SchedulingSend now, or at a time, or in the user's quiet window
  6. 06
    StatusWas it sent, delivered, opened?

As always, start by asking questions. This one has many possible features, so your job is to pick a sensible core and say what you are leaving out.

The channels: mobile push, email and text messages, with in-app notifications as a likely next step. And producers: any internal service can send a notification, so the system needs to know who sent what, for limits and for billing between teams.

Preferences are essential. Users can turn off a channel, or a category, like marketing, while still getting security alerts. Ask whether some categories can never be turned off. Usually yes: login codes and security alerts must always go out, because they are part of the product working, not marketing.

Templates: producers should send structured data, like the order number and the delivery date, and the notification service turns that into the final text in the user's language. That keeps wording consistent and lets non-engineers edit messages.

And scheduling and status. Producers want to send now, or at a specific time. And they want to know what happened: sent, delivered, failed, opened. Customer support will ask the same question every day: did this user get their code? So tracking is a real requirement, not an extra.

Non-functional requirements
  1. 01
    ReliableAccepted means it will be sent, at least once
  2. 02
    No duplicatesUsers should not get the same message twice
  3. 03
    Fast for urgent onesLogin codes within seconds
  4. 04
    ScalableCampaigns of millions at once
  5. 05
    IsolatedOne slow provider or noisy team cannot block others

Now the qualities. Reliability: once we accept a notification, it must not be lost. And at the same time, no duplicates, because a user who gets three copies of a message turns notifications off, and that hurts every team. These two pull against each other, and the design will need to handle both.

Latency depends on the kind of message. A login code must arrive within seconds, because the user is staring at the screen waiting for it. A weekly summary can take an hour. So we will need priorities.

And scale and isolation. A marketing campaign can mean twenty million notifications in a few minutes, and that burst must not delay a single login code. Likewise, if the email provider slows down, push notifications must keep flowing. Isolation between channels, priorities and teams will shape the whole design.

Step 2: Back-of-the-envelope estimates

Sizing the system
Users100 millionwith apps and email addresses
Notifications a day1 billionabout 12,000 a second on average
Campaign peak200,000 / sa big send in a few minutes
Split70% push25% email, 5% SMS
SMS costreal moneyeach message costs a fraction of a cent or more
Log storageabout 1 TB / day1 billion events x 1 KB

Let us size it.

Say a hundred million users and a billion notifications a day. That is about twelve thousand a second on average. But campaigns are bursty: a marketing team sends twenty million messages at once, and if we let them, that is two hundred thousand a second for a couple of minutes. So the peak is much higher than the average, and the design must absorb bursts rather than size every part for them.

The split matters. Most notifications are push, which is cheap. Email is a quarter. Text messages are a small share but expensive: each one costs real money, so a bug that sends a million duplicate texts costs a lot. Say that out loud. It is a good reason why deduplication and limits matter so much here.

And tracking: a billion notifications a day, each with a few status events of about a kilobyte, is around a terabyte of event data a day. That needs a store designed for high write volume and time-based queries, not the main relational database. Keep a few weeks hot, and archive the rest.

Notice what these numbers do not need. Twelve thousand notifications a second is a modest rate for queues and workers. The difficulty is not throughput. It is bursts, external providers we do not control, and correctness for users: the right message, once, at the right time. So the design will spend its effort on queues, isolation and deduplication, not on exotic scaling tricks.

Step 3: The API for producers

Sending a notification
POST /v1/notifications
{ "idempotencyKey": "order-8812-shipped",
  "userId": "u_4411",
  "category": "order_updates",
  "template": "order_shipped",
  "data": { "orderId": "8812", "eta": "Friday" },
  "channels": ["push", "email"],     // optional
  "priority": "normal",
  "sendAt": null }
→ 202 Accepted { "notificationId": "n_9f2..." }

The producer's API is the contract with every team in the company, so get it right. A producer sends a user id, a category, a template name and the data for the template. It can optionally pick channels; otherwise the category's default channels and the user's preferences decide.

Two fields deserve emphasis. The idempotency key, chosen by the producer, such as order eight eight one two shipped. If the producer retries because of a timeout, we recognise the key and do not create a second notification. This is the first defence against duplicates, and it costs almost nothing.

And the response is two-oh-two, accepted, not two hundred. We are not saying the message was delivered, only that we have it durably and will deliver it. That honest status code tells the interviewer you already plan to separate accepting from sending. For campaigns, add a bulk endpoint that takes a segment of users or a file, so a team does not make twenty million separate calls.

Add two read endpoints too: the status of a notification by its id, for producers and support, and the user's own preferences, which the app's settings screen reads and writes. That is the whole external surface: send, check status, and manage preferences.

Step 4: The high-level design

High-level design
acceptper channelCLIENTProducersinternal servicesSERVICENotification APIvalidate, dedupeQUEUEIntake queuedurableWORKERProcessorprefs, template, limitsQUEUEChannel queuespush, email, SMSWORKERChannel senderscall providersEDGEProviderspush, email, SMS

Now the architecture. The most important idea fits in one sentence: accept fast, deliver later. Producers call the notification API, which validates the request, checks the idempotency key, and does nothing else on the request path.

It writes the notification to a durable intake queue and returns accepted. That queue is what makes our reliability promise true: once the write is acknowledged, the notification survives any crash after it. And a burst of twenty million campaign messages simply makes the queue longer; it does not overload anything.

A pool of processor workers reads the intake queue. For each notification, they look up the user's contact details and preferences, decide which channels to use, apply quiet hours and per-user limits, and render the template for each channel in the user's language.

Then the processor puts one message per channel onto that channel's own queue. Push, email and text each get a separate queue, and, as we will see, separate priorities within them.

Finally, channel senders read their queue and call the external providers: the mobile platforms' push services, an email delivery provider and an SMS gateway. Each channel's senders scale independently, and each has its own retry and failover logic, because each provider fails in its own way.

Pause and point out why this shape works. Every stage is connected by a queue, so each stage can be scaled, slowed or restarted on its own, and a problem in one stage builds up a backlog instead of a failure. That is the theme of this whole design.

Step 5: Preferences, quiet hours and limits

Data the processor reads
TableKeyHolds
contactsuser_iddevice tokens, email, phone, language, time zone
preferencesuser_id, categorychannel on or off
categoriescategorydefaults, can it be muted, priority
user_countersuser_id, daynotifications sent today

The processor is where the user's wishes are enforced, so let us look at the data it reads.

The contacts table holds the device tokens for push, one per installed app, plus the email address, phone number, language and time zone. Device tokens change when apps are reinstalled, so the app registers its latest token on every launch, and we remove tokens that providers tell us are no longer valid.

Preferences are per user and per category: order updates by push and email, marketing never. The categories table holds the defaults, and a flag saying whether the category may be muted at all. These tables are read on every notification and change rarely, so cache them heavily. A billion lookups a day against a cache is fine; against the database it would not be.

Then protection for the user. Quiet hours: unless a notification is urgent, hold it until morning in the user's time zone, which means the processor sometimes schedules a notification instead of sending it. And a per-user limit, say no more than a handful of marketing pushes a day across all teams. Without it, each team behaves reasonably on its own, and the user still gets twenty notifications a day in total. The shared service is the only place that can see the total, so it is the right place to enforce it.

Say one more thing: preferences must be checked when sending, not only when accepting. If a user turns off marketing while a campaign is still waiting in the queue, they should not get it. So the sender can re-check a cached preference just before the provider call. It is cheap and it avoids a common complaint.

Step 6: Channels, providers and retries

Each channel fails differently
ChannelProvider limitsCommon failures
Pushplatform push gatewaysexpired tokens, throttling
Emaildelivery provider, sending reputationbounces, spam complaints, slow accepts
SMSgateway per country, cost per messagecarrier filtering, country rules

Now the senders, where the outside world gets messy. Each channel talks to different providers with different limits and failure modes.

Push goes through the mobile platforms' push gateways, which are fast and free, but throttle senders who go too fast, and tell us when a token is invalid, at which point we must delete it. Sending to dead tokens repeatedly can get us throttled further.

Email goes through a delivery provider. Our reputation as a sender decides whether mail lands in the inbox or in spam, so bounces and spam complaints must be processed: a hard bounce means stop sending to that address. And text messages go through SMS gateways, which cost money per message, differ by country, and are filtered by carriers. Many companies use two SMS providers and route by country and price.

Retries without making things worse
  1. 01
    Retry transient errorsTimeouts and throttling: back off exponentially with jitter
  2. 02
    Do not retry permanent onesInvalid token, hard bounce: record and stop
  3. 03
    Fail overSecond provider when the first keeps failing
  4. 04
    Dead letter queueAfter N tries, park it for inspection
  5. 05
    Circuit breakerStop hammering a provider that is down

Retries are central to reliability, but careless retries cause outages. Separate transient errors, like timeouts and throttling, which we retry with exponential backoff and random jitter, from permanent errors, like an invalid token or a hard bounce, which we must never retry. Retrying permanent failures wastes money and damages our reputation with providers.

When a provider keeps failing, fail over to a second one, if we have it. Text messages and email often have two providers for exactly this reason. Push usually has only one per platform, so for push we wait and retry.

After a set number of attempts, move the message to a dead letter queue, where it is kept for inspection and can be replayed once the problem is fixed. And put a circuit breaker around each provider: if most calls are failing, stop sending for a short while, and let messages wait in the queue. A queue that grows is far better than a thousand workers hammering a provider that is already struggling.

Step 7: At least once, but not twice

Where duplicates come from, and the fixes
Producer retries a timed-out call   → idempotency key at the API
Queue redelivers after a crash       → dedupe on notificationId + channel
Provider call times out, then worked → provider idempotency id

sender:
  if seen(notificationId, channel): skip
  provider.send(msg, idempotencyId = notificationId)
  markSent(notificationId, channel)

We promised reliability and no duplicates. Queues give us at-least-once delivery: if a worker crashes after sending but before acknowledging the message, the queue gives the message to another worker, which sends it again. So duplicates are a natural consequence of reliability, and we need explicit defences at every step.

At the front door, the idempotency key stops duplicate producer calls. Inside, each sender records which notification and channel pairs it has already sent, in a fast store with a time to live of a day or two. Before sending, it checks that record. So a redelivered queue message is recognised and skipped.

There is one gap that no internal record can close: we call the provider, the call times out, but the provider actually sent the message. Did it go out or not? We cannot know. Where providers support it, pass our notification id as their idempotency id, so a retry is recognised on their side. Where they do not, choose per channel: for a login code, a rare duplicate is better than a missing code; for a marketing text that costs money, prefer to skip. Saying that this is a per-channel trade-off is exactly what interviewers want to hear.

Step 8: Priorities and fairness

Priority lanes for one channel
always firstrate limitedWORKERProcessorQUEUEUrgent queuecodes, securityQUEUENormal queueactivity, ordersQUEUEBulk queuecampaigns, digestsWORKERSendersreserved capacity per lane

Now, the campaign problem. A marketing team sends twenty million notifications. If they all go into the same queue as login codes, a login code waits behind twenty million campaign messages, and users cannot sign in. So each channel gets several priority lanes: urgent, normal and bulk.

Senders always drain urgent first, and each lane has reserved capacity, so bulk traffic can use spare capacity but can never take the share reserved for urgent messages. The bulk lane is also rate limited to what the providers allow and what our sending reputation can handle. A campaign takes twenty minutes instead of two, and nobody notices.

Fairness between teams matters too. Give each producer a quota, and if one team floods the system, its notifications queue up behind its own quota rather than everyone else's. This is the same token bucket idea from the rate limiter lesson, applied to producers. It turns one team's mistake into that team's problem, which is the right outcome for a shared platform.

Step 9: Scheduled and delayed notifications

Holding notifications until later
  1. 01
    WhysendAt times, quiet hours, digests, reminders
  2. 02
    Time bucketsStore by the minute they are due
  3. 03
    SchedulerEach minute, move due items to the intake queue
  4. 04
    Cancel and replaceDelete by id before it is due

Many notifications should not go out right away. A producer asks for a specific send time, quiet hours push a message to the morning, and reminders fire a day after something happened. So we need a way to hold notifications until they are due, potentially millions of them.

A simple, scalable approach: store scheduled notifications in a table partitioned by the minute they are due. Each partition holds everything due in that minute, so the scheduler never scans the whole table. It only reads the bucket for the current minute.

Every minute, a scheduler reads the due bucket and puts those notifications onto the intake queue, where they go through the normal pipeline, including a fresh check of preferences. To avoid one scheduler being a single point of failure, run several, each owning a share of the buckets, with a lease so that exactly one handles each share at a time. If a scheduler falls behind, it simply processes older buckets first, so nothing is skipped.

And producers must be able to cancel. A reminder to finish checking out should not arrive after the user already paid. So scheduled notifications can be deleted by id, or replaced by sending a new one with the same idempotency key. This is a detail interviewers like, because it is the kind of thing real products need on day one.

Digests are a special case of scheduling. Instead of ten separate notifications about likes on a post, the processor can collect them for an hour and send one message: ten people liked your post. That means grouping by user and category in a short-lived store, and a scheduled job that sends the summary. It reduces noise for users and cost for us, and it is a nice extension to mention if time allows.

Step 10: Templates and tracking

Templates and status events
  1. 01
    Versioned templatesPer channel and language; edited without deploys
  2. 02
    Render at processing timeNot when accepted, not when sent
  3. 03
    Status eventsaccepted, queued, sent, delivered, opened, failed
  4. 04
    Event storeWrite-heavy, time-ordered, kept for weeks

Templates are stored with versions, per channel and language, because a push needs one short line, while an email needs a subject, a body and an unsubscribe link. Editing a template should not need a deploy, but every change is versioned so a bad edit can be rolled back, and we always know which version produced a given message.

For tracking, every stage emits a status event: accepted, queued, sent, delivered, opened or failed, with a reason. Delivered and opened come back later from the providers, through webhooks for email and receipts for push, so tracking is naturally asynchronous.

With a terabyte of events a day, store them in a write-optimised store partitioned by time and by notification id. Support can then answer did this user get their code in seconds, producers can see delivery rates per template, and we can spot a provider getting worse before users complain.

Use the same events to drive automatic hygiene. Hard bounces remove email addresses, invalid tokens remove devices, and a user who never opens a category's notifications can be sent fewer of them. That keeps our sender reputation healthy, which directly improves delivery for every team.

Step 11: Storing everything

Where each kind of data lives
DataStoreWhy
Contacts, preferencesrelational, cachedsmall, read constantly, changed rarely
Templatesrelational, versionededited by people, needs history
Queuesdurable log or queueordering per lane, replay
Sent records for dedupein-memory store with TTLfast checks, short lifetime
Status eventswide-column or columnar1 TB a day, queried by id and time

Let us close the design by saying where each kind of data lives, because a notification system touches several very different kinds of data, and one database cannot serve them all well.

Contacts, preferences and templates are small, change rarely, and are read on every notification. A relational database works well, with a cache in front. Templates need history, so keep every version.

The queues need durability and the ability to replay, so a durable log or a managed queue service fits. The record of what we have already sent, used for deduplication, only needs to live a day or two and must be very fast, so an in-memory store with a time to live is ideal.

And the status events, a terabyte a day, go into a store built for heavy writes and time-ordered reads, partitioned by time. Choosing different stores for different access patterns, and explaining why, is a sign of a mature answer.

Step 12: The follow-up questions

Max asks

“The SMS provider goes down for an hour. What happens to login codes?”

The circuit breaker opens for that provider and the sender fails over to the second SMS provider. If there is no second one, urgent texts wait in their queue with retries, and the product should offer another way to receive the code, like email or an authenticator app. When the provider recovers, we should drop codes that have already expired instead of sending them, so senders check an expiry time on urgent messages before sending.

Max asks

“A user has the app on three devices. Do they get three notifications?”

For push, we send to every registered device, because the user might be using any of them, and the mobile platforms collapse duplicates where the same app is on one device. Then when the user opens or dismisses it on one device, a silent update can clear it from the others. For email and text there is only one address, so the question does not arise.

Max asks

“How would you send a campaign to twenty million users at exactly nine in the morning in each time zone?”

Store the campaign once, not twenty million scheduled rows. A scheduler, every minute, finds the time zones where it has just become nine, and expands that slice of the audience in batches into the bulk lane. The bulk lane's rate limit spreads the sends over several minutes, which is fine. Expanding lazily like this keeps storage small and lets us cancel the campaign at any point.

Max asks

“How do you keep a buggy producer from spamming every user?”

Several layers. A per-producer quota in the API. A per-user daily limit across all producers. An alert when a producer's volume jumps far above its normal level, which can automatically pause the bulk lane for that producer. And for new templates or campaigns, start with a small percentage of users and watch the complaint rate before sending to everyone.

Max asks

“Product wants an in-app notification inbox as well. What changes?”

It becomes a fourth channel, but one we own end to end. The sender writes the message into an inbox store, keyed by user and ordered by time, and the app reads the latest page when it opens. For users who are online right now, we also push the new item over their open connection, so it appears instantly. Read and unread state lives in the same store. Because there is no outside provider, this channel is the most reliable of all, and it is a good fallback when push permission is turned off.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsThree channels, many producers, preferences, status
  2. 02
    5 to 10: estimates and API1 billion a day, bursty; idempotency key; 202
  3. 03
    10 to 20: the pipelineIntake queue, processor, channel queues, senders
  4. 04
    20 to 35: deep divesPreferences, retries, duplicates, priorities
  5. 05
    35 to 45: operationsTemplates, tracking, provider failure, campaigns

Here is the forty-five minutes. Five minutes of requirements: three channels, many producers, preferences and status. Five minutes of numbers and the API, ending with an idempotency key and a two-oh-two accepted response.

Ten minutes on the pipeline: accept fast into a durable queue, process preferences and templates, split into channel queues, and send through providers. Every stage connected by a queue.

Then fifteen minutes on the hard parts: preferences and limits, retries that do not cause outages, duplicates at every step, and priority lanes so a campaign never delays a login code. And the last ten minutes on templates, tracking and the follow-ups. If your answer keeps returning to isolation, between channels, priorities and teams, the interviewer will see you have built shared platforms before.

This question has many moving parts, and it is easy to ramble. Practicing out loud is how you learn to keep it in order. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson seven.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.