Day 11 B-Building blocks 2026-10-05 ← All lessons

Design a notification system: queues, retries, fan-out

Your billing service wants to text a payment reminder, and the SMS company you pay is having a bad afternoon. The question is whether that one outage also delays every push and every email you send today. This lesson builds the version where it does not — and shows why “never lost” and “never duplicated” cannot both be true.

16M/day10M push, 1M SMS, 5M email — about 185/s average
4 vendorsOutside companies every delivery depends on. You control none of them
0 lostThe bar. Late or out of order is fine; missing is not
1 gapThe window between “vendor accepted” and “ID recorded” that no dedupe can close (§4)

Key points

Outcomes

01Derive the load and argue why throughput is not the design driver.
02Predict what one vendor outage does to each of the two designs — and verify it in the simulator.
03Point at the exact crash window that produces a duplicate, and explain why it cannot be closed.
04Argue the ack-before versus ack-after trade and pick a side with a reason.
01

16 million sends that depend on strangers


Six requirements, numbered, because every later decision points back at one of them:

ChannelPer dayAverage/sDelivered by
Push10,000,000~116APNs (iOS), FCM (Android)
SMS1,000,000~12Twilio, Vonage
Email5,000,000~58SendGrid, Amazon SES
Total16,000,000~185

Daily volume ÷ 86,400. No peak figure is given, so treat peaks as “higher, unknown” and design so a peak causes delay — allowed by (2) — rather than loss, forbidden by (6).

185 sends a second is not a big number, so why is this a hard question? Because the slow part is not your code. Each send ends in a network call to another company and a wait for their answer. The two expensive pieces are building the content (rendering an HTML email) and waiting on third parties. A thread blocked on Twilio is doing nothing useful.

Before anything can be sent you need addresses. Email and phone number live on the user table; device tokens live on a separate device table keyed by user_id, because one user owns several devices and a push goes to all of them. That one-user-to-many-devices relationship is the “fan-out” in this lesson's title — and it will matter in §6 in a way most people get wrong on the first attempt.

The design everyone draws first, and its three failures

Failure of the one-server designRequirement it breaks
Single point of failure. One server, so its crash stops all sending and drops whatever it held in memory.(6), and (2) for everyone at once
Cannot scale independently. Database, cache and every channel's processing share one box.(5) as volume grows
Performance bottleneck. Slow rendering and slow vendor calls compete for the same resources.(2) — one slow channel delays all channels
02

The mental model: a sorting room with one bin per carrier


Picture a mail sorting room. Clerks at the counter take letters, check the address is real, look up the recipient and stamp them. They do not deliver anything. They drop each letter into the bin for its carrier. Behind each bin stands a team of couriers who only ever empty that bin.

Now the SMS carrier goes on strike. The SMS bin fills. Those couriers keep trying and failing. The Apple, Google and email couriers never notice, because they never touch the SMS bin. The clerks keep stamping. Nothing is thrown away; it is waiting in a bin.

How to read: Left to right is the send path. Notice there is no arrow between any two queues. That absence is the isolation — it is the most important thing in the picture.

services1 … N notificationservers(the clerks) cache + databaseusers, devices, settings iOS push queue Android push queue SMS queue email queue workers workers workers workers APNs FCM SMS vendorhaving a bad day email vendor no arrows between queues A dead vendor backs up exactly one line. The other three keep draining, because nothing connects them. Isolation is a property of the shape. You own everything left of the vendor column. You own nothing in it — which is exactly why the queue sits where it does.
The analogy and the system match part for part: clerks are notification servers, bins are queues, couriers are workers, carriers are the vendors. §4 is where the analogy stops being true.
03

The mechanism: run the outage yourself


Follow one request: the shipping service tells user 123456 by SMS that a package arrives tomorrow. Six steps — the service calls the API; the server reads phone number, tokens and settings from cache; the server puts an SMS event on the SMS queue and answers the caller immediately; a free SMS worker takes the event; the worker calls the vendor and waits; the vendor delivers.

The interesting case is step 5 failing. Run both designs and watch.

How to operate: Press Run and let it settle. Press SMS vendor: up to take the vendor down, and watch the sent this tick column for push and email. Then press Switch design and repeat. Try Push spike and fix it with Add push worker. Press Crash a server in each design and watch Lost.

tick 0 design: one shared server all vendors healthy lost: 0

ChannelWaitingSent this tickSent total
Push000
SMS000
Email000

Press Run to start.

Units are illustrative. Arrivals of 10 / 1 / 5 per tick mirror the daily ratio from (5); the capacities and the 5-unit timeout cost are chosen to make the effect visible in a few ticks. One modelling detail that matters: a failed send becomes due again on the next tick, as it would under a real queue’s visibility timeout. That is what makes the backlog compound — if failures drifted to the back of an ever-growing queue instead, they would get rarer rather than denser, and nothing would collapse.

What you should have seen in the shared design. It does not break instantly — it erodes. Each failed SMS call ties up the server for a timeout, the message becomes due again next tick, and it costs the same again. The SMS backlog grows by one per tick, so a larger share of each tick’s budget is spent on calls that cannot succeed. Around tick 7 the four queued SMS retries consume the entire budget and push and email go to exactly zero and stay there. This is head-of-line blocking, and it breaks (2) for channels that did nothing wrong.

In the queued design, the SMS workers still fail, but they are the only ones failing. Their queue grows by one per tick, which is the right signal: delay, not loss — satisfying (2) and (6). When the vendor recovers, the backlog drains.

The spike shows the queue's other job: absorbing a burst. Push waiting climbs, and the key metric to monitor is exactly this — total queued notifications per channel. A large number means workers are not keeping up, and the answer is more workers. Because workers are per-channel, you add push capacity without touching SMS or email.

The crash button Crashing in the shared design throws away everything held in memory, and requests arriving while it is down are rejected. In the queued design the notification servers are several machines behind autoscaling, and pending work sits in the queues, not in a process — so a crash loses nothing. That is the SPOF row from §1, fixed.
04

The weakness: retries guarantee delivery and cause duplicates


The sorting-room model has a hidden assumption: a courier either delivers a letter or clearly does not. Real distributed systems are worse. A worker can call the vendor, the vendor can accept the message, and the worker can then die before telling anyone. From the queue's point of view that message was never finished.

To satisfy (6), the queue must hand unfinished messages out again. A worker acks only after the send succeeds; no ack means redelivery. This is at-least-once delivery, and the cost is in the name.

The mitigation is a dedupe check: when an event arrives, look up its event ID; if seen, discard; otherwise send. Try to break it.

How to operate: Leave dedupe on and press each crash button in turn, reading the log and the buzz count. One crash point beats the check — find it. Then turn dedupe off and repeat. Finally press Ack before sending to see the opposite mistake.

phone buzzes: 1 worker routine: pull → check ID → call vendor → record ID → ack

Moving the ack earlier removes that duplicate and creates a lost message instead. You must pick which failure you prefer.

So the honest statement is: dedupe shrinks the duplicate window to the gap between the vendor's acceptance and your write to the seen-ID store. You cannot close that gap, because the vendor call and your database write are two separate systems with no shared transaction. Recording the ID before calling the vendor just moves the gap — a crash there means the ID says “sent” and nothing was, which violates (6).

Option A — what (6) requires

Ack after sending (at-least-once)

  • A crash anywhere leads to redelivery, so nothing is lost.
  • A crash after the vendor accepted produces a duplicate.
  • Fits (6): delayed or repeated, never lost.
Option B

Ack before sending (at-most-once)

  • Never a duplicate.
  • A crash after the ack but before the vendor call loses the message forever.
  • Violates (6). Acceptable only for messages nobody misses.
Two more places the model is generous The queue only buys time. If a vendor is down for hours, the backlog grows for hours and users see late messages. Isolation contains the blast radius; it does not deliver the SMS.  Duplicates have unequal cost. A repeated one-time code is mildly annoying; a repeated “your payment failed” email generates support calls. That asymmetry is why dedupe is worth its storage even though it cannot be perfect.
05

The fix and its price: components around the queue


The final design wraps the queues in guards. Each exists because of a specific requirement or failure, and each one costs something.

ComponentWhat it doesPrice you pay
Notification logPersists every notification so a crash anywhere can be recovered and retried. Serves (6)A write per notification — ~16M rows a day — plus retention decisions
Retry on errorA failed send returns to its queue and is retried a bounded number of times, then developers are alerted. Serves (6)Retries multiply load on a vendor already struggling, and they are the source of duplicates (§4)
Dedupe by event IDDiscards an event whose ID was already sentA lookup on every send, and a store of seen IDs with a retention window
Notification settings(user_id, channel, opt_in), checked before any send. Serves (4)Another read on the hot path; cached to keep it cheap
Rate limitingCaps how many notifications one user receives, because flooded users disable notifications entirelySome legitimate messages get held or dropped — and you must decide which
AuthenticationappKey / appSecret so only verified clients can sendKey distribution and rotation for every internal caller
TemplatesPreformatted messages with parameters: “[ITEM] is back, until [DATE]”A template store to version and cache
Queue monitoringWatches queued count per channel; a rising number means add workersDashboards and alert thresholds to tune
Event trackingRecords pending, sent, delivered, click, unsubscribe, error; feeds analyticsMore event volume than the sends themselves

The order on the hot path matters: authenticate, check settings, rate-limit, then enqueue. Checking opt-in after enqueueing wastes queue and worker capacity on a notification nobody will receive.

Read the price column as a budget. An interviewer will ask which you would build first, and the honest order follows the requirements: notification log and retries first because (6) is non-negotiable, the settings check next because (4) is a legal and trust issue, then dedupe, rate limiting and analytics as the product matures.

How many workers? Little’s Law answers it in one line

The lesson has said “add more workers” several times without ever saying how many. There is an exact answer, and it is the most useful formula in queueing:

L = λ × W  —  concurrency = arrival rate × time in system

Push runs at ~116 sends/second, and an APNs call takes ~200 ms wall-clock, almost all of it waiting. So 116 × 0.2 = 23 — you need about 23 concurrent workers in flight just to keep up, and that number is driven almost entirely by the vendor's latency rather than by your own CPU. If the vendor slows from 200 ms to 1 s, the same traffic suddenly needs 116 workers. A vendor getting slower is indistinguishable from your traffic rising 5×, and that is the single most useful consequence of the formula.

And you cannot run them at 100% Queueing time rises as ρ / (1 − ρ), where ρ is utilisation. At 50% busy, a message waits about as long as one service time. At 90% it waits 9×. At 95%, 19×. At 99%, 99×. The curve is not a gentle slope — it is a wall, and you hit it suddenly. This is why a system that looks fine at 70% utilisation falls over at 85% with no change in traffic shape, and why capacity planning targets 60–70% rather than “we have headroom until 100%”. Size the pool for peak arrival rate at your target utilisation, not for the average.

Three more guards worth naming

PatternWhat it doesWhy it belongs here
Circuit breakerThree states. Closed: calls flow, failures counted. Open: after a threshold, stop calling entirely and fail instantly for a cooldown. Half-open: let one probe through; success closes it, failure re-opens.Retries alone make a struggling vendor worse. A breaker is the thing that stops you calling — it converts a slow timeout on every message into an instant local failure, freeing the workers that were all blocked waiting.
Bounded queuesEvery queue has a maximum depth, and a defined behaviour on overflow.An unbounded buffer is a latency bomb: it never rejects, so it absorbs an overload silently and then delivers hours-old messages. For notifications specifically, a one-time code delivered six hours late is worse than not delivered — so time-sensitive messages need a TTL and should be allowed to expire in the queue. That is a deliberate, named exception to requirement (6), and saying so is better than pretending the requirement is absolute.
Load shedding and degradationUnder overload, reject the lowest-value work early rather than serving everything badly. Keep behaviour the same whether or not a dependency is healthy — static stability.If the dedupe store is down, you can still send (accepting duplicate risk) rather than stopping. If the template service is down, send plain text. Degrading on a known axis beats failing on an unknown one.
Where the work lives Workers and notification servers stay stateless. Everything that must survive a crash lives in the queue, the notification log, or the seen-ID store. That is precisely why you can add or kill workers freely: no worker owns anything another worker could not pick up.
06

The code: fan-out, backoff, dedupe


worker.py — standard library only, vendor faked with a 30% failure ratepython
import heapq, random, time

MAX_RETRIES = 3        # bounded: then a human is told
BASE_DELAY  = 0.2      # seconds before the first retry

devices  = {123456: ["ios-tok-a", "android-tok-b", "ios-tok-c"]}
settings = {(123456, "push"): True}      # (user_id, channel) -> opt_in
seen     = set()                         # dedupe store (Redis in production)
ready, dead, seq = [], [], 0

class VendorError(Exception): pass

def vendor_send(token, body):
    if random.random() < 0.3:
        raise VendorError("timeout")
    print(f"  delivered to {token}: {body}")

def schedule(msg, delay=0.0):
    global seq
    seq += 1
    heapq.heappush(ready, (time.time() + delay, seq, msg))

def enqueue(event):
    if not settings.get((event["user_id"], event["channel"]), False):
        print("  skipped: user opted out")      # (4): nothing is queued at all
        return
    for token in devices.get(event["user_id"], []):      # fan-out: one msg per device
        schedule({"id": f'{event["id"]}:{token}',      # key is event:token, NOT event
                  "token": token, "body": event["body"], "attempt": 0})

def worker():
    while ready:
        ready_at, _, msg = heapq.heappop(ready)
        wait = ready_at - time.time()
        if wait > 0: time.sleep(wait)
        if msg["id"] in seen:
            print(f"  dup discarded {msg['id']}"); continue
        try:
            vendor_send(msg["token"], msg["body"])
        except VendorError as e:
            msg["attempt"] += 1
            if msg["attempt"] > MAX_RETRIES:
                dead.append(msg)
                print(f"  ALERT: {msg['id']} failed {MAX_RETRIES} retries ({e})")
            else:
                delay = BASE_DELAY * 2 ** (msg["attempt"] - 1)   # 0.2, 0.4, 0.8
                delay *= random.uniform(0.5, 1.5)               # jitter
                schedule(msg, delay)
            continue
        # ---- the duplicate window from §4 is between the line above and the line below.
        #      It cannot be closed: two systems, no shared transaction. ----
        seen.add(msg["id"])
        # In a real queue, the ack goes here — after the ID is recorded.

enqueue({"id": "evt-9001", "user_id": 123456, "channel": "push",
         "body": "Your package arrives tomorrow"})
worker()
print(f"sent={len(seen)} dead_lettered={len(dead)}")

The lines that matter, in the order the worker hits them:

  1. The settings check is in enqueue, not in the worker

    An opted-out user never costs queue space or a vendor call — the hot-path ordering from §5.

  2. Fan-out creates one message per device

    User 123456 has three devices, so one event becomes three queue entries. Each fails and retries on its own, so a dead Android token does not hold back the two iPhones.

  3. The dedupe key is event_id:token, not event_id

    If the key were the event alone, the first device to succeed would mark the event seen and the other two would be discarded as duplicates. That is a silent loss, which breaks (6) — and it is the single most common bug in this design.

  4. Backoff doubles, with jitter

    0.2s, 0.4s, 0.8s. A vendor having a bad afternoon gets fewer and fewer calls instead of a retry storm, and the jitter stops thousands of workers retrying in the same instant.

  5. After three retries the message is dead-lettered and an alert fires

    Parked, not deleted, so a human can inspect and replay it.

  6. seen.add comes after the vendor call

    Move it before and a crash makes the system believe it sent something it did not. §4's trade-off, written as a line order.

07

Field guide and interview follow-ups


RoleReal serviceWhy it is there
iOS pushAPNsThe only way to reach an iPhone. The OS holds one persistent connection per device, so you hand off rather than keeping millions of sockets
Android pushFCMGoogle's equivalent. Unavailable in China, where Jpush or PushY are used — so design the worker to swap providers
SMSTwilio, VonageCarrier relationships and per-country routing are a business, not a feature
EmailSendGrid, Amazon SESDeliverability depends on IP reputation, DKIM/SPF and bounce handling. Vendors have warmed IPs; your own SMTP lands in spam
Per-channel queuesKafka, SQS, RabbitMQDurable buffers with ack and redelivery. One topic per channel gives the §3 isolation
Seen-ID storeRedis with a TTL per keyFast lookup on every send; expiry bounds the set. A week at 16M/day is about 112M keys
Log, settings, devicesPostgreSQL or DynamoDBDurability matters more than raw speed at ~185 writes/s
MonitoringPrometheus + GrafanaAlert on queued count per channel. A rising SMS line with flat push and email lines is a vendor outage

Vendor names come from the chapter; the infrastructure choices are common industry picks, not prescriptions. In an interview, name the reason, not just the product.

Follow-upOne-line answer
How do scheduled notifications work (3)?A scheduler stores the send time and enqueues the event when due. The rest of the path is unchanged
The SMS vendor is down for six hours. Now what?The queue absorbs it while retries back off. For longer outages, fail over to a second vendor behind the same worker interface
Do you need ordering?No — (6) allows re-ordering, which is what lets you run many workers per queue with no coordination
How long do you keep seen IDs?Longer than the longest possible redelivery delay (retries plus backlog). A few days with a TTL
What if a device token is invalid?APNs and FCM report it. Delete the token — no retry will ever succeed, and you are paying for the attempt
A peak hits 10×. Scale servers or workers?Watch which queue grows and add workers for that channel only. Notification servers just enqueue and rarely bottleneck
Why not let services call vendors directly?Every service would reimplement settings, rate limits, retries and dedupe — and none would agree
How do you stop 10M marketing pushes delaying OTPs?Separate priority queues, so transactional traffic is never stuck behind bulk
Q&A

Check yourself


Q1An SMS vendor goes down. Over the next few minutes push and email throughput erodes and then stops completely, while SMS was only 6% of your volume. Which design are you looking at, and what is the mechanism?
  • Per-channel queues with dedupe turned off
  • One shared server: failing SMS calls burn its time on timeouts, so healthy channels starve
  • Too few device tokens
✓ One shared server — head-of-line blocking, compounding. Each failed SMS call holds a thread for the full timeout; the message becomes due again and costs the same next cycle. Because the SMS backlog only grows, an increasing share of a fixed capacity budget is spent on calls that cannot succeed, until none is left. The detail worth saying out loud is that the collapse is gradual and then total — which is exactly why it is missed in testing, where a short outage just looks like a small dip. Run the §3 simulator in shared mode: throughput erodes for about seven ticks and then pins at zero. Dedupe is unrelated; it affects correctness, not throughput.
Q2A user's phone buzzes twice for one shipping update even though dedupe is on. Where did the worker crash, and why can you not fix it?
  • Before calling the vendor
  • After the vendor accepted but before the ID was recorded
  • After recording the ID but before the ack
✓ After the vendor accepted, before the ID was recorded. That is the one gap dedupe cannot cover: the vendor delivered, but your seen-ID store never heard about it, so the redelivery looks brand new. A crash in option A delivers once on retry; a crash in option C is caught by the dedupe check. It is unfixable because the vendor call and the database write are two systems with no shared transaction — there is no atomic “send and record”. All you can do is make the window as narrow as possible.
Q3Dedupe is keyed on event_id alone, and the event fans out to three devices. What goes wrong, and how would you notice in production?
  • Nothing — the event is still sent once
  • After the first device succeeds, the other two are discarded as duplicates and never notified
  • Every device receives three copies
✓ Two of three devices are silently dropped. The key must identify the unit of delivery, which is one event to one device — event_id:token. Keyed on the event alone, the first successful send marks it seen and the rest are discarded as if they were retries. How you would notice: you probably would not, from logs — the discards look like healthy dedupe hits. The signal is a product one: users with multiple devices report that notifications only arrive on whichever device happens to win the race. The monitoring fix is to alert when the dedupe-discard rate rises, since legitimate duplicates should be rare.
Q4Your SMS vendor has a 6-hour outage. The queue absorbs 12 million messages. The vendor recovers. What do you do before letting the workers drain?
  • Nothing — drain at full speed, that is what the queue was for
  • Decide what is still worth sending, and throttle the drain so you do not overwhelm the recovering vendor
  • Purge the queue and start fresh
✓ Triage the backlog, then drain slowly. Two separate problems. Relevance: a “your code is 123456” SMS delivered six hours late is worse than useless — it is confusing and possibly a security signal. Time-sensitive messages need a TTL so they expire in the queue rather than being delivered stale; this is a real exception to “never lose a notification”, and you should name it as a deliberate product decision rather than pretend (6) is absolute. Thundering herd: a vendor that just came back will be knocked over again by 12 million queued messages arriving at once, so you rate-limit the drain to something near your normal send rate plus a margin. This question separates people who have operated a queue from people who have drawn one.
Q5Product wants a “breaking news” push to all 20 million users, delivered within two minutes. Your steady state is 116 push/s. What changes?
  • Add workers until the queue drains in two minutes
  • Add workers, but the real constraints are the fan-out write amplification, APNs/FCM rate limits, and keeping transactional pushes out of the way
  • It is impossible at that scale
✓ Add workers — and handle three things that bite before the workers do. 20M in 120s is roughly 170,000 sends/s, about 1,400× steady state. (a) Fan-out amplification: 20M users with ~1.5 devices each is ~30M queue entries, and generating them is itself a large batch job — you cannot enqueue them from a single request thread. (b) Vendor limits: APNs and FCM have their own throughput ceilings and will throttle you; you need multiple connections and to have negotiated the burst with them in advance. (c) Isolation: this bulk traffic must go on a separate queue from transactional pushes, or every password reset for the next two minutes queues behind a news alert — the same priority-queue answer as the OTP follow-up in §7. The usual honest conclusion is to push back on “two minutes” and negotiate a delivery window.
In practiceWhat production adds, and the questions that come next optional

This lesson covers the layer that decides an interview. Below it is the operational layer — the things that only show up once a system is running, and the questions that come if someone keeps pulling the thread. None of it is answered above.

Backpressure and queueing

  • Queue disciplines: FIFO vs. LIFO under overload, priority queues, and controlled delay (CoDel)
  • Shed vs. buffer vs. degrade: choosing per endpoint, and the client contract for each

Delivery semantics

  • Consumer-side transactional boundaries: commit offset before or after the side effect, and the consequence

Observability

  • The four golden signals / RED and USE methods as dashboard defaults

Terms used

Fan-out
One logical event becoming many deliveries — here, one event per device.
Head-of-line blocking
The item at the front of a queue stalling everything behind it, even work that would succeed.
At-least-once
Ack after the send. Nothing is lost; duplicates are possible.
At-most-once
Ack before the send. No duplicates; messages can be lost.
Exactly-once
Not achievable end to end across systems you do not control. At-least-once plus dedupe is the practical substitute.
Idempotency key
The identifier a dedupe check is keyed on. Must identify the unit of delivery, not the unit of intent.
Exponential backoff
Doubling the wait between retries, so a struggling vendor gets progressively fewer calls.
Jitter
Randomising the backoff so many workers do not retry in the same instant.
Dead-letter queue
Where a message goes after exhausting its retries. Parked for a human, not deleted.
Queue depth
Messages waiting in a queue. The single most informative metric in this design.

Where this leaves you. Eleven days in, you have the foundations (1–4) and six building blocks (5–11) that recur in almost every larger design. The patterns repeat: isolate failure domains, make the bad state unrepresentable rather than merely discouraged, and name the price of every guarantee you claim. Day 12 puts several of them together on a news feed — fan-out on write versus on read, which is this lesson's fan-out question asked at a much larger scale.

Source: System Design Interview, Ch. 10 — Design a notification system (pp. 151–165). The two simulators, the backlog-triage question and the broadcast-scale question are added here; the chapter states the isolation and duplicate-window results but does not demonstrate them.