Systemsfor Aravinda
0 / 78 core
Week 9 · Case studies

Design a notification system

1.5 hours · core path

Read first: Queues and logs, Retries, backoff, and circuit breakers

In one sitting

A notification system turns a product event into in-app, email, or push where the user's preferences allow, and it checks those preferences again at send time. A queue absorbs a morning spike and workers retry with backoff. At-least-once delivery plus an idempotency key stops your own duplicates, without promising that a phone shows the banner exactly once.

A notification is a decision to bother someone, on a channel they allowed, retried until it is done or you give up. You can make your own handler remember what it already did. You cannot promise that a phone shows a banner exactly once. The design is at-least-once delivery into an idempotent handler, plus a queue so a 9am spike does not become a 9am outage.

Requirements

The user is a person who set preferences, and a product team that emits “the report is ready” without knowing whether that person wants email. The notification system owns the decision and the retries. The product team owns the fact that something happened.

Functional requirements:

  • Accept an event: who, what happened, which category.
  • Deliver on the channels that preferences allow. The channels in this design are an in-app inbox, email, and mobile push. Adding another channel later should be another queue, not a rewrite.
  • Honor quiet hours for delayable categories. A security alert is immediate. A weekly tip is not.
  • Retry when a provider is briefly down. Stop retrying when the request is invalid.
  • A person who turns a channel off should stop getting it, including for events already queued.

Non-goals:

  • Exactly-once display on a lock screen. You will not promise that, and you will not accept a design that pretends a checkbox provides it.
  • The product workflow itself. If the report failed, this system does not rerun the report. It might tell the person the report failed, if that event is emitted.
  • A marketing studio, template editor, and campaign calendar. A scheduled send is just a large batch of events. The studio is someone else’s product.
  • Cross-channel transactions. Email failing must not roll back the in-app row. They are different side effects.

Assumption: the inbox is yours, so a write there can be as durable as your database. Email and push are someone else’s API. An acknowledgement from them means they accepted the request, not that a human saw it.

Estimation

Assumptions:

  • 25 million events per day arrive from product services.
  • Ordinary peak is 4 times the average. Assumption.
  • A scheduled reminder at 09:00 local is 4 million pushes you would like to finish in 10 minutes. Assumption of the campaign, separate from the ordinary peak. Say it as a spike, not as the average.
  • After preferences, 70 percent of events become an inbox row, 25 percent an email, and 20 percent a push. They overlap, so the shares sum past 100 percent. Assumption.
  • The email provider allows 2,000 sends per second on the contract you imagined. That number is a placeholder you replace with a real contract. The shape is what the interview is grading.
  • An inbox row is 400 bytes, kept 60 days. An idempotency record is about 100 bytes, kept 7 days. Both are assumptions.
25,000,000 / 86400 = 289 events per second average
25,000,000 / 1e5   = 250 events per second shortcut
ordinary peak, 4x  = about 1,160 per second
campaign 4,000,000 / 600 seconds = about 6,700 per second for 10 minutes

A day is 86,400 seconds. Dividing by 1e5 is about 14 percent low. One million events a day is about 12 per second. Ordinary traffic is a few hundred per second. The campaign is the reason the queue exists.

at 2,000 emails/s, 4,000,000 sends take 2,000 seconds, about 33 minutes
inbox rows 0.7 * 25e6 * 400 bytes = about 7 GB/day
60 days = about 420 GB raw
keys, about 29e6 channel-sends/day * 100 bytes * 7 days = about 20 GB

The 33 minutes is the lesson in the spike. The queue does not create provider capacity. If the product insists on a 10 minute drain and the provider allows 2,000 per second, you need a higher cap or an earlier start. Four million divided by 600 seconds is about 6,700 per second, and 6,700 is not a number you get to send just because you queued it. Workers drain at the rate the provider actually accepts. Everyone else keeps running while that drain happens, which is the point of a separate email queue.

Storage is small. Do not spend the interview sharding the inbox. Spend it on the crash window around the provider call.

High-level design

flowchart LR
  product[Product event] --> inboxwrite[Durable event]
  inboxwrite --> planner[Preference planner]
  planner --> qIn[In app queue]
  planner --> qEmail[Email queue]
  planner --> qPush[Push queue]
  qIn --> inbox[Inbox store]
  qEmail --> emailw[Email worker]
  qPush --> pushw[Push worker]
  emailw --> idem[Idempotency store]
  pushw --> idem
  emailw --> provider[Email provider]

Product services do not call the email provider. They record the event durably. The clean way is a transactional outbox: the business row and an outbox row commit together, and a publisher reads the outbox. If they publish to a bus and the publish fails after the commit, the event is lost. If they publish and then fail the commit, you notify about something that did not happen. The outbox closes that hole. The consumer is still idempotent, because the publisher can send the row twice.

The planner reads the event, loads preferences, and writes one intent per allowed channel. The idempotency key is event id, user id, and channel. Intents go to separate queues. A slow email provider must not block push, and push must not block the inbox. Competing consumers pull each queue. The inbox worker is a database insert. The other two call providers.

Partition the queues by user id if you want one person’s notifications ordered relative to each other. You do not need a global order. A campaign of 4 million people must spread across partitions. One key of “campaign id” would pin the spike to one partition and recreate the stampede you queued to avoid.

Deep dive

Channels and preferences

The inbox is a table you own. The unique key is the idempotency key. A retry inserts the same row and gets a conflict it treats as success. You can show the notification in a UI you control, mark it read, and delete it. This is the only channel where “delivered” means “a row committed.”

Email and push are requests to a provider. Their ack means the provider accepted them. The device can be offline. The provider may retry on their side for a while, by their own rules, which you do not get to narrate as if you had read their source. You certainly do not get to tell the interviewer that the banner appears exactly once.

Preferences are per user, per category, per channel. “Reports: email and inbox. Tips: none. Security: push and email, including during quiet hours.” Cache them. A 60 second TTL is an assumption. The important part is when you read them.

Read them at send time, including after the intent is already queued. A person who turns email off while sitting in your queue for twenty minutes does not want the mail. A decision frozen at enqueue time will send it. Quiet hours are the same check. If the category is delayable and the local time is inside quiet hours, the worker delays the intent. It does not drop it, and it does not sit in a tight retry loop. If the category is immediate, it sends. Security is immediate. A weekly tip is delayable. That classification is on the event, decided by the product, not inferred by the worker from the prose.

A stale preference cache of 60 seconds can still send one extra email after an opt-out. Say that. Shorten the TTL if that one extra is the incident you cannot have, and pay the extra reads. Do not cache preferences for a day.

At-least-once, the key, and the crash window

Delivery comes in three words and only two of them are available to you here. At-most-once is “send and forget,” or ack the queue before you call the provider. You will drop notifications whenever a worker dies. At-least-once is “ack after you are done,” which means a crash in between redelivers, so duplicates happen unless the handler is idempotent. Exactly-once is a bounded protocol inside a system that can share a transaction with the effect. A push provider is not that system. Kafka’s idempotent producer does not extend to a lock screen. Say that plainly. Idempotency plus at-least-once is the practical shape.

The handler’s record has states: empty, in progress, done, and failed in a way you will not retry. The key is event, user, and channel. Store a fingerprint of the payload. The same key with a different payload is an error, not a second send. Stripe’s published guidance treats idempotency keys as a short-term tool, on the order of 24 hours, and stores the outcome so a retry returns it. Brandur Leach’s writeup of that pattern adds the pieces you actually need: the fingerprint, a lock so two workers do not both run, and a recovery point around the side effect you cannot roll back.

Walk the email worker:

  1. Claim the queue message and insert the key as “about to send,” or lock the existing row, in one transaction. If the row is already “done,” ack the queue and return the stored outcome. Do not call the provider.
  2. If two workers race, one lock wins. The other waits or retries later. It does not start a second send.
  3. Call the provider, passing your key if they accept one.
  4. Record “sent” with whatever id they returned, then ack the queue.

A crash before step 3 retries safely. You have not called. A crash after step 4 has the outcome, so the redelivery does not call again. A crash between the provider accepting and you recording the outcome is the window. You do not know if they got it.

If the provider honors your key, the retry is safe. They return the original acceptance. If they do not, your options are to ask them whether that key was accepted, or to accept that this narrow crash can double-send. There is no third option where you “use exactly-once.” Write the honest one down. For email, a double send in a crash window is visible and annoying. For push, the provider may also duplicate on their side even when you call once. Your key stops your workers from being the source of duplicates. It does not govern their pipeline.

Keep the key at least as long as you might retry or as long as an upstream publisher might replay the event. Assumption: retry for up to 2 hours, keep the key for 7 days. Seven days is longer than the 24 hour published Stripe window because your replay threat includes a product service rebuilding a day of outbox rows, as well as a client double-clicking. Label it as your assumption. If you drop the key after an hour and a replay arrives tomorrow, you send again.

Retries and the queue

Retry when the provider times out, returns a rate-limit response, or returns a server error. Exponential backoff and full jitter: sleep a random time up to a growing cap, not exactly the cap, or a fleet of workers will retry on the same second and extend the outage. Bound the attempts. A retry budget means you do not schedule more work than the notification is still worth. A tip dies sooner than a password-reset mail.

Do not retry a bad device token or a malformed address the same way. That is a permanent failure. Remove the dead token. Ack the message. Alert if permanent failures spike, because that is often a bug in your payload, not in the provider.

A poison message that crashes the worker before the ack will come back forever. Count attempts on the intent. After the bound, park it on a dead-letter queue and ack the original. A human or a job can look at the dead letter. An infinite nack is how one bad payload eats a worker pool.

The queue’s other job is the 9am spike. Producers enqueue and return. Workers pull at the provider’s rate, which is a token bucket or a leaky drain in front of the client. Retries and breakers sit on that client. When the provider is failing, the breaker opens and the workers stop calling for a cool-down instead of holding every thread on a timeout. The queue grows. That is healthy. An unbounded queue is not. Cap it. When the cap is near, shed tips and marketing first. Do not shed security alerts to make room for a campaign. The campaign is the traffic that can wait until tomorrow. The “your login looked strange” mail is not.

Separate queues are also separate breakers. Email’s provider being down leaves push and the inbox running. One shared queue with one consumer that calls three providers will stop the world because the first call in the handler is the sick one.

Tradeoffs

Choice What you gain What you spend
At-least-once plus an idempotency key A crash retries, and a completed key does not send again You store keys, and the crash window still needs a provider that honors the key
At-most-once, ack before send Simple, and no duplicates from your workers Any crash drops the notification
Promise exactly-once push A sentence stakeholders like A lie. Their pipeline and your crash window can both duplicate
Check preferences at send time An opt-out during the queue delay is honored An extra read on the hot path, unless you cache briefly and admit one stale send
Freeze preferences at enqueue Less work at send, a stable plan A person who opted out still gets the message
One queue for every channel One thing to operate A slow email provider blocks push and the inbox
Separate queues and a bounded depth One sick channel stays in its box, and a spike cannot allocate memory forever You must decide what to shed when a bound is hit

The row you defend is at-least-once, the key, preferences at send time, and a separate bounded queue per channel. You give up the exactly-once sentence on purpose.

Failure modes

  • Provider down. The breaker opens, the email queue grows, inbox and push continue. Producers are unaffected because they only wrote the outbox. If you sized workers to the campaign spike instead of to the provider’s rate, you get a wave of rate-limit responses and then a retry storm of your own making. The drain rate is min of your worker count and their cap. Set the worker count from the cap.
  • Crash in the window after the provider accepted and before you recorded it, and their API has no idempotency key. A retry can send a second email. The symptom is rare double mail after deploys or worker kills, not a steady duplicate on the happy path. The fix is their key, or a read-back by your key, not a faster worker. If neither exists, you tell the interviewer the window is real.
  • Two product services emit two event ids for one human action, because each retry of the business operation minted a new id. Your dedupe never sees them. The key has to be derived from the business action. This is the upstream bug that looks like a notification bug. Push the idempotency requirement back to the producer.
  • Preference cache too stale. Opt-outs “do not work” for the TTL, and if a campaign is in flight the TTL covers the whole send. Checking at send time with a short TTL bounds it. Checking only in the planner does not.
  • Poison payload. One event crashes every worker that touches it, the queue retries, throughput of that partition goes to zero. Attempt cap, dead letter, ack. A handler that nacks on every exception is the bug.
  • Queue with no bound, campaign ten times larger than you assumed. Memory grows, then the broker or the worker host dies, then the retry of the whole campaign starts over. The bound and the shed policy are the failure mode you designed on purpose so this one stays a delayed tip instead of a downed pipeline.
  • Inbox unique key missing. Retries insert a second row and the person sees two copies of “report ready,” which is the one channel where you had full control and still duplicated. The key is a unique constraint, not a best-effort lookup before insert. Two workers can both see “absent” and both insert if the constraint is not in the database.

In the interview

First five minutes: three channels, preferences at send time, producers write an outbox, workers pull queues, the key is event plus user plus channel. The ordinary rate is about 250 per second with the shortcut. The 4 million person reminder is about 6,700 per second if you insist on 10 minutes, and at 2,000 per second of provider capacity it actually takes about half an hour. Say that so they know the queue is a buffer, not a multiplier.

Skip a template language, skip user-interface pixels, skip a claim about exactly-once.

The question that follows is the crash between the provider call and the recorded outcome. You name the window. If they honor the key, the retry is safe. If they do not, you can double-send, and you will not paper over it. The tradeoff you admit is duplicates in that window versus dropped notifications if you ack early. You picked duplicates you can usually suppress over silent loss.

Check yourself

Why can you not promise that a push notification is displayed exactly once?

You call a provider. Their ack means they accepted the request, not that the phone rendered it. They can duplicate inside their own pipeline, and you can call twice if you crash after they accept and before you record the outcome, unless they honor your idempotency key. At-least-once into a handler that stores the key is as far as your side goes. Exactly-once does not cross that boundary.

The worker dies after the email provider accepts and before the idempotency row is marked done. The provider does not store your key. What can happen on retry?

The redelivered job does not find a done row, so it calls again, and the person can get two emails. That window is the part you have to say out loud. A provider-side key, or a way to ask them whether this key was already accepted, closes it. A faster retry does not.

A user turns email off while the intent is still in the queue. Why is the preference check at enqueue not enough?

The planner already decided to send, based on the old preference. The message can sit in the queue for minutes during a spike or a quiet-hours delay. Checking again at send time observes the opt-out. A cache makes that check a bit stale. A decision frozen at enqueue stays wrong for the whole wait.

You want 4 million emails finished in 10 minutes, and the provider allows 2,000 per second. What does the queue actually buy you?

Four million divided by 600 seconds is about 6,700 per second, which the provider will not accept. At 2,000 per second the drain takes about 2,000 seconds, a bit over half an hour. The queue lets producers finish and lets you send at the real cap without dropping the events on the floor. It does not raise the cap. To finish in 10 minutes you need a higher cap or a smaller batch.

One payload crashes the worker every time, and the queue nacks it. What should the handler do instead?

Count attempts on the intent. After a bound, move it to a dead letter and ack the original so the partition is not stuck behind it forever. Retry with backoff and jitter is for timeouts and rate limits. An exception you throw on every delivery is a poison message, and an unbounded nack turns it into a stuck queue.

Based on: Brandur Leach, idempotency writeup; Stripe idempotency guidance; Jay Kreps, Neha Narkhede, Jun Rao, Kafka; Marc Brooker and the AWS Builders' Library.