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.
Outcomes
Six requirements, numbered, because every later decision points back at one of them:
| Channel | Per day | Average/s | Delivered by |
|---|---|---|---|
| Push | 10,000,000 | ~116 | APNs (iOS), FCM (Android) |
| SMS | 1,000,000 | ~12 | Twilio, Vonage |
| 5,000,000 | ~58 | SendGrid, Amazon SES | |
| Total | 16,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.
| Failure of the one-server design | Requirement 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 |
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.
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
| Channel | Waiting | Sent this tick | Sent total | |
|---|---|---|---|---|
| Push | 0 | 0 | 0 | |
| SMS | 0 | 0 | 0 | |
| 0 | 0 | 0 |
Press Run to start.
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 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
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).
The final design wraps the queues in guards. Each exists because of a specific requirement or failure, and each one costs something.
| Component | What it does | Price you pay |
|---|---|---|
| Notification log | Persists 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 error | A 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 ID | Discards an event whose ID was already sent | A 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 limiting | Caps how many notifications one user receives, because flooded users disable notifications entirely | Some legitimate messages get held or dropped — and you must decide which |
| Authentication | appKey / appSecret so only verified clients can send | Key distribution and rotation for every internal caller |
| Templates | Preformatted messages with parameters: “[ITEM] is back, until [DATE]” | A template store to version and cache |
| Queue monitoring | Watches queued count per channel; a rising number means add workers | Dashboards and alert thresholds to tune |
| Event tracking | Records pending, sent, delivered, click, unsubscribe, error; feeds analytics | More 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.
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.
ρ / (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.| Pattern | What it does | Why it belongs here |
|---|---|---|
| Circuit breaker | Three 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 queues | Every 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 degradation | Under 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. |
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:
enqueue, not in the workerAn opted-out user never costs queue space or a vendor call — the hot-path ordering from §5.
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.
event_id:token, not event_idIf 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.
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.
Parked, not deleted, so a human can inspect and replay it.
seen.add comes after the vendor callMove it before and a crash makes the system believe it sent something it did not. §4's trade-off, written as a line order.
| Role | Real service | Why it is there |
|---|---|---|
| iOS push | APNs | The 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 push | FCM | Google's equivalent. Unavailable in China, where Jpush or PushY are used — so design the worker to swap providers |
| SMS | Twilio, Vonage | Carrier relationships and per-country routing are a business, not a feature |
| SendGrid, Amazon SES | Deliverability depends on IP reputation, DKIM/SPF and bounce handling. Vendors have warmed IPs; your own SMTP lands in spam | |
| Per-channel queues | Kafka, SQS, RabbitMQ | Durable buffers with ack and redelivery. One topic per channel gives the §3 isolation |
| Seen-ID store | Redis with a TTL per key | Fast lookup on every send; expiry bounds the set. A week at 16M/day is about 112M keys |
| Log, settings, devices | PostgreSQL or DynamoDB | Durability matters more than raw speed at ~185 writes/s |
| Monitoring | Prometheus + Grafana | Alert 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-up | One-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 |
event_id alone, and the event fans out to three devices. What goes wrong, and how would you notice in production?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.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.
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.