SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a Chat App
  • Design a News Feed
  • Design a Notification System
  • Design a Web Crawler
  • Design Search Autocomplete
  • Design File Storage (Dropbox)
  • Design Video Streaming (YouTube/Netflix)
  • Design a Distributed Cache
  • Design a Leaderboard
  • Design a Job Scheduler
  • Design a Social Media Platform (Facebook)
System Design/Case Studies/Medium
Interview case study

Design a Notification System

Send push, SMS and email to millions of users: queues, retries, preferences and no duplicates.

โฑ 32 min readMedium case studyIntermediate23 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

โ€œDesign a notification system.โ€

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Scoping a vague promptPush, SMS, email and in-app are different systems with different costs and guarantees. A strong candidate asks which channels, which kinds of message, and how many.
Reliability without duplicatesNobody can promise exactly once. The interviewer wants at-least-once delivery plus an idempotency key, and an honest account of what happens when a send fails.
Isolation and priorityA marketing campaign must never delay a login code. This is the heart of the question and separates a diagram from a design.
Respecting outside limitsProviders such as APNs, FCM and SMS gateways have rate limits and outages. The design must pace itself and survive them.
Users and trustPreferences, quiet hours, opt-out and not sending fifty pushes in a minute are product features that shape the data model.

TL;DRThe whole design in 60 seconds

A notification system takes an event or a campaign and delivers it to the right user, on the right channel, once, at the right time. We build it as a pipeline: an intake API stores the request, a preference check filters it, separate priority queues feed one worker pool per channel, and the workers call the outside providers and record the result.

  • Scale: 10M notifications a day is only about 120 a second, and 1,200 a second at a 10x peak. Throughput is easy. Correctness, isolation and provider limits are the hard parts.
  • No lost messages: save the request first (outbox), then queue it. The queue is at-least-once, and failed sends retry with backoff and jitter, then go to a dead-letter queue.
  • No duplicates: an idempotency key per (notification, user, channel). The second copy is recognised and skipped.
  • Priority: transactional messages (login codes, receipts) get their own queue and workers, and reserved provider capacity. A campaign can slow itself down but can never slow a code.
  • Campaigns: expand the audience in pages, send in paced batches, checkpoint so a crash resumes, and let an operator pause or cancel.
  • Respect the user: opt-outs, quiet hours in the user's time zone, frequency caps, and a digest instead of a flood.
๐Ÿ’กHow to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
5
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Channels, transactional vs marketing, scale, delivery promise, preferences.
2. Estimate3Sends per second, per-channel mix, provider limits, token and log storage.
3. API and data5One intake call with an idempotency key, preferences, the notification log.
4. High-level design8Intake, checks, priority queues, channel workers, providers, status callbacks.
5. Deep dives15Reliability and duplicates, then priority isolation, then preferences, then campaign fan-out.
6. Scale and failures7Provider outage, hot campaign, dead tokens, monitoring, security.
7. Wrap up3Recap, trade-offs, what you would do next.

Step 1Clarify requirementsabout 4 min

๐Ÿค”
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change the design. Hint: think about which channels, what is urgent and what is bulk, what delivered means, and what the user can control.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
Which channels: mobile push, SMS, email, in-app, or all of them?Each channel has its own provider, cost, limits and delivery signal.Push, SMS and email. In-app is a stretch goal.One pipeline with a pluggable worker per channel, each with its own queue and rate limit.
What kinds of message: transactional (codes, receipts), event alerts, or marketing campaigns?Urgent and bulk traffic cannot share a line, or a campaign will delay a login code.All three. Codes must arrive in seconds.Priority lanes with separate queues, workers and reserved provider capacity.
How many notifications a day, and how big can one campaign be?Sets throughput, queue depth, and whether fan-out needs its own service.About 10 million a day, bursts of 10 times, and campaigns up to 1 million recipients.Modest throughput. A campaign expander with paging and pacing is required.
What does delivery guarantee mean: at most once, at least once, exactly once?Decides retries, deduplication, and what we promise the business.Never lose a code, and never send the same message twice if we can avoid it.At-least-once queue plus an idempotency key. We say plainly that exactly once is not possible end to end.
Can users choose channels, opt out, or set quiet hours?Preferences must be checked on every send and shape the data model.Yes. Per channel and per category, with quiet hours by time zone.A preferences store read on every notification, and time-zone-aware scheduling.
Do we need to know if it was delivered or opened?Delivery receipts exist for some channels only and arrive later, if at all.Track sent and delivered where the provider tells us, and clicks for email.A status callback path and a notification log with a state machine.
Is a message built from a template, with languages and personalisation?Rendering can be a separate service and affects message size and caching.Yes, templates with variables, in several languages.A template service, rendered at send time, versioned.
Can messages be scheduled for later, or sent at a local time?Scheduling needs a timer store and affects fan-out timing.Yes, such as 9 am in each user's time zone.A scheduler that releases batches by time zone.
Do we own the providers or call third parties such as APNs, FCM and an SMS gateway?Third parties set rate limits and fail on their own schedule.Third parties, with a backup SMS vendor.Pacing, retries, circuit breakers and provider failover.
How fast must a transactional message arrive?The latency target decides how we protect that lane.A login code within 5 seconds at the 99th percentile.A short, dedicated path with a tight queue-age alert.

Write the scope on the board

Functional (must do)
  • โ€ขAccept a notification request for a user (or an audience) with a template and a priority
  • โ€ขDeliver by push, SMS and email, and record the result of each attempt
  • โ€ขRespect each user's channel choices, opt-outs and quiet hours
  • โ€ขSend campaigns to a large audience, with pause and cancel
  • โ€ขSchedule a notification for a later time or a local time
  • โ€ขReport status: queued, sent, delivered, failed
Non-functional (how well)
  • โ€ขTransactional messages delivered within 5 seconds at p99
  • โ€ขNever lose an accepted notification, and avoid duplicates
  • โ€ขHandle 10M a day on average and a 10 times burst
  • โ€ขSurvive a provider outage without losing or flooding messages
  • โ€ขA campaign must never delay urgent traffic
  • โ€ขAuditable: we can say what was sent to whom, and why not
Out of scope (say it)
  • โ€ขBuilding our own email server, push gateway or telephone network
  • โ€ขA rich campaign editor and A/B testing of messages
  • โ€ขReal-time chat delivery (a different problem)
  • โ€ขDeep analytics and attribution
๐ŸŽค
Say it out loud
โ€œLet me confirm the scope. We deliver push, SMS and email, from three kinds of traffic: transactional codes and receipts, event alerts, and marketing campaigns. Scale is about 10 million a day, with 10 times bursts and campaigns up to a million recipients. Codes must arrive within 5 seconds at p99. We promise at-least-once delivery with deduplication, so we avoid duplicates but never claim exactly once. Users can opt out per channel and set quiet hours. We call third-party providers, so we respect their limits and handle their outages. I will leave out a campaign editor and analytics. Does that match?โ€

Step 2Estimate the scaleabout 3 min

๐Ÿค”
Pause. Try it yourself first
On paper: sends per second on average and at peak, the split by channel, how long a big campaign takes at the provider limit, and how big the token, preference and log tables are. Which number drives the design?

Assumptions (say them first)

AssumptionValue
Notifications per day (average)10 million
Peak to average10 times
Channel mix70% push, 20% email, 5% SMS, 5% in-app
Largest campaign1 million recipients
Provider limit for one SMS or push account (illustrative)about 1,000 sends per second
Share of that limit reserved for transactional traffic30%
Registered users and devices100 million users, 1.5 devices each
Notification log recordabout 500 bytes, kept 90 days
One send call to a providerabout 100 ms, 50 in flight per worker
At-least-once redelivery rate (illustrative)about 0.5% of messages
Price per SMS and per email (illustrative)about $0.01 and $0.0001

The arithmetic, line by line

WhatMathsResult
Average sends per second10,000,000 รท 86,400about 116, say 120 per second
Peak sends per second120 ร— 10about 1,200 per second
Push, email, SMS per day10M ร— 70%, 20%, 5%7M push, 2M email, 500K SMS (and 500K in-app)
A 1M campaign at the full 1,000/s limit1,000,000 รท 1,0001,000 s, about 17 minutes
A code stuck behind that campaign in one shared queueup to the whole drain timeup to about 17 minutes (a code lives for about 5)
A campaign when 30% is reserved for codes1,000,000 รท (1,000 ร— 70%)1,429 s, about 24 minutes
Send workers needed at peak1,200 รท (50 รท 0.1 s = 500 per worker)2.4, so 3. Run 6 for headroom and zones
Device-token table100M ร— 1.5 ร— 200 bytes30 GB
Preference table100M users ร— 200 bytes20 GB
Notification log10M ร— 500 bytes ร— 90 days, then ร— 3 copies5 GB a day, 450 GB, 1.35 TB replicated
Duplicates a day with no deduplication10,000,000 ร— 0.5%50,000 people get a message twice
Daily cost of SMS versus email500K ร— $0.01 against 2M ร— $0.0001$5,000 against $200: 25 times the daily bill, from a quarter of the volume (100 times the price per message)
What the numbers tell us about the design
  • โ€ขThroughput is small: 1,200 sends a second at peak is a few workers. The difficulty is not speed.
  • โ€ขA shared queue is a trap: one 1M campaign takes about 17 minutes to drain and would hold every login code behind it.
  • โ€ขThe provider limit, not our hardware, sets the pace. We must pace sends and reserve capacity for urgent traffic.
  • โ€ขTables are small (30 GB of tokens, 20 GB of preferences). Preferences and tokens can be cached in memory.
  • โ€ขWithout deduplication about 50,000 people a day get a message twice. At-least-once needs an idempotency key.
  • โ€ขSMS is the cost driver: 100 times the price of email in our assumption. Cost control (digest, channel fallback order, quotas) is a real requirement.
๐ŸŽค
Say it out loud
โ€œLet me do the maths. Ten million a day is about 120 sends a second, 1,200 at a 10 times peak, so a handful of workers. That tells me speed is not the hard part. The hard part is that a 1-million campaign at a 1,000 a second provider limit takes about 17 minutes, so if codes share the queue, a code waits behind it. So I will reserve capacity for transactional traffic and give it its own lane. Tokens and preferences are tens of gigabytes, so they cache well. Redelivery of about half a percent means 50,000 duplicates a day without an idempotency key. And SMS costs 100 times email per message, so on a quarter of the volume it is still 25 times the daily bill: channel choice is a cost decision too.โ€

Step 3Define the API and the data modelabout 5 min

๐Ÿค”
Pause. Try it yourself first
Write the one call a product team makes to send something, what you must put in it so a retry cannot cause a duplicate, and the tables you need for preferences, devices and the log.

Endpoints

MethodPathRequestResponseNotes
POST/v1/notifications{ idempotencyKey, to: user | audience, template, data, priority, channels?, sendAt? }202 { id, status: queued }Accepted, not delivered. The same idempotencyKey returns the same id and sends nothing new. Priority is transactional, alert or bulk.
GET/v1/notifications/{id}none200 { status, attempts: [{ channel, provider, state, at }] }For support and the product team. Reads the log, never changes it.
PUT/v1/users/{id}/preferences{ channels: { push, sms, email }, categories, quietHours: { start, end, zone } }200Read on every send, so it is cached. An opt-out takes effect within seconds.
POST/v1/devices{ userId, platform, pushToken }201Called by the app on start-up. A token can change or die, so this is an upsert.
POST/v1/campaigns/{id}/pausenone200Also resume and cancel. Campaigns are long-running jobs with a state, not a single request.
POST/webhooks/{provider}provider payload200Delivery receipts and bounces from outside. Verify the signature, then update the log. Must be idempotent.

Data model

TableKey fieldsNotes
notificationsid, idempotency_key (unique), user_id, template, priority, state, created_at, send_atThe source of truth. State machine: queued, rendering, sent, delivered, failed, suppressed.
attemptsnotification_id, channel, provider, state, error, atOne row per try. Explains why a message was or was not sent.
user_preferencesuser_id, channel opt-ins, categories, quiet_hours, time_zoneAbout 20 GB. Cached in memory, written through on change.
devicesuser_id, platform, push_token, last_seenAbout 30 GB. A dead token is deleted when a provider reports it invalid.
templatesid, version, locale, channel, bodyVersioned, so a send always uses the version it was queued with.
campaignsid, audience_query, state, cursor, total, sentThe cursor lets a crashed campaign resume where it stopped.
The send message on the queue (small, no personal data beyond ids)
{
  "notificationId": "n_8f21",
  "idempotencyKey": "order-991-shipped:u_42:push",
  "userId": "u_42",
  "channel": "push",
  "priority": "transactional",
  "template": { "id": "order_shipped", "version": 7, "locale": "en" },
  "data": { "orderId": "991" },
  "attempt": 1
}
๐Ÿ“Which store, and why
The notification log and campaigns need durability and queries by id and user, so a replicated database (sharded by user id) is the source of truth. Preferences and tokens are read on every send, so they sit in a database with a cache in front. Queues carry the work, one per channel and priority. Counters (frequency caps, per-provider pacing) live in a fast in-memory store such as Redis, because losing a few only means a small error.
๐ŸŽค
Say it out loud
โ€œProduct teams call one endpoint with an idempotency key, a template, the data and a priority, and get back 202 with an id: accepted, not delivered. The idempotency key is built from the business event, such as order 991 shipped, so a retry cannot send twice. Preferences, device tokens, templates and a notification log with a state machine sit behind it. Providers call us back with receipts on a webhook, which we verify and apply idempotently.โ€

Step 4Draw the high-level designabout 8 min

๐Ÿค”
Pause. Try it yourself first
Draw the boxes from the request to the phone. Where do you save the request before it is queued, where do you check preferences, and where do you split urgent from bulk?
Notification system: high-level design
๐Ÿ›’Services and eventsorders, auth, marketing
โ†’โ†“POST /notifications
๐ŸšชIntake APIvalidate, idempotency key
โ†’โ†“
๐Ÿ—„๏ธLog + outboxsave first
โ†’โ†“
๐ŸงญRouterpreferences, caps, quiet hours
Priority lanes (queues)
๐Ÿ”‘Transactionalcodes, receipts: own queue
๐Ÿ””Alertsevent updates
๐Ÿ“ฃBulkcampaigns, digests
Channel workers
๐Ÿ“ฑPush workerAPNs, FCM
๐Ÿ’ฌSMS workertwo vendors
โœ‰๏ธEmail workertemplate render
Around the edge
๐ŸงฉTemplate servicerender, locale
๐ŸชฆDead-letter queuegave up, inspect
๐Ÿ“ฅWebhook receiverreceipts, bounces
๐ŸงฎCampaign expanderpages, paced batches
โ†’โ†“bulk lane
โฐSchedulersend_at, time zones
Save, then queue. Separate lanes by priority and channel. Workers pace themselves against each provider. Callbacks close the loop.
ComponentWhat it does
Intake APIValidates, checks the idempotency key, saves the notification, and answers 202. It does no sending.
Log and outboxThe notification row and the queue message are written in one local transaction, so we never save without queueing, or queue without saving.
RouterReads preferences (cached), applies opt-out, quiet hours and frequency caps, picks channels, and puts a message on the right lane.
Priority lanesSeparate queues (and worker pools) for transactional, alert and bulk traffic. Transactional has reserved capacity.
Channel workersRender the template, call the provider with a pacing limit and a timeout, and record the attempt. Retries with backoff and jitter.
Provider layerWraps APNs, FCM, SMS and email vendors. Has a circuit breaker per provider and a backup vendor for SMS.
Campaign expanderTurns an audience into batches, pages through it, checkpoints a cursor, and feeds the bulk lane at a paced rate.
SchedulerHolds messages with a send time and releases them on time, including local times by zone.
Webhook receiverTakes receipts and bounces from providers, verifies them, and updates the log. Removes dead tokens and suppresses bounced addresses.
Write path (follow one request)
  1. A service calls POST /v1/notifications with an idempotency key, a template, data and a priority.
  2. The intake API checks the key. If it was seen, it returns the earlier id. Otherwise it validates the request.
  3. In one local transaction it inserts the notification (state queued) and an outbox row. It answers 202.
  4. A relay reads the outbox and publishes a routing message. The relay is at-least-once, and the key makes repeats harmless.
  5. The router loads preferences, drops opted-out channels, applies quiet hours and caps, and writes one send message per channel and priority lane.
  6. A campaign request does the same, except the expander creates the messages in pages and paced batches.
Read path (follow one request)
  1. A channel worker takes a message from its lane. Transactional lanes are served first, with their own worker pool.
  2. It checks the idempotency key in a fast store. If this (notification, user, channel) was already sent, it acknowledges and stops.
  3. It renders the template for the user's locale and loads the device token or address.
  4. It asks the provider pacer for permission (a token bucket per provider), then calls the provider with a short timeout.
  5. On success it records sent and acknowledges the message. On a temporary failure it retries later with backoff and jitter. After the last try it goes to the dead-letter queue.
  6. Later the provider calls the webhook. We update the log to delivered or failed, delete a dead token, or suppress a bounced address.
๐ŸŽค
Say it out loud
โ€œHere is the picture. Services call an intake API, which saves the notification and an outbox row in one transaction and answers 202. A relay publishes it to a router, which applies preferences, quiet hours and frequency caps. Then it goes on one of three lanes: transactional, alerts or bulk, each with its own queue and workers, so a campaign can never hold up a login code. Channel workers render the template, pace themselves against the provider, and call it with a timeout. Failures retry with backoff, then go to a dead-letter queue. Providers call a webhook with receipts, which updates the log and cleans dead tokens. A campaign expander and a scheduler feed the bulk lane.โ€

Step 5Deep dive into the hard partsabout 15 min

๐Ÿง The pattern for every deep dive
Problem โ†’ options โ†’ pick one โ†’ say why โ†’ say what it costs. Interviewers score the reasoning more than the choice.
5.1

Reliable delivery without duplicates

The problem: A send can fail at any step: the server crashes after saving, the worker crashes after calling the provider but before acknowledging, the provider times out after actually sending. We must not lose a notification, and we must not send it twice. Both cannot be guaranteed perfectly, so we choose which error to prefer.

OptionHow it worksGoodBad
Send in the request, no queueThe intake API calls the provider and returns the result.Simplest. Immediate feedback.A slow provider slows the caller. A crash loses the message. No retries.
Queue only (at-most-once)Publish to a queue and acknowledge before sending.No duplicates.A crash after the acknowledgement loses the message. Wrong for a login code.
Outbox plus at-least-once queue plus idempotency keySave the notification and an outbox row in one transaction. Publish from the outbox. Workers acknowledge after sending, and skip a key they already sent.Nothing is lost. A repeat is recognised and skipped. Retries are safe.More parts. A small window remains: a provider that accepted a send but did not answer may send twice.
Exactly-once from the brokerRely on transactional features of the queue.Fewer duplicates inside the queue.Stops at the edge: the call to an outside provider is not part of that transaction. Not a real guarantee here.
Pick
Outbox, an at-least-once queue, and an idempotency key per (notification, user, channel)

Save before you queue. The notification row and the outbox row are written in one local transaction, so the intake API can crash at any point and nothing is lost or half-saved. A relay publishes from the outbox, possibly more than once, which is fine because the next steps are idempotent.

Prefer a duplicate to a loss for a code, and say so. Workers acknowledge after the provider call. If a worker dies in between, the message is redelivered. The idempotency key (a unique key in a fast store, set before the call and confirmed after) makes the second attempt a no-op. For providers that accept a client-supplied message id (many email and SMS vendors do), pass the same id so they de-duplicate too.

The worker loop (sketch)
msg = queue.take()
key = msg.idempotencyKey                       // "order-991-shipped:u_42:push"

if store.alreadySent(key): ack(msg); return     // a repeat: do nothing

if !pacer.tryAcquire(msg.provider):             // respect the provider limit
    requeue(msg, delay = backoff(msg.attempt)); return

result = provider.send(msg, clientId = key, timeout = 2s)

if result.ok:
    store.markSent(key); log.sent(msg); ack(msg)
else if result.temporary:                       // 5xx, timeout, throttled
    requeue(msg, delay = backoff(msg.attempt) + jitter)
else:                                           // permanent: bad token, bounced address
    log.failed(msg); cleanup(msg); ack(msg)

after max attempts: deadLetterQueue.put(msg); ack(msg)
Where it failsWhat the system does
Intake crashes before savingNothing was accepted. The caller sees an error and retries with the same key.
Crash after saving, before queueingThe outbox row is still there. The relay publishes it on restart.
Worker crashes after the provider acceptedThe message is redelivered. The key (and the provider's own id) stops a second send in most cases.
Provider times out after sendingThe one case that can duplicate. We accept it and say so: duplicate over loss.
Provider rejects the token or addressA permanent failure: do not retry. Delete the token or suppress the address.
๐Ÿง Say it plainly
Exactly-once delivery to a phone is not possible: the last hop is outside our control. We promise at-least-once delivery with deduplication, which gives exactly-once effects in almost every case.
๐ŸŽค
Say it out loud
โ€œI cannot promise exactly once, because the last hop is a third party. So I save the notification and an outbox row in one transaction, publish at-least-once, and have workers acknowledge after the send. An idempotency key per notification, user and channel makes a repeat a no-op, and I pass it to the provider as the message id when it supports that. The one gap is a provider that sent but timed out, and for a login code I would rather risk a duplicate than a loss. Failures retry with backoff and jitter, and the last ones go to a dead-letter queue.โ€
5.2

Priority and isolation: a campaign must not delay a login code

The problem: All traffic wants the same provider capacity. A million-message campaign can fill a shared queue for 17 minutes. A login code that arrives behind it expires before it is sent. We also have per-provider rate limits we must not exceed.

OptionHow it worksGoodBad
One shared queue, first in first outEverything goes into one line.Simplest. Fair by arrival.A campaign blocks everything behind it. The failure we are trying to avoid.
One queue with priority levelsA priority queue serves urgent messages first.One system. Urgent jumps ahead.A busy bulk worker pool still holds the provider connections. Starvation of bulk. Hard to reason about under load.
Separate queues and worker pools per priority and channelTransactional, alerts and bulk each have their own queue, workers and autoscaling.Real isolation. A bulk backlog cannot touch urgent traffic. Easy to alarm per lane.More queues to run. Idle capacity in the quiet lane.
Separate lanes plus reserved provider capacityAs above, and a per-provider token bucket gives transactional a guaranteed share (for example 30%) that bulk cannot spend.Isolation holds even at the provider limit. Bulk is paced to the leftover.Bulk is slower than it could be. Needs the provider limit to be known.
Pick
Separate lanes per priority and channel, with reserved provider capacity for transactional traffic

Isolation has to hold at three places: the queue (so a backlog cannot block), the workers (so bulk cannot use up the connections), and the provider limit (so bulk cannot spend the allowance). That is why a priority queue alone is not enough. Each channel and priority has its own queue and pool, and each provider has a token bucket per lane, with transactional guaranteed its share.

Bulk is allowed to be slow: with 30% reserved, our million-message campaign takes about 24 minutes instead of 17, and that is the right thing to give up. Alarm on queue age in the transactional lane (oldest message above a few seconds), not on queue length.

LaneQueueWorkersProvider shareAlarm
Transactionalown, shortown pool, always warm30% reserved, can borrowoldest message above 5 s
Alertsownown poolshares the restoldest above 60 s
Bulkown, deepsmall pool, scales on a schedulewhat is left, pacedcampaign behind its plan
๐Ÿ’กTry it in the visualizer below
Put everything in one shared queue and watch the codes wait for minutes behind the campaign. Then switch to separate lanes. Then switch the provider to an outage and compare dropping failures with retrying them.
๐Ÿ“Fairness between teams
If many teams send, give each tenant a weighted share of the bulk lane so one team's campaign cannot starve another's. A token bucket per tenant on the expander does it.
๐ŸŽค
Say it out loud
โ€œThe risk is a big campaign delaying a login code. A single shared queue does that, and a priority queue alone does not fix it, because the bulk workers still hold the provider connections. So I give transactional, alerts and bulk their own queues and worker pools, and a token bucket per provider that guarantees transactional a share, say 30%. Bulk gets the rest and is paced. A million-message campaign then takes about 24 minutes instead of 17, which is a fair price. I alarm on the age of the oldest transactional message, not on queue length.โ€
5.3

Preferences, quiet hours and not annoying people

The problem: A notification system that sends everything it is asked to will get uninstalled, blocked or reported as spam. We must honour opt-outs and quiet hours, cap how often one person is contacted, and merge noisy events, all on every send and without slowing the pipeline.

OptionHow it worksGoodBad
Callers decideEach product team checks preferences before calling us.Simple for the platform.Every team reimplements it, differently. Opt-outs get missed. Legally risky.
Central check at send timeThe router reads preferences, quiet hours and caps for each message.One place, always applied. An opt-out takes effect at once.A read on every send, so it needs a cache. Adds a little latency.
Central check at send time, plus digest and collapseAs above, and batch similar events (50 likes) into one message, or replace an older unread one with the newer.Fewer, better notifications. Less SMS spend.A delay for digest items. More logic and state.
Pick
A central check in the router at send time, with a cached preference store, frequency caps and digests

The platform owns this, because it is the only place that sees everything sent to a person. The router reads the user's preferences from a cache (about 20 GB, so it fits in memory across a few nodes), drops opted-out channels, and holds back anything inside the user's quiet hours. Transactional messages such as a login code are normally exempt from quiet hours and from marketing opt-out, and that exemption is a rule the business must own.

For frequency, a counter per (user, category) in Redis allows, say, 3 marketing messages a day. For noisy event streams, a collapse key keeps only the latest notification of a kind, and a short digest window merges many into one. Quiet hours and scheduled sends need the user's time zone, so the scheduler releases a campaign in waves by zone, not all at once.

RuleApplies toWhere it runs
Opt-out by channel or categoryMarketing and alerts. Not legal or security messages.Router, from the preference cache
Quiet hours (user time zone)Marketing and alerts. Codes are exempt.Router holds the message and the scheduler releases it
Frequency cap (for example 3 a day)MarketingCounter in Redis per user and category
Collapse keyEvent streams (likes, comments)Keep the newest, drop older unsent ones
Digest windowLow-urgency eventsHold for a few minutes, then send one summary
Channel fallback orderEverythingPush first, then email, SMS only when it matters (it costs the most)
โš ๏ธLegal and trust
Unsubscribe links, consent records and region rules for SMS and email are legal requirements in many places. Treat them as hard rules in the router, keep the consent history in the log, and say that the exact rules should be checked with legal.
๐ŸŽค
Say it out loud
โ€œPreferences have to be applied in one central place, because only the platform sees everything sent to a person. The router reads cached preferences, drops opted-out channels and holds anything inside quiet hours, using the user's time zone. Codes are exempt, which is a business rule. A counter per user and category in Redis enforces a frequency cap, a collapse key keeps only the newest notification of a kind, and a short digest window merges noisy events. SMS is the most expensive channel, so the fallback order is push, then email, and SMS only when it matters.โ€
5.4

Fanning out a campaign to a million people

The problem: A campaign is one request that means a million sends. Creating a million messages at once floods the queue and the database, a crash halfway can send some people twice or never finish, and an operator who spots a typo needs to stop it now.

OptionHow it worksGoodBad
Create all messages up frontQuery the audience and enqueue one message per person immediately.Simple.A huge memory and queue spike. Cannot be paused. A crash loses track of who was done.
One worker loops over the audienceA single job pages through users and sends.Easy to follow. Easy to pace.One machine is the limit. A crash restarts from the beginning.
Paged expansion with a checkpoint cursorThe expander reads the audience in pages (for example 1,000 ids), enqueues them to the bulk lane, and saves the cursor after each page.Resumable. Memory stays small. Paced. Can pause and cancel between pages.More state to keep. Audience can change while it runs, so fix the audience at the start.
Sharded expansionSplit the audience by id range or user hash across several expanders, each with its own cursor.Scales to very large audiences. Faster.More coordination. Pacing must be shared across shards.
Pick
Paged expansion with a checkpoint cursor, a paced bulk lane, and a shared limit for the whole campaign (shard it only if one expander is too slow)

Fix the audience when the campaign starts (a snapshot or a stable query), so people do not move in and out. The expander walks it in pages, enqueues each page to the bulk lane, and saves a cursor after every page. After a crash it resumes from the cursor, and the idempotency key (campaign id, user, channel) makes the one possibly-repeated page harmless.

Pace the ramp-up: start slowly, watch error rate and provider throttling, and grow. Keep a progress record (total, enqueued, sent, failed, suppressed) so an operator can watch it, and check a paused or cancelled flag before each page. Pause and cancel stop new pages at once, and the workers drop queued messages for a cancelled campaign.

Campaign stateWhat happens
Draft, then scheduledAudience query and template are saved. Nothing is sent. A send time is set.
RunningThe expander pages through the audience, saves its cursor, and feeds the bulk lane at the paced rate.
PausedNo new pages. Queued messages for it are skipped by workers. Resume continues from the cursor.
CancelledNo new pages. Workers drop its queued messages. The record keeps the counts.
DoneCursor at the end, and the sent, failed and suppressed counts add up to the audience.
๐Ÿ’กTwo numbers to know
A 1M campaign in pages of 1,000 is 1,000 pages. At a paced 700 sends a second the lane drains in about 24 minutes. The cursor row is written 1,000 times, which is trivial.
๐ŸŽค
Say it out loud
โ€œI would not create a million messages at once. I fix the audience when the campaign starts, then an expander reads it in pages of about a thousand, puts each page on the bulk lane, and saves a cursor. If it crashes it resumes from the cursor, and the idempotency key covers the one page that may repeat. Sends are paced and ramped up while I watch errors and provider throttling, and the expander checks a paused or cancelled flag before every page, so an operator who finds a typo can stop it within a page. If one expander is too slow I shard the audience by id range.โ€
VisualizerA campaign, a login code, and a provider outageStart with one shared queue and a 500,000 campaign: watch how long the codes wait. Switch to separate lanes. Then set the provider to an outage and compare dropping failed sends with retrying them, and turn the idempotency key on.
Queues
The provider (APNs, SMS gateway, email service)
Failed sends
Duplicate protection
The campaign is queued at second 0. 3,000 one-time codes arrive from second 10 to 70 (50 a second). The picture shows the queue length over time (8 min 23 s in all).
One-time codes waiting (peak 3,000)
Campaign waiting (peak 499,000)
0 s4 min 12 s8 min 23 s
Code wait (worst)
8 min 11 s
average 7 min 43 s
Campaign done
8 min 20 s
last message sent
Duplicates delivered
2,515
people who got it twice
Dead-letter queue
0
0 are codes
One shared line: every code waited behind the campaign. The worst code took 8 min 11 s (average 7 min 43 s). A login code that arrives after its 5-minute life is useless. Switch to โ€œSeparate priority lanesโ€ and the codes jump the line.

A simplified model with fixed numbers (no random values). The provider sends up to the limit each second. Workers retry by pausing during the outage, which is what backoff achieves. Redeliveries are set at 0.5% of sends, an illustrative rate for an at-least-once queue.

Step 6Scale, bottlenecks and failuresabout 7 min

๐Ÿค”
Pause. Try it yourself first
If traffic grows 10 times, what breaks first? If the SMS vendor goes down, what do users see? If a campaign has a typo, how fast can you stop it?

What breaks first, and the fix

BottleneckFix
Provider rate limits (not our hardware)A token bucket per provider and lane, with transactional reserved. Ask for higher limits, and add providers or accounts before adding workers.
Bulk backlog after a big campaignSeparate bulk lane, paced ramp-up, and scale bulk workers on a schedule. Never let it share workers with transactional.
Preference and token lookups on every sendCache in memory (about 50 GB in all), write-through on change, and batch lookups per page for campaigns.
Hot database rows (a popular user, a busy campaign counter)Shard the log by user id, and count campaign progress in batches or in Redis, then flush.
The notification log grows without limitPartition by day, keep 90 days hot, archive the rest to cheap storage, and drop payloads sooner than metadata.
Template rendering cost at 1M a campaignRender at send time from a cached, compiled template. Pre-render only if the body is identical for all.
Time-zone peaks (everyone at 9 am)Release the scheduled sends in waves by zone, which also spreads provider load across the day.

What if a part fails?

FailureHow the design copes
A provider is down or throttlingCircuit breaker per provider. Retry with backoff and jitter, then fail over to a backup vendor for SMS and email. Urgent traffic gets the backup first.
Worker crashes mid-sendThe message is redelivered. The idempotency key stops a second send in nearly every case.
A queue or broker node failsReplicated queues. Producers retry. The outbox means nothing accepted is lost.
A dead or invalid device tokenThe provider says so. Delete the token on a permanent error and do not retry.
A bad campaign (wrong template, wrong audience)Pause or cancel within a page, workers drop its queued messages. Test sends and a small first wave catch most of these.
Webhook receipts are late or missingTreat sent as the main state and delivered as bonus. A timeout turns an unknown into 'sent, not confirmed' without a retry.
What to monitor
  • โ€ขOldest message age per lane, and the transactional p99 time from accepted to sent
  • โ€ขProvider error rate, throttle responses and circuit breaker state, per provider
  • โ€ขDead-letter queue size and its top error reasons
  • โ€ขCampaign progress against plan, and the unsubscribe or complaint rate right after a send
  • โ€ขDuplicate-suppressed count (a jump means redelivery is high) and invalid-token rate
Security and abuse
  • โ€ขAuthenticate callers and give each team limits, so no one can send as another or spam the platform.
  • โ€ขKeep personal data out of queue messages and logs. Pass ids and fetch details at send time.
  • โ€ขVerify provider webhooks by signature, and treat them as untrusted input.
  • โ€ขProtect codes: short life, one use, and rate-limit how many a person can ask for (SMS pumping fraud is a real cost attack).
  • โ€ขHonour consent and unsubscribe as hard rules, and keep an audit trail of what was sent and why not.

Step 7Wrap upabout 3 min

An intake API saves each request with an outbox row in one transaction and answers 202. A router applies preferences, quiet hours and caps, and puts work on separate lanes for transactional, alert and bulk traffic, each with its own queue and workers and a share of every provider's limit. Workers send with an idempotency key, retry with backoff, and dead-letter what keeps failing. Campaigns expand in pages with a checkpoint and can be paused. Webhooks close the loop and clean up dead tokens.

Trade-offs you made

DecisionWhat we gainWhat it costs
At-least-once with an idempotency keyNothing accepted is lost, and duplicates are almost always caught.A rare duplicate when a provider sends but times out. True exactly-once is not possible.
Separate lanes with reserved provider capacityA campaign can never delay a login code.More queues and pools to run, and bulk is slower than it could be.
Central preference check at send timeOpt-outs and quiet hours are applied everywhere, at once.A cached read on every send, and one more component to keep available.
Outbox before the queueNo lost or half-saved notifications.A relay to run and a small publish delay.
Sent as the main state, delivered as a bonusHonest about what we know. Works for every channel.Product teams must accept that delivery receipts are partial.
Digest and collapse for noisy eventsFewer messages, happier users, lower SMS cost.Some updates arrive a few minutes late.
If we had more time, we wouldโ€ฆ
  • โ€ขMulti-region: a stack per region, with users routed to their home region and a backup path for provider outages.
  • โ€ขA second push path and smarter channel choice based on what each user opens.
  • โ€ขSend-time optimisation and per-user frequency learning.
  • โ€ขA test-send and dry-run mode that shows what a campaign would do before it starts.
  • โ€ขA load test of a million-message campaign beside a steady stream of codes, and a provider-failure drill.
๐ŸŽค
Say it out loud
โ€œTo recap: an intake API saves the request with an outbox row in one transaction. A router applies preferences, quiet hours and caps, then puts the work on separate lanes for transactional, alert and bulk traffic, each with its own queue and workers and a reserved share of each provider's limit. Workers send with an idempotency key, retry with backoff and jitter, and dead-letter what keeps failing. Campaigns expand in pages with a cursor and can be paused. The main trade-off is that we promise at-least-once with deduplication, not exactly once. Next I would add multi-region and send-time optimisation.โ€

Q&ACross-questions (23)

๐Ÿ’กHow to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Reliability and duplicates

The interviewer wants to hear you refuse to promise exactly once, and still show a design that behaves like it.

Scale, priority and the providers

The traffic is easy. The shared resource is the provider limit.

Users, preferences and time

These questions test whether you think about the person at the other end.

Curveballs

These change the problem. Say what changes and what stays.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Add real-time in-app notificationsA new channel worker writes to a per-user inbox and pushes through a connection service. The inbox is the source of truth. The router, preferences and log are unchanged.
Messages must arrive in order for a userPartition by user id so one user's messages go to one worker, add a sequence number the client checks, and accept lower parallelism. Prefer a collapse key where only the latest matters.
Strict regional rules: data must stay in the EUA full stack per region, users homed to a region, providers chosen per region, and logs that never leave it. Cross-region campaigns run one expander per region.
Users can reply to a messageAdd an inbound path: provider webhooks for replies, a parser, and routing to the right team. Add spam checks. This is a new system beside the sender.
Guaranteed delivery with an audit for the regulatorStronger log retention, an immutable audit trail, delivery confirmation as a requirement, and a fallback to a second channel when no receipt arrives.
Cost cap: SMS budget is cut by 80%Move to push and email first, use SMS only for codes, add per-team quotas and digests, and report spend by team. A routing rule, not new architecture.
Notifications triggered by thousands of events a second per user (a trading app)Collapse keys and digests become mandatory, with a per-user rate limit and a local aggregator. The queue sees fewer, merged messages.
Very low latency for codes: under 1 secondA dedicated, always-warm transactional path with local provider connections, a short timeout, an immediate second provider, and no preference lookup beyond a cache hit.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts with queues. Never separates urgent from bulk, or asks about channels and guarantees.Asks about channels, scale, urgency and delivery promise, and writes them down.Also asks about preferences, quiet hours, receipts and cost, and states what is out of scope.
EstimationNo numbers, or assumes the hard part is throughput.Sends per second, a peak, and storage.Notices that a campaign drains for minutes at the provider limit, and uses that to justify separate lanes.
ReliabilitySays use a queue with exactly once.Outbox or retry with an idempotency key, and a dead-letter queue.Explains the acknowledge-after-send gap, the provider-timeout duplicate, and chooses duplicate over loss for codes.
Isolation and limitsOne shared queue, or a priority field only.Separate queues per priority.Isolates queue, workers and provider share, paces with a token bucket, and alarms on queue age.
User respectSends whatever it is told.Checks preferences and opt-outs.Quiet hours by zone, frequency caps, collapse and digest, and exempts codes by rule.
CommunicationDraws a box for every vendor without a reason.Follows the steps and explains choices.Names what is approximate or not guaranteed, summarises each step, and checks in with the interviewer.

AvoidCommon mistakes on this question

MistakeDo this instead
Promising exactly-once deliverySay at-least-once plus deduplication, and name the one gap: the provider that sent but timed out.
One shared queue for everythingSeparate lanes, workers and a reserved share of each provider limit, and alarm on the oldest transactional message.
Calling the provider inside the requestAccept, save with an outbox row, return 202, and send from workers.
Retrying everything immediatelyRetry only temporary failures, with backoff and jitter, a maximum attempts and age, and a dead-letter queue.
Ignoring the provider's rate limitPace with a token bucket per provider and scale on the allowance, not on CPU.
Letting every team check preferences themselvesCheck centrally in the router, at send time, so opt-outs are applied everywhere.
Putting personal data in queue messages and logsCarry ids, fetch details at send time, and keep sensitive details out of push and SMS bodies.
Treating delivered as always knownUse sent as the main state, delivered as a bonus where receipts exist, and say so to product teams.

Revise60-second revision sheet

  • โœ”Scale: 10M a day is about 120 sends a second, 1,200 at a 10 times peak. Speed is easy. The provider limit and isolation are the hard parts.
  • โœ”Campaign maths: 1M at 1,000 a second is about 17 minutes. With 30% reserved for codes it is about 24 minutes.
  • โœ”Pipeline: intake API, log and outbox, router, priority lanes, channel workers, providers, webhooks.
  • โœ”Save before you queue: the notification and an outbox row in one transaction. Answer 202.
  • โœ”Delivery promise: at-least-once plus an idempotency key. Never claim exactly once. Prefer a duplicate to losing a code.
  • โœ”Retries: only temporary failures, with backoff and jitter, then a dead-letter queue. A bad token or bounced address is permanent.
  • โœ”Isolation: separate queue, workers and provider share per priority. Alarm on queue age.
  • โœ”Respect users: opt-out, quiet hours by time zone, frequency caps, collapse keys and digests. Codes are exempt by rule.
  • โœ”Campaigns: fixed audience, paged expansion with a cursor, paced ramp-up, pause and cancel between pages.
  • โœ”Cost and abuse: SMS costs 100 times email per message, so use it last. Limit code requests to stop SMS pumping.

Read these topics next

Push Notificationsโ†’

How a message reaches a closed phone through APNs and FCM.

Message Queuesโ†’

The lanes between the router and the workers.

Dead Letter Queuesโ†’

Where the messages that keep failing go.

Retries with Backoffโ†’

Retrying temporary failures without causing a flood.

Idempotent Consumer and Inbox Patternโ†’

How a repeated message is recognised and skipped.

Outbox Patternโ†’

Saving the request and the queue message together.

Rate Limitingโ†’

Pacing sends to a provider's limit.

Webhooksโ†’

How providers report receipts and bounces back to you.

Design a Rate Limiterโ†’

The token bucket that paces each provider lane.

โ† Previous
Design a News Feed
Next โ†’
Design a Web Crawler