Case study: design a notification service
A senior-level walkthrough of a notification platform: duplicates and the ledger, consent and quiet hours, priority lanes, provider failover, digests, and the traffic a campaign sends back to your own API, with tested C#.
Case studyApplied54 min readUpdated
- 1 architecture diagram
- 2 sequence flows
- 4 data models
- 2 API designs
- 11 code samples
- 9 interviewer follow-ups
- 4 self-checks
On this page18 sectionsHLDLLDSenior depth
Read first: A framework for system design interviews, Queues and asynchronous work, Rate limiting
- Make repeats harmless with an idempotency key, a claim with a lease and a guarantee chosen per kind, because an external effect cannot be exactly once.
- Decide whether and when before anything is queued, and check consent again just before the provider call.
- Give urgent traffic its own lane, take the class from the type and not from the caller, and bound every sender with a quota.
- Put a breaker in front of each provider and fail over before the call, because failing over after each timeout still falls behind.
- Spread campaigns over time, fold bursts into digests, and answer the senior follow-ups.
10 code samples (485 lines), collapsed so the explanation stays in focus.
A notification service looks like one function: send(user, message). That function is the easy part. The hard parts are around it: the same event arrives twice, a campaign and a login code want the same provider at the same moment, the SMS provider goes quiet, a user muted marketing an hour ago, and a push sent to twenty million phones brings a good share of those people to your own API within minutes. This lesson designs the service the way a senior round would: the high-level design (HLD) first, then the low-level design (LLD) with tested C#, then the follow-ups an interviewer uses to push.
It builds on queues and async work for delivery guarantees and retries and on rate limiting for the limiter in front of each provider. It is also the other half of the chat system, where a push is only a hint to reconnect and sync.
Spend the first minutes on questions. Each answer changes the design.
| Ask | Why it matters |
|---|---|
| Which channels: push, SMS, email, in-app? | Each differs in cost, speed, feedback and failure. Design the interface for all of them and scope the build to two or three |
| Who sends, and what kinds of message? | Service events (login codes, receipts), product events ("Ana replied") and campaigns to millions differ in volume and deadline, and must not share a queue |
| How late is too late, for each kind? | A login code is worthless after about a minute, a receipt can take five, a campaign has a deadline. That sets the lanes and the expiry |
| Which mistake is worse, a duplicate or a loss? | A text message cannot be exactly once. A login code may repeat, a promotion may not. Decide per kind |
| What can the user control? | Per-category opt-outs, channels, quiet hours, language and frequency. These are product rules and, in many countries, legal ones |
| Is per-message status needed? | Receipts are storage and webhook work. For some kinds "sent" is enough |
| Scheduled sends and time zones? | "9 am local" needs a delay mechanism and a time zone for every user |
| Who owns the content? | Templates with variables and locales, versioned, rendered at send time |
| Build or buy? | The providers (APNs, FCM, SMS aggregators, email services) are always bought. Below a few million messages a day a vendor for the orchestration is often cheaper than a team, and the design here is what that team would own |
Functional: accept a request from a service, a product event or a campaign; decide whether and when it may be sent; deliver it on push, SMS or email; honour opt-outs, quiet hours and caps; retry and fail over; report status. Non-functional: a login code within seconds, nothing marked critical lost, no duplicate promotions, a bounded delay for everything else, no single provider outage that stops a channel, and a send rate that both the providers and your own API can absorb. Out of scope: the campaign tool's interface, audience segmentation, ranking and send-time prediction models, and content creation. Paging engineers from monitoring alerts is a close cousin with its own grouping and inhibition problems, covered in the metrics monitoring case study.
State assumptions out loud; they are illustrative and the interviewer may change them.
users: 100M daily users, 8 notifications per user per day
volume: 800M a day = ~9,300/s on average, ~28,000/s at peak (x3)
channels: 90% push, 8% email, 2% SMS
campaign: one push to 20M users in 10 minutes = ~33,000/s
providers: each account takes a capped rate: theirs is the real limit
SMS bill: 16M a day at an illustrative $0.01 = $160,000 a day
open storm: 8% open, 6 requests each = 9.6M requests after one push
ledger: ~300 B x 800M = ~240 GB a day, 30 days kept = ~7 TBFour conclusions:
- The campaign is the sizing event, and the provider is the ceiling. The average, about 9,300 a second, is modest. A campaign of 20 million in ten minutes is 33,000 a second for ten minutes, while login codes must still arrive within seconds. Each provider account accepts a capped rate (often per credential, sender number or sending domain), so the real limit is a token bucket per provider account. It is the rate limiter turned around: here you are the traffic, and someone else's system needs protecting from you.
- Channels differ in what a mistake costs. Push is nearly free. Every SMS has a price, so a retry bug that doubles the sends doubles the bill. Email costs little per message but lives on a sender reputation that complaints damage. A duplicate is a billing problem on one channel and a deliverability problem on another.
- A push is a call to action, and the answer comes back to you. Within minutes of a large send, a lot of people open the app, and every open is several requests. That spike hits your own API, not the provider's. The stampede section measures it.
- The ledger is small and short-lived. About 240 GB a day, read mostly by notification ID or by user, so a key-value store partitioned by user fits. Thirty days is about 7 TB. Older history belongs in cold storage or an analytics pipeline, not in the send path.
The send path is one write. Everything else (preferences, devices, receipts) is small supporting CRUD.
| Call | Who calls it | Meaning |
|---|---|---|
POST /v1/notifications | Other services | Send one notification to one user. An idempotency key is required |
POST /v1/campaigns | Marketing tools | A job: an audience, a type, a window, a rate cap and an expiry |
PUT /v1/users/{id}/preferences | The app and the settings page | Opt-ins, quiet hours, time zone and locale |
POST /v1/users/{id}/devices | The app | Register or refresh a push token |
GET /v1/notifications/{id} | Support tools | Status and timeline: why did this user get it twice, or not at all |
POST /v1/webhooks/{provider} | Providers | Delivery receipts, bounces, complaints and replies such as STOP. Verify the provider's signature, timestamp and event id first (see encryption, secrets and abuse) |
- auth
- service token (names the sending team and its quota)
- idempotency
- Idempotency-Key header built from the business event (for example order-991/shipped), a retry returns the first notification
- body
- { "user_id": "u_42", "type": "login_code", "data": { "code": "481516" }, "expires_in": 300 }
- note
- the caller names a type, not a priority or a channel. The platform owns the table from type to class, lane, channels, template and guarantee
- 202accepted, returns { "id": "n_9f3a", "status": "queued" }
- 400unknown type, or the template needs a field that is missing
- 429this sender is over its quota for this class
- auth
- marketing token
- idempotency
- Idempotency-Key header
- body
- { "audience": "segment_184", "type": "promo", "local_time": "09:00", "rate_per_second": 8000, "expires_in": 21600 }
- note
- a large audience needs a second approver and starts with a canary of 1 percent
- 202accepted as a draft, returns { "id": "c_77", "status": "pending_approval" }
Notice what the caller does not send: a priority. If callers chose it, every team would choose "urgent". The class comes from the registered type, which the platform team owns, and each sender has a quota per class.
The ledger is read by ID and by user and is written at every stage, so it is a key-value store partitioned by user. Preferences are read on every send, so they sit behind a cache that is keyed by a version number.
user_idtext
PKSHARD KEYidtext
time-sortable, so a user's recent history is one range read
PKdedupe_keytext
sender plus Idempotency-Key, unique inside the user's shard
UNIQUEtypetext
login_code, order_update, promo ...
classtext
critical, normal or bulk: taken from the type, never from the caller
channeltext
stagetext
queued, sending, expired, sent, failed, delivered, opened
attemptsint
lease_untiltimestamptz
set while a worker holds the claim
NULLexpires_attimestamptz
after this the notification is never sent
provider_reftext
the provider's own message ID, used to match receipts
NULLcreated_attimestamptz
A worker claims with one conditional update. Keep 30 days, then archive.
user_idtext
PKSHARD KEYtimezonetext
an IANA name such as Asia/Kolkata, not a fixed offset
localetext
quiet_fromint
minutes after local midnight
quiet_untilint
mutedtext
the kinds the user turned off, per channel
versionbigint
bumped on every change, so caches and workers can tell it is stale
user_idtext
PKSHARD KEYtokentext
an APNs or FCM registration token
PKplatformtext
ios, android or web
last_seentimestamptz
refreshed when the app starts, so old tokens can be pruned
INDEXstatustext
active, or invalid after the provider said "unregistered"
idbigint
PKaudiencetext
typetext
statetext
draft, approved, running, paused, done or cancelled
rate_per_secondint
cursortext
how far audience expansion has got, so a restart resumes
NULLapproved_bytext
NULL
Workers read state before every chunk and again before every send, so pausing takes effect on queued messages.
Read it as a pipeline of decisions. The API validates the request and writes the first ledger row, where the unique idempotency key does the deduplication, then answers 202 so the producer never waits for a provider. Policy and routing decide whether and when (consent, quiet hours, caps, expiry), choose the channels, render the template in the user's language and pick the lane from the type. A lane is a queue plus a worker pool for one channel and one class. A worker claims the notification in the ledger, checks consent and expiry again, and calls the provider through an adapter behind a breaker. The adapter turns each provider's own errors into three answers a worker understands: sent, try later, or give up. Providers answer later through receipts, which only move the ledger forward.
Producers reach the API in one of two ways. They call it directly, which is explicit and gives the caller an ID and an error. Or they publish business events and the platform subscribes, which decouples teams but makes the platform learn every event schema. Many companies offer both: events for product notifications, the API for transactional ones. Either way, producers should publish through an outbox (see the queues lesson), so that a committed order always produces a request.
Duplicates are born in three places, and each needs its own defence.
| Where it is born | Example | Defence |
|---|---|---|
| The producer | A service times out calling POST /v1/notifications and calls again | An idempotency key that is unique in the ledger, so the second call returns the first notification |
| The queue | The broker redelivers because a worker was slow or died (at-least-once delivery) | A claim: a worker must win a conditional update from queued to sending before it may call a provider |
| The provider call | The worker sent the text, then died before it wrote sent | It cannot be closed completely. Narrow it, then choose per kind which mistake to risk |
The key must come from the business event, not from the call: order-991/shipped for the shipping notice, not a fresh random ID per attempt, because a new ID per attempt makes every retry look new. Keep keys longer than any caller will retry, a day or more. A queue's own deduplication is far too short to rely on: an SQS FIFO queue remembers a deduplication ID for five minutes.
The claim is one conditional write in the ledger, the atomic-update pattern from transactions and isolation levels. If it changes a row, this worker won. If it changes none, another worker holds the claim or the notification is done.
UPDATE notifications
SET stage = 'sending', attempts = attempts + 1,
lease_until = :now + :lease
WHERE user_id = :user AND id = :id
AND (stage = 'queued'
OR (stage = 'sending' AND lease_until <= :now))
-- one row changed: send. none: another worker has it, or it is doneA worker that dies never writes sent. Its lease runs out, and the next delivery of the queue message can claim the notification again. What should happen then is the third row of the table, and it is where exactly-once ends: a provider call has an external effect, and a timeout cannot tell you whether the text left. So the choice is made per kind, when the type is registered.
- At least once for a login code or a security alert. A second copy costs a little, and a missing one locks someone out. After a lapsed lease the claim is granted again.
- At most once for a promotion or a social nudge. A second copy is a complaint, and a missing one costs nothing. After a lapsed lease the notification is marked failed and never retried.
Push offers a cheap extra defence. Send the notification ID as the collapse key (apns-collapse-id for APNs, the collapse key in the FCM message) and a duplicate that does reach the phone replaces the first instead of showing twice, as long as the content is replaceable. Set an expiry as well (apns-expiration for APNs, the time-to-live setting for FCM), so a push service does not hold a stale message for a phone that is off. FCM keeps an undelivered message for up to four weeks by default, which is far too long for a login code.
C# · The order of Stage is a ladder: a report can only move a notification up (see Receipt).
using System;
using System.Collections.Generic;
// The order of Stage is a ladder: a report can only move a notification up (see Receipt).
public enum Stage { Queued, Sending, Expired, Sent, Failed, Delivered, Opened }
public enum Guarantee { AtLeastOnce, AtMostOnce }
public enum Claim { Granted, Busy, AlreadyDone, Expired, GaveUp }
public sealed class Notification
{
public string Id { get; set; }
public string Kind { get; set; }
public Guarantee Guarantee { get; set; }
public long ExpiresAt { get; set; }
public Stage Stage { get; set; } = Stage.Queued;
public int Attempts { get; set; }
public long LeaseUntil { get; set; }
}
public sealed class Ledger
{
private readonly Dictionary<string, Notification> _byKey = new Dictionary<string, Notification>();
public int Count => _byKey.Count;
/// <summary>The producer's call. The same idempotency key always returns the first notification.</summary>
public Notification Accept(string key, string kind, Guarantee guarantee, long expiresAt, out bool duplicate)
{
duplicate = _byKey.TryGetValue(key, out var existing);
if (duplicate) return existing;
var made = new Notification { Id = "n" + (_byKey.Count + 1), Kind = kind, Guarantee = guarantee, ExpiresAt = expiresAt };
_byKey[key] = made; // in production: a unique index on (sender, key)
return made;
}
/// <summary>A worker asks for the right to send. In production this is the one conditional UPDATE above.</summary>
public Claim TryClaim(Notification n, long now, long leaseMs)
{
if (n.Stage >= Stage.Expired) return Claim.AlreadyDone; // expired, sent, failed, delivered or opened
if (now >= n.ExpiresAt) { n.Stage = Stage.Expired; return Claim.Expired; } // late is worse than never
if (n.Stage == Stage.Sending)
{
if (now < n.LeaseUntil) return Claim.Busy; // another worker is on it
if (n.Guarantee == Guarantee.AtMostOnce) { n.Stage = Stage.Failed; return Claim.GaveUp; } // it may have gone out: no second copy
}
n.Stage = Stage.Sending;
n.Attempts++;
n.LeaseUntil = now + leaseMs;
return Claim.Granted;
}
public void Complete(Notification n) { if (n.Stage == Stage.Sending) n.Stage = Stage.Sent; }
/// <summary>A transient error: give the claim back so the retry policy can try again.</summary>
public void Release(Notification n) { if (n.Stage == Stage.Sending) n.Stage = Stage.Queued; }
/// <summary>A permanent error (a dead token, a number that does not exist): final.</summary>
public void Fail(Notification n) { if (n.Stage <= Stage.Sending) n.Stage = Stage.Failed; }
/// <summary>A provider webhook. Duplicated, late and out of order is normal, so a report only ever moves a notification up.</summary>
public void Receipt(Notification n, Stage reported)
{
if (reported > n.Stage) n.Stage = reported;
}
}The driver walks through each rule: a retried producer call, two workers racing, a crash with both guarantees, an expired notification, out-of-order receipts, and a campaign chunk that is run twice.
C#
using System.Diagnostics;
var ledger = new Ledger();
const long Min = 60_000;
var shipped1 = ledger.Accept("order-991/shipped", "social", Guarantee.AtLeastOnce, 10 * Min, out bool dup1);
var shipped2 = ledger.Accept("order-991/shipped", "social", Guarantee.AtLeastOnce, 10 * Min, out bool dup2);
Debug.Assert(!dup1 && dup2 && shipped1.Id == shipped2.Id && ledger.Count == 1, "the same idempotency key returns the first notification");
Debug.Assert(ledger.TryClaim(shipped1, now: 1_000, leaseMs: 30_000) == Claim.Granted);
Debug.Assert(ledger.TryClaim(shipped1, now: 2_000, leaseMs: 30_000) == Claim.Busy, "a second worker backs off while the lease is live");
ledger.Complete(shipped1);
Debug.Assert(ledger.TryClaim(shipped1, now: 40_000, leaseMs: 30_000) == Claim.AlreadyDone, "once sent, a redelivered queue message does nothing");
var code = ledger.Accept("otp/u42/1", "otp", Guarantee.AtLeastOnce, 5 * Min, out _);
var promo = ledger.Accept("promo-7/u42", "promo", Guarantee.AtMostOnce, 60 * Min, out _);
ledger.TryClaim(code, now: 0, leaseMs: 30_000); // both workers crash after claiming
ledger.TryClaim(promo, now: 0, leaseMs: 30_000);
Debug.Assert(ledger.TryClaim(code, now: 31_000, leaseMs: 30_000) == Claim.Granted && code.Attempts == 2, "a login code is sent again, accepting a possible duplicate");
Debug.Assert(ledger.TryClaim(promo, now: 31_000, leaseMs: 30_000) == Claim.GaveUp && promo.Stage == Stage.Failed, "a promotion is dropped rather than risk a second copy");
ledger.Receipt(promo, Stage.Delivered);
Debug.Assert(promo.Stage == Stage.Delivered, "the abandoned promotion did go out, and the provider's receipt corrects the record");
var ride = ledger.Accept("ride-5/arriving", "social", Guarantee.AtLeastOnce, 2 * Min, out _);
Debug.Assert(ledger.TryClaim(ride, now: 3 * Min, leaseMs: 30_000) == Claim.Expired && ride.Stage == Stage.Expired, "past its expiry it is never sent");
var invoice = ledger.Accept("invoice-1", "social", Guarantee.AtLeastOnce, 10 * Min, out _);
ledger.TryClaim(invoice, 0, 30_000);
ledger.Receipt(invoice, Stage.Delivered); // the webhook beat the worker's own write ...
ledger.Complete(invoice); // ... which therefore changes nothing
ledger.Receipt(invoice, Stage.Sent); // and a stale duplicate cannot move the status back
Debug.Assert(invoice.Stage == Stage.Delivered, "receipts only move a notification up");
ledger.Receipt(invoice, Stage.Opened);
Debug.Assert(invoice.Stage == Stage.Opened);
var flaky = ledger.Accept("flaky-1", "social", Guarantee.AtLeastOnce, 10 * Min, out _);
ledger.TryClaim(flaky, 0, 30_000);
ledger.Release(flaky);
Debug.Assert(ledger.TryClaim(flaky, 1_000, 30_000) == Claim.Granted && flaky.Attempts == 2, "a transient error gives the claim back for the next attempt");
ledger.Fail(flaky);
Debug.Assert(ledger.TryClaim(flaky, 2_000, 30_000) == Claim.AlreadyDone, "a permanent error is final");
int before = ledger.Count;
for (int pass = 0; pass < 2; pass++) // a crashed chunk is simply run again
foreach (var member in new[] { "u1", "u2", "u3" })
ledger.Accept("campaign-9/" + member, "promo", Guarantee.AtMostOnce, 60 * Min, out _);
Debug.Assert(ledger.Count == before + 3, "a campaign chunk that runs twice creates each notification once");Receipts only move a notification up
Providers report back later: accepted, delivered, bounced, opened. Those webhooks are duplicated, delayed and out of order, and one can arrive before the worker has written its own sent. The fix is the one the chat lesson used for read receipts: make the order of the stages a ladder and merge with max. In the sample the Stage enum is declared in ladder order, so Receipt is a single comparison. A bounce after sent moves a notification up to failed. A late delivered outranks an earlier failed, because proof of delivery beats a guess that it was lost.
Treat silence as unknown, not as failed. A push service tells you it accepted a message, not that the phone showed it. SMS delivery receipts depend on the carrier and the country. Email open tracking is unreliable because mail apps can prefetch images. So build any fallback ("no reaction in ten minutes, send an email") on your own signals, such as the app reporting that it opened, and not on the absence of a provider receipt.
Everything so far makes sending safe. Policy decides whether sending is wanted, and when. It runs twice: when the notification is accepted, so a muted one never takes a queue slot, and again in the worker, just before the provider call. The second run is the one that matters for consent. A campaign can sit in a lane for an hour, and a user who unsubscribed ten minutes ago must not receive it.
The rules run in a fixed order, and the order is part of the design.
| Order | Rule | Result |
|---|---|---|
| 1 | Is the channel itself suppressed: a number that replied STOP, an address that bounced, a dead token? | Skip that channel for every kind, critical included. The provider would refuse it anyway |
| 2 | Is the kind critical: a login code, a security alert, a receipt? | Send now. It ignores quiet hours and caps |
| 3 | Has the user muted this kind on this channel? | Drop. Consent comes before everything else |
| 4 | Is it quiet hours in the user's own time zone? | Defer until they end, unless the notification would expire first, and then drop it |
| 5 | Is the user over the daily cap for this kind? | Drop, or fold it into a digest |
The sample is a pure function of the user's preferences, the clock and a small history, which makes every rule testable. Two details deserve a test of their own. Quiet hours that wrap past midnight (22:00 to 08:00) are a classic bug, because "after the start" and "before the end" are joined by or, not and. And a deferral must respect the expiry: a "your driver is arriving" message that would be sent at eight the next morning is not delayed, it is dropped.
C# · Verdict, Decision, KindRule, …
using System;
using System.Collections.Generic;
public enum Verdict { Send, Defer, Drop }
public readonly record struct Decision(Verdict Verdict, string Reason, long SendAt);
public readonly record struct KindRule(bool Critical, int DailyCap);
public sealed class Preferences
{
public HashSet<string> MutedKinds { get; } = new HashSet<string>();
public int OffsetMinutes { get; set; } // a fixed offset keeps the sample deterministic; production stores the zone name
public int QuietFrom { get; set; } = 22 * 60; // minutes after local midnight: from 22:00 ...
public int QuietUntil { get; set; } = 8 * 60; // ... until 08:00
}
public sealed class PolicyEngine
{
private const long Minute = 60_000, Day = 24 * 60 * Minute;
private readonly Dictionary<string, KindRule> _rules;
private readonly Dictionary<string, Queue<long>> _recent = new Dictionary<string, Queue<long>>(); // "user/kind" -> decisions in the last day
public PolicyEngine(Dictionary<string, KindRule> rules) { _rules = rules; }
public Decision Decide(string user, string kind, Preferences prefs, long now, long expiresAt)
{
var rule = _rules[kind];
if (rule.Critical) return new Decision(Verdict.Send, "critical", now); // a login code ignores quiet hours and caps
if (prefs.MutedKinds.Contains(kind)) return new Decision(Verdict.Drop, "muted", 0); // consent comes before everything else
long at = QuietEnd(prefs, now); // equals now when it is not quiet
if (at >= expiresAt) return new Decision(Verdict.Drop, "would expire during quiet hours", 0);
var sent = Recent(user, kind, now);
if (sent.Count >= rule.DailyCap) return new Decision(Verdict.Drop, "daily cap", 0);
sent.Enqueue(now); // counted when decided: slightly conservative
return at > now ? new Decision(Verdict.Defer, "quiet hours", at) : new Decision(Verdict.Send, "ok", now);
}
/// <summary>The first moment at or after `now` that is outside the user's quiet hours.</summary>
private static long QuietEnd(Preferences p, long now)
{
if (p.QuietFrom == p.QuietUntil) return now; // no quiet hours
long local = now + p.OffsetMinutes * Minute;
int minuteOfDay = (int)(((local / Minute) % 1440 + 1440) % 1440);
bool quiet = p.QuietFrom < p.QuietUntil
? minuteOfDay >= p.QuietFrom && minuteOfDay < p.QuietUntil
: minuteOfDay >= p.QuietFrom || minuteOfDay < p.QuietUntil; // the window wraps past midnight
if (!quiet) return now;
int wait = (p.QuietUntil - minuteOfDay + 1440) % 1440;
return now - now % Minute + wait * Minute;
}
private Queue<long> Recent(string user, string kind, long now)
{
string key = user + "/" + kind;
if (!_recent.TryGetValue(key, out var q)) _recent[key] = q = new Queue<long>();
while (q.Count > 0 && q.Peek() <= now - Day) q.Dequeue(); // a rolling 24 hours, not a calendar day
return q;
}
}C#
using System.Collections.Generic;
using System.Diagnostics;
var rules = new Dictionary<string, KindRule>
{
["otp"] = new KindRule(Critical: true, DailyCap: int.MaxValue),
["social"] = new KindRule(Critical: false, DailyCap: 20),
["promo"] = new KindRule(Critical: false, DailyCap: 2),
};
var policy = new PolicyEngine(rules);
var asha = new Preferences { OffsetMinutes = 330 }; // UTC+5:30, quiet from 22:00 to 08:00 local
long dayStart = 20_000L * 86_400_000L;
long Utc(int hour, int minute) => dayStart + (hour * 60L + minute) * 60_000L;
const long Hr = 3_600_000;
var afternoon = policy.Decide("asha", "social", asha, Utc(9, 30), Utc(9, 30) + Hr);
Debug.Assert(afternoon.Verdict == Verdict.Send, "3:00 pm local: send now");
var lateNight = policy.Decide("asha", "promo", asha, Utc(18, 0), Utc(18, 0) + 24 * Hr);
Debug.Assert(lateNight.Verdict == Verdict.Defer && lateNight.SendAt == Utc(26, 30), "11:30 pm local: held until 8:00 am local");
var almost = policy.Decide("asha", "social", asha, Utc(2, 29), Utc(2, 29) + 24 * Hr);
Debug.Assert(almost.Verdict == Verdict.Defer && almost.SendAt == Utc(2, 30), "7:59 am local: one minute to wait");
var morning = policy.Decide("asha", "social", asha, Utc(2, 30), Utc(2, 30) + 24 * Hr);
Debug.Assert(morning.Verdict == Verdict.Send, "8:00 am local: quiet hours are over");
var login = policy.Decide("asha", "otp", asha, Utc(21, 30), Utc(21, 30) + 5 * 60_000);
Debug.Assert(login.Verdict == Verdict.Send && login.SendAt == Utc(21, 30), "a login code at 3:00 am local goes out at once");
var arriving = policy.Decide("asha", "social", asha, Utc(17, 30), Utc(17, 30) + 10 * 60_000);
Debug.Assert(arriving.Verdict == Verdict.Drop, "11:00 pm local, and the news expires at 11:10 pm: waiting until morning would make it wrong, so it is dropped");
var ben = new Preferences();
ben.MutedKinds.Add("promo");
Debug.Assert(policy.Decide("ben", "promo", ben, Utc(12, 0), Utc(12, 0) + 24 * Hr).Verdict == Verdict.Drop, "a muted kind is never sent");
var cy = new Preferences();
var first = policy.Decide("cy", "promo", cy, Utc(12, 0), Utc(12, 0) + 24 * Hr);
var second = policy.Decide("cy", "promo", cy, Utc(13, 0), Utc(13, 0) + 24 * Hr);
var third = policy.Decide("cy", "promo", cy, Utc(14, 0), Utc(14, 0) + 24 * Hr);
var nextDay = policy.Decide("cy", "promo", cy, Utc(12, 0) + 25 * Hr, Utc(12, 0) + 49 * Hr);
Debug.Assert(first.Verdict == Verdict.Send && second.Verdict == Verdict.Send, "two promotions a day are fine");
Debug.Assert(third.Verdict == Verdict.Drop && third.Reason == "daily cap", "the third is over the cap");
Debug.Assert(nextDay.Verdict == Verdict.Send, "the window is rolling: a day later it is allowed again");Time zones are data, not arithmetic
The sample uses a fixed offset so that it is deterministic. Production stores the zone name (Asia/Kolkata, Europe/Berlin) and converts at decision time with a time zone library, because a fixed offset is wrong for half the year wherever daylight saving applies. Test the two changeover days. People also travel and phones change zones, so take the zone from the account setting or the device that last reported, and let the user override it.
Who decides across channels
When each product team sends on its own, a user gets the same news on push, email and SMS and a stream of unrelated ones. LinkedIn's engineering team described moving to a central decision-maker, Air Traffic Controller, that sees every notification which could go to a member and chooses what to send using the member's settings and history. You do not need that scale to take the idea: policy belongs in one place that sees all the candidates for a user, not in each sender.
A queue per channel is not enough. Within one channel the promises differ: a login code in seconds, an order update in a minute, a campaign by its deadline. Give each class its own lane: its own queue, its own workers and, where the provider throttles per account, its own credentials or sender pool, so that a throttled campaign cannot throttle login codes.
The simulation uses one provider that accepts 5,000 messages a second and three lanes: critical (login codes), normal (order updates) and bulk (a campaign). It compares three ways to share the provider.
- One queue. Everything waits in arrival order.
- Strict priority. Critical first, then normal, then bulk.
- Reserved shares. Each lane is guaranteed a share of the capacity (40%, 20% and 10%) whenever it has a backlog. Whatever is left goes to the highest priority first.
C# · Scheduling, LaneResult, LaneSim, …
using System;
using System.Collections.Generic;
public enum Scheduling { OneQueue, StrictPriority, Reserved }
public sealed class LaneResult
{
public int[] Sent = new int[3]; // per lane: critical, normal, bulk
public int[] LongestWait = new int[3]; // seconds, counting messages still queued when the run ends
public int[] Left = new int[3];
}
public static class LaneSim
{
public const int Critical = 0, Normal = 1, Bulk = 2;
private static readonly double[] Floors = { 0.40, 0.20, 0.10 }; // each lane's guaranteed share of the capacity
private sealed class Batch { public int Lane, Arrived, Count; }
/// <summary>One tick is one second. The provider accepts `capacity` messages a second; `arrivals(lane, second)` joins each queue.</summary>
public static LaneResult Run(Scheduling mode, int capacity, int seconds, Func<int, int, int> arrivals)
{
var result = new LaneResult();
var queues = new LinkedList<Batch>[mode == Scheduling.OneQueue ? 1 : 3];
for (int q = 0; q < queues.Length; q++) queues[q] = new LinkedList<Batch>();
for (int now = 0; now < seconds; now++)
{
for (int lane = 0; lane < 3; lane++)
{
int joined = arrivals(lane, now);
if (joined > 0) queues[mode == Scheduling.OneQueue ? 0 : lane].AddLast(new Batch { Lane = lane, Arrived = now, Count = joined });
}
int budget = capacity;
if (mode == Scheduling.OneQueue) Send(queues[0], ref budget, int.MaxValue, now, result);
else
{
if (mode == Scheduling.Reserved) // first each lane's guaranteed share ...
for (int lane = 0; lane < 3; lane++) Send(queues[lane], ref budget, (int)(capacity * Floors[lane]), now, result);
for (int lane = 0; lane < 3; lane++) Send(queues[lane], ref budget, int.MaxValue, now, result); // ... then the rest, highest priority first
}
}
foreach (var queue in queues)
foreach (var batch in queue)
{
result.Left[batch.Lane] += batch.Count;
result.LongestWait[batch.Lane] = Math.Max(result.LongestWait[batch.Lane], seconds - batch.Arrived);
}
return result;
}
private static void Send(LinkedList<Batch> queue, ref int budget, int limit, int now, LaneResult result)
{
limit = Math.Min(limit, budget);
while (limit > 0 && queue.First != null)
{
var batch = queue.First.Value;
int take = Math.Min(limit, batch.Count);
result.Sent[batch.Lane] += take;
result.LongestWait[batch.Lane] = Math.Max(result.LongestWait[batch.Lane], now - batch.Arrived);
batch.Count -= take; limit -= take; budget -= take;
if (batch.Count == 0) queue.RemoveFirst();
}
}
}The first experiment is the everyday one. A campaign of a million messages is queued at second 0, and from second 1 login codes (100 a second) and order updates (1,000 a second) keep arriving. The second experiment adds a bug: one sender marks 6,000 extra messages a second as critical for 30 seconds. The third applies the fix, a quota of 500 a second for that sender, refused with a 429 at the door.
C#
using System;
using System.Diagnostics;
int Campaign(int lane, int second) => lane switch
{
LaneSim.Critical => second >= 1 ? 100 : 0,
LaneSim.Normal => second >= 1 ? 1_000 : 0,
_ => second == 0 ? 1_000_000 : 0,
};
var shared = LaneSim.Run(Scheduling.OneQueue, 5_000, 300, Campaign);
var strict = LaneSim.Run(Scheduling.StrictPriority, 5_000, 300, Campaign);
var reserved = LaneSim.Run(Scheduling.Reserved, 5_000, 300, Campaign);
Debug.Assert(shared.LongestWait[LaneSim.Critical] is >= 195 and <= 205, "behind the campaign, a login code waits about 200 seconds");
Debug.Assert(strict.LongestWait[LaneSim.Critical] == 0 && reserved.LongestWait[LaneSim.Critical] == 0, "in its own lane it does not wait");
Debug.Assert(shared.Left[LaneSim.Bulk] == 0 && strict.Left[LaneSim.Bulk] == 0, "all three send the whole campaign");
Debug.Assert(shared.LongestWait[LaneSim.Bulk] is >= 195 and <= 205 && strict.LongestWait[LaneSim.Bulk] is >= 250 and <= 260,
"the campaign finishes about a minute later (256 s, not 199 s): the same capacity, reordered");
// A buggy sender adds 6,000 "critical" messages a second between seconds 10 and 39.
int Buggy(int lane, int second) => lane == LaneSim.Critical && second is >= 10 and < 40 ? Campaign(lane, second) + 6_000 : Campaign(lane, second);
var buggyStrict = LaneSim.Run(Scheduling.StrictPriority, 5_000, 60, Buggy);
var buggyReserved = LaneSim.Run(Scheduling.Reserved, 5_000, 60, Buggy);
Debug.Assert(buggyStrict.LongestWait[LaneSim.Normal] is >= 30 and <= 40, "strict priority: order updates starve behind the flood for about 36 seconds");
Debug.Assert(buggyReserved.LongestWait[LaneSim.Normal] == 0, "reserved shares: they keep their guaranteed rate");
Debug.Assert(buggyStrict.LongestWait[LaneSim.Critical] is >= 5 and <= 10 && buggyReserved.LongestWait[LaneSim.Critical] is >= 18 and <= 26,
"but the flooded lane itself waits longer with reserved shares (about 22 s against 7 s), because it gave up part of the capacity");
// The fix is at the door: that sender is limited to 500 a second and the rest is refused.
int Limited(int lane, int second) => lane == LaneSim.Critical && second is >= 10 and < 40 ? Campaign(lane, second) + 500 : Campaign(lane, second);
var limitedStrict = LaneSim.Run(Scheduling.StrictPriority, 5_000, 60, Limited);
var limitedReserved = LaneSim.Run(Scheduling.Reserved, 5_000, 60, Limited);
Debug.Assert(limitedStrict.LongestWait[LaneSim.Critical] == 0 && limitedStrict.LongestWait[LaneSim.Normal] == 0, "with a quota nobody waits under strict priority");
Debug.Assert(limitedReserved.LongestWait[LaneSim.Critical] == 0 && limitedReserved.LongestWait[LaneSim.Normal] == 0, "or under reserved shares");| Measure | One queue | Strict priority | Reserved shares |
|---|---|---|---|
| 1. Login code, longest wait | 199 s | 0 s | 0 s |
| 1. Campaign finishes after | 199 s | 256 s | 256 s |
| 2. Flood: login code wait | not run | 7 s | 22 s |
| 2. Flood: order update wait | not run | 36 s | 0 s |
| 3. Flood capped at 500 a second: any wait | not run | none | none |
Five things follow from the table.
- Lanes reorder work, they do not create capacity. The campaign finishes about a minute later (256 s instead of 199 s) because login codes and order updates took their share first. The total sent is the same. That minute is the price of the isolation, and it is almost always worth paying.
- Strict priority has a failure of its own. When the top lane floods, every lane below it starves. Here order updates waited 36 seconds behind a 30-second flood.
- Reserved shares trade one problem for another. Floors protect the middle and bottom lanes, and the price is paid by the flooded lane, whose own login codes now wait longer. When nobody floods, the two behave identically (experiment 1), so the floors cost nothing in the normal case.
- Only admission control makes the waiting disappear. Scheduling decides who waits when demand exceeds capacity. A quota per sender and class, enforced at the API with the token bucket from the rate limiting lesson, keeps the demand under the capacity in the first place.
- "Who says urgent" is a design decision. If callers choose the priority, "urgent" inflates until it means nothing. The class comes from the registered type, and a new type in the critical class needs a review. Google's SRE book describes the same idea as criticality levels that decide what is shed first under overload.
Measure each lane's queue age (the age of the oldest waiting message), not its depth. A deep queue that is draining is fine, and a shallow one whose oldest message is two minutes old is an outage for the people in it.
Providers fail in different ways, and the adapter's job is to turn each failure into one of three answers.
| What came back | Meaning | Action |
|---|---|---|
| Accepted | Ok | Record sent, then wait for receipts |
| A timeout, a reset connection or a 5xx | Transient, and ambiguous (the message may have gone out) | Retry later with exponential backoff and jitter, within the notification's expiry. Counts toward the breaker |
| A 429 or a "slow down" | Transient, but about your rate and not the provider's health | Slow the lane's limiter, honour Retry-After. Does not trip the breaker |
| An invalid number, a dead token, a hard bounce, a STOP reply | Permanent | Never retry. Fix the source of truth: delete the token, suppress the address or number |
The first defence against a failing provider is not to wait on it. A circuit breaker counts recent transient failures. After a few it opens and fails calls immediately. After a cooldown it lets one call through as a probe, and the probe's result closes it or reopens it (see Martin Fowler's description).
The second defence is a backup provider, and the sample shows why the two belong together. Two minutes of traffic at 200 messages a second go through 100 workers. The primary provider is down from second 30 to second 90, and a call to it times out after two seconds. The backup answers in 100 ms. Every message that hits a timeout, or an open breaker, goes to the backup. A message is late if it takes more than 30 seconds.
C# · Outcome, CircuitBreaker, FailoverSim, …
using System;
using System.Collections.Generic;
public enum Outcome { Ok, Transient, Permanent }
public sealed class CircuitBreaker
{
private readonly int _threshold;
private readonly long _cooldownMs;
private int _failures;
private long _openedAt = -1; // -1 means closed
private bool _probing; // half-open: one trial call is out
public CircuitBreaker(int threshold, long cooldownMs) { _threshold = threshold; _cooldownMs = cooldownMs; }
public bool IsOpen => _openedAt >= 0;
public bool Allow(long now)
{
if (_openedAt < 0) return true; // closed: calls flow
if (now - _openedAt < _cooldownMs || _probing) return false; // open, or a probe is already out: fail fast
_probing = true; // half-open: exactly one call tests the provider
return true;
}
public void Record(Outcome outcome, long now)
{
if (outcome != Outcome.Transient) { _failures = 0; _openedAt = -1; _probing = false; return; } // the provider answered, even if it said no
if (_probing || ++_failures >= _threshold) { _openedAt = now; _probing = false; } // open, or stay open
}
}
public static class FailoverSim
{
public readonly record struct Result(int Messages, int OnTime, int TimedOutCalls, long WorstWaitMs, bool BreakerOpenAtEnd);
public static Result Run(bool useBreaker)
{
const int Workers = 100, PerSecond = 200, Seconds = 120;
const long OutageFrom = 30_000, OutageTo = 90_000, CallMs = 100, TimeoutMs = 2_000, DeadlineMs = 30_000;
var breaker = new CircuitBreaker(threshold: 5, cooldownMs: 10_000);
var free = new long[Workers]; // when each worker is next idle
var unheard = new PriorityQueue<Outcome, long>(); // results the breaker has not seen yet, by completion time
int onTime = 0, timeouts = 0;
long worst = 0;
int total = PerSecond * Seconds;
for (int n = 0; n < total; n++)
{
long arrived = n * 1000L / PerSecond;
int w = 0;
for (int k = 1; k < Workers; k++) if (free[k] < free[w]) w = k; // the worker that frees up first
long start = Math.Max(free[w], arrived);
while (unheard.TryPeek(out var heard, out long heardAt) && heardAt <= start) { unheard.Dequeue(); breaker.Record(heard, heardAt); }
bool primaryDown = start >= OutageFrom && start < OutageTo;
long done;
if (useBreaker && !breaker.Allow(start)) done = start + CallMs; // the breaker is open: straight to the backup
else if (!primaryDown) { done = start + CallMs; unheard.Enqueue(Outcome.Ok, done); }
else { timeouts++; done = start + TimeoutMs + CallMs; unheard.Enqueue(Outcome.Transient, start + TimeoutMs); } // wait out the timeout, then the backup
free[w] = done;
if (done - arrived <= DeadlineMs) onTime++;
worst = Math.Max(worst, done - arrived);
}
return new Result(total, onTime, timeouts, worst, breaker.IsOpen);
}
}using System.Diagnostics;
var withoutBreaker = FailoverSim.Run(useBreaker: false);
var withBreaker = FailoverSim.Run(useBreaker: true);
Debug.Assert(withoutBreaker.OnTime is > 17_000 and < 20_000, "failing over after every timeout still leaves about a fifth of the messages late");
Debug.Assert(withoutBreaker.TimedOutCalls > 2_500 && withoutBreaker.WorstWaitMs > 40_000, "because nearly every message first waits out the 2 s timeout, and the workers fall behind");
Debug.Assert(withBreaker.OnTime == withBreaker.Messages && withBreaker.WorstWaitMs < 3_000, "with a breaker nothing is late");
Debug.Assert(withBreaker.TimedOutCalls == 104, "100 calls were already in flight when the outage began, plus one probe every 10 seconds");
Debug.Assert(!withBreaker.BreakerOpenAtEnd, "the first probe after the outage succeeds and closes the breaker");| Failover only | Breaker and failover | |
|---|---|---|
| Messages on time (within 30 s) | 78% (18,726 of 24,000) | 100% |
| Calls that waited out the 2 s timeout | 2,900 | 104 |
| Longest wait | 46.9 s | 2.1 s |
Failover alone still loses because the timeout is the expensive part. Each worker is stuck for two seconds per message, so 100 workers can finish only about 48 messages a second against 200 arriving, and the backlog grows for the whole outage. The breaker removes the wait: after the first few failures nothing is sent to the dead provider, and the cost is the 100 calls already in flight plus four probes. It is also a bulkhead argument for a lane and a worker pool per channel, so that one slow provider cannot consume every worker.
A few things to say aloud:
- Fail over before the call, not after a timeout. A timeout is ambiguous: the first provider may have sent the message. Sending it again through the second provider can deliver two copies. When the breaker is already open, nothing was sent to the primary, so routing to the backup is safe. For a login code you can accept the rare duplicate after a timeout. For a promotion, retry the same provider with the same key, or drop it. This is the guarantee from the ledger again.
- Keep the backup warm. A provider you never use is a provider that does not work when you need it. Send a few percent of traffic through the backup all the time, so its credentials, registered sender IDs and reputation are real. A cold email IP address that suddenly carries a whole channel's volume is likely to be throttled or filtered.
- Production breakers use a window. They track the failure rate over recent calls with a minimum volume, not a count of consecutive failures, and they treat a throttle response (429) as a signal to slow down rather than as a failure.
- Retries are budgeted. The attempts are capped, the delays have jitter, and the retry stops at the notification's expiry. See tail latency and overload for retry budgets and why retries at several layers multiply.
The kindest notification is the one you do not send. A post that gets a thousand likes in a minute should not buzz a thousand times. The standard pattern is a leading edge with a trailing summary: the first event goes out at once, later events for the same target are folded into a window, and when the window ends one summary goes out ("Ben, Cy and 997 others liked your post"). The target then gets at most one message per window, however busy the post is.
C# · Digest, Window
using System;
using System.Collections.Generic;
public sealed class Digest
{
private sealed class Window
{
public long EndsAt;
public string What;
public HashSet<string> Seen = new HashSet<string>(); // everyone counted so far, including the one already told
public List<string> Pending = new List<string>(); // new people since the last message
}
private readonly long _windowMs;
private readonly Dictionary<string, Window> _open = new Dictionary<string, Window>(); // "recipient/post" -> window
public Digest(long windowMs) { _windowMs = windowMs; }
/// <summary>The text to send right now, or null when the event was folded into the open window.</summary>
public string Offer(string target, string actor, string what, long now)
{
if (!_open.TryGetValue(target, out var w))
{
_open[target] = new Window { EndsAt = now + _windowMs, What = what, Seen = { actor } };
return Text(new List<string> { actor }, what); // the first event goes out at once
}
if (w.Seen.Add(actor)) w.Pending.Add(actor); // the same person twice is not news
return null;
}
/// <summary>Summaries that are due. Call it from a timer. Each target gets at most one message per window.</summary>
public List<(string Target, string Text)> Flush(long now)
{
var due = new List<(string Target, string Text)>();
foreach (var target in new List<string>(_open.Keys))
{
var w = _open[target];
if (now < w.EndsAt) continue;
if (w.Pending.Count == 0) { _open.Remove(target); continue; } // quiet again: forget the target
due.Add((target, Text(w.Pending, w.What)));
w.Pending = new List<string>();
w.EndsAt = now + _windowMs; // the next summary is a window away
}
return due;
}
private static string Text(List<string> actors, string what) => actors.Count switch
{
1 => actors[0] + " " + what,
2 => actors[0] + " and " + actors[1] + " " + what,
_ => actors[0] + ", " + actors[1] + " and " + (actors.Count - 2) + " others " + what,
};
}C#
using System.Diagnostics;
var digest = new Digest(windowMs: 60_000);
var firstLike = digest.Offer("ann/post-9", "bo", "liked your post", now: 0);
Debug.Assert(firstLike == "bo liked your post", "the first like goes out at once");
int folded = 0;
for (int fan = 1; fan <= 999; fan++)
if (digest.Offer("ann/post-9", "fan" + fan, "liked your post", now: fan * 50) == null) folded++;
Debug.Assert(folded == 999, "the other 999 likes in the minute are folded into the window");
Debug.Assert(digest.Offer("ann/post-9", "bo", "liked your post", now: 50_000) == null, "the same person liking twice adds nothing");
Debug.Assert(digest.Flush(now: 30_000).Count == 0, "nothing is due before the window ends");
var summary = digest.Flush(now: 60_000);
Debug.Assert(summary.Count == 1 && summary[0].Text == "fan1, fan2 and 997 others liked your post", "one summary replaces 999 notifications: 1,000 likes became 2 messages");
Debug.Assert(digest.Flush(now: 90_000).Count == 0 && digest.Flush(now: 120_000).Count == 0, "then the target is quiet, and is forgotten");
Debug.Assert(digest.Offer("ann/post-9", "zed", "liked your post", now: 500_000) == "zed liked your post", "a later like starts a fresh window");The window is state, so it must be durable: a keyed store with expiry, or the state of a stream processor, plus a timer to flush it. If the process restarts, the pending list has to survive. The summary is one notification, so it is the summary that counts toward the daily cap. Email "daily digest" settings are the same pattern with a window of a day.
A campaign is not 20 million API calls. It is a job, and the design is the job's life cycle.
- Draft, approval and canary. A large audience needs a second approver and a preview. The first step sends to 1 percent of the audience and waits while someone looks at errors, unsubscribe rate and complaints, and only then ramps up.
- Expansion in chunks. An expander reads the audience a page at a time after a stored cursor, writes one ledger row per user with the deterministic key
campaign-9/userand enqueues the chunk. A crash resumes at the cursor, and a chunk that runs twice creates nothing new (the ledger driver above asserts this). - A rate cap. The campaign carries
rate_per_second, and its lane releases no faster than the smaller of that cap and the campaign's share of the provider's budget. - A kill switch. Workers read the campaign state before each chunk and again before each send. Pausing or cancelling takes effect on messages that are already queued, which then expire in place instead of going out.
Scheduled sends
"9 am local" means a different instant for each time zone, so the audience is split by zone and each group gets its own due time. Add jitter inside a window of 10 to 30 minutes, or every zone's boundary becomes a spike. Delayed delivery needs a mechanism, and the choices differ in how long a delay they allow.
| Mechanism | How it works | Limit |
|---|---|---|
| Queue-native delay | A per-message delay on the queue | Short: SQS delays a message by 15 minutes at most |
A database index on due_at | A scheduler claims due rows every second with a conditional update | Simple and durable. Partition by due hour once the table is large |
| A sorted set | Score is the due time. A poller takes the members that are due | Fast, but durability depends on how the store persists |
| Buckets plus a timer | Store far-future items by hour, load the next hour into memory | The usual hybrid for very large volumes |
The push stampede
A push is a call to action. Tens of thousands of people open the app within a minute of a large send, and each open is several requests to your API. The simulation sends a push to 20 million people. It assumes that 8% open the app, each after a random delay that averages 90 seconds, and that an open costs your API 6 requests. The only thing that changes between the rows is how long the send takes.
C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
int PeakRequestsPerSecond(int sendOverSeconds)
{
var random = new Random(7);
int opens = (int)(20_000_000 * 0.08);
var perSecond = new Dictionary<int, int>();
int peak = 0;
for (int n = 0; n < opens; n++)
{
double sentAt = random.NextDouble() * sendOverSeconds; // the push goes out evenly across the window
double delay = -90.0 * Math.Log(1 - random.NextDouble()); // exponential: most react within minutes, some much later
int second = (int)(sentAt + delay);
perSecond[second] = perSecond.GetValueOrDefault(second) + 6;
peak = Math.Max(peak, perSecond[second]);
}
return peak;
}
int allAtOnce = PeakRequestsPerSecond(1);
int tenMinutes = PeakRequestsPerSecond(600);
int thirtyMinutes = PeakRequestsPerSecond(1_800);
Debug.Assert(allAtOnce is > 100_000 and < 112_000, "sent in one second, the opens add about 106,000 requests a second");
Debug.Assert(tenMinutes is > 15_000 and < 19_000 && allAtOnce > 5 * tenMinutes, "spread over ten minutes the peak is about 17,000, six times lower");
Debug.Assert(thirtyMinutes is > 5_000 and < 7_000, "spread over thirty minutes, about 6,000");| Send takes | Peak extra requests a second |
|---|---|
| 1 second | about 106,000 |
| 10 minutes | about 17,000 |
| 30 minutes | about 6,000 |
The total is identical in every row: 9.6 million requests. Only the shape changes. So the campaign's rate cap is not only about the provider. It protects your own API, and it is the reason a "send now to everyone" button should not exist. The numbers are illustrative, because open rates and delays vary by product, but the shape (a fast rise, then a long tail) is why you spread the send, warm caches for the screens a push opens, and keep the landing screen cheap.
| Push (APNs, FCM) | SMS | ||
|---|---|---|---|
| Cost per message | Nearly free | Priced per message and country | Low |
| What can be reached | A valid token on a device with notifications on | A number that carriers will deliver to | An address, if the mail is not filtered |
| Feedback | Accepted or rejected, errors for dead tokens, no per-message "shown" | Delivery receipts that vary by carrier and country | Bounces and complaints. Opens are unreliable |
| Typical hazard | Token churn | Fraud and regulation | Sender reputation |
| Payload | A few kilobytes: send a pointer and let the app fetch the content | Short text | Rich |
Device tokens. A user has several, and they change when the app is reinstalled or restored. APNs and FCM reject a dead token with an error such as Unregistered. Treat that as permanent: delete the token. Prune tokens not seen for months, because stale tokens waste send budget and distort delivery statistics. Firebase's guide on registration tokens describes the practice.
Email reputation. Authenticate with SPF, DKIM and DMARC. Google's rules for bulk senders also require one-click unsubscribe on marketing mail (the List-Unsubscribe headers of RFC 8058, which transactional mail is exempt from), honouring unsubscribes within two days, and keeping the user-reported spam rate below 0.1% and never reaching 0.3%. Put every bounce and complaint on a suppression list (Amazon SES keeps an account-level one) and never send to it again. Send transactional and marketing mail from separate subdomains, and at volume from separate IP pools, so that marketing complaints cannot damage the reputation that password resets depend on.
SMS fraud and rules. The best-known attack is SMS pumping, also called artificially inflated traffic: bots trigger code messages to premium-rate numbers that the attacker profits from, and you pay. Defences are the ones from the rate limiting lesson (limits per phone number, device and IP on code requests), a country allow-list, checking the account or device before a message is sent, and an alert on the ratio of codes entered to codes sent. Offer a channel that costs nothing, such as an in-app prompt or an authenticator, where you can. Replies such as STOP must opt the number out everywhere at once. In some countries, carriers or regulators require senders to register before messages are delivered, so treat registration as lead time in the project and check the current rules.
| Case | What goes wrong | Response |
|---|---|---|
| A producer retries | Two notifications for one event | A unique idempotency key built from the business event, kept for a day or more |
| The queue redelivers | Two workers send | A conditional claim with a lease. The loser backs off |
| A worker dies after the provider call | A second copy, or none | A guarantee per kind: resend a login code, drop a promotion. Collapse keys on push. Accept the small window |
| The user changed a setting while queued | A muted message arrives | Check consent again in the worker, not only at accept |
| A provider goes down | Workers stall on timeouts and deadlines pass | A breaker, failover before the call, a warm backup, expiry |
| A provider throttles (429) | A retry storm makes it worse | Treat it as a rate signal: slow the limiter and honour Retry-After. Do not trip the breaker |
| A backlog drains after an outage | Stale messages arrive in a burst | An expiry on every notification, a cap on the drain rate, expire in place |
| A wrong audience or a template bug | Millions of wrong messages | Approval, a canary, a preview, a rate cap and a kill switch that reaches queued messages |
| A runaway sender | Other lanes starve | The class comes from the type. A quota per sender and class |
| Stale device tokens | Wasted sends and skewed statistics | Delete on Unregistered. Prune tokens not seen for months |
| Receipts arrive late, twice or never | Wrong status, wrong fallbacks | A stage ladder merged with max. Silence means unknown. Base fallbacks on your own app signals |
| A poison message crashes a worker | A crash loop on every worker that receives it | An attempt cap, then a dead-letter queue with the reason |
| Daylight saving or a changed zone | A 9 am send at 8 or 10 | Store the zone name, convert at decision time, test the changeover days |
| SMS pumping | A huge bill and blocked countries | Limits per number, device and IP, a country allow-list, a conversion alert |
| Message bodies in logs | Login codes sit in plain text | Redact bodies, keep short retention, log the notification ID instead |
Interviewer follow-upL5How do you stop the same notification from going out twice?How to answer
Name the three places a duplicate is born and defend each. The producer retries, so the API takes an idempotency key built from the business event and the ledger enforces it with a unique index. The queue redelivers, so a worker must win a conditional claim with a lease before it calls a provider. The provider call itself cannot be made exactly once, so choose per kind: resend a login code, drop a promotion, and send the notification ID as a collapse key on push. Say plainly that what you get is effectively-once, not exactly-once.
Interviewer follow-upL5How do you decide between push, SMS and email, and when do you fall back?How to answer
Start from the kind and the user's settings, not from the channel. Push first for anything the app can show, because it is nearly free. SMS for the few kinds that must reach someone without the app (login codes, security alerts), because it costs money and invites fraud. Email for receipts and anything long. Fall back only on your own signals (the app did not report that it opened within N minutes), never on the absence of a provider receipt, since push services do not give per-message delivery receipts.
Interviewer follow-upL6A campaign is delaying login codes. What do you change?How to answer
Separate lanes by class, with their own workers, and, where the provider throttles per account, their own credentials or sender pool so that a throttled campaign cannot throttle codes. Take the class from the registered type, not from the caller. Add a quota per sender and class at the API. Choose strict priority or reserved shares knowingly: strict priority protects the top lane and starves the rest during a flood, shares protect everyone but make the flooded lane wait longer. In the simulation a campaign delayed codes by 199 seconds in one queue and by none in their own lane, at the price of the campaign finishing a minute later.
Interviewer follow-upL6The SMS provider is down. What happens to a login code in flight?How to answer
The call times out, and the adapter reports a transient, ambiguous failure. The ledger keeps the claim until the lease ends. For a critical kind the worker retries or fails over within the code's expiry, accepting a rare duplicate. The breaker opens after a few failures, so later codes go straight to the backup instead of each waiting out a timeout, and it probes the primary on a cooldown. If nothing works before the expiry, the code expires rather than arriving late, and the product offers another method. Say that the backup has to be warm, and that failing over before the call is safe while failing over after a timeout can send two.
Interviewer follow-upL6Users get the same alert on their phone, tablet and by email. Fix it.How to answer
Make the decision per user and event, not per device and channel. One notification ID covers all the channels that were chosen, and the policy stage picks the best one for the user's current state. Where more than one is sent, mark the others as superseded once one is acknowledged by your own app (opened or dismissed), and use collapse keys so that devices replace instead of stacking. Send a lower-urgency copy to the second channel after a delay, and cancel it if the first was seen.
Interviewer follow-upL6How do you send at 9 am local time to 20 million users?How to answer
Split the audience by time zone and give each group its due time, expanded in chunks with deterministic keys. Add jitter inside a 10 to 30 minute window so that each zone boundary is not a spike. Hold the due items in a delay mechanism with a long horizon (a database index on due time, or a sorted set, not a queue delay that stops at 15 minutes). Cap the rate by the provider's budget and by the opens your own API can take, and check consent again when each message is sent, since hours have passed. Use zone names, not offsets, so that daylight saving changes do not move the send.
Interviewer follow-upL7A bug sent a promotion to every user twice. Which controls would have stopped it?How to answer
The deterministic key campaign/user makes the second run a no-op at the ledger. Approval for a large audience, a 1 percent canary with a metrics check before the ramp, and a preview catch a wrong audience or template. A rate cap limits the blast radius while someone notices, and a kill switch that is checked at send time reaches messages that are already queued. A per-user daily cap catches it even if everything else fails. After the incident, add the missing check as a test, since this class of failure is what the pipeline exists to prevent.
Interviewer follow-upL7Run this in two regions. What changes?How to answer
Keep each user's ledger and preferences in a home region, and send from there, so the claim and the policy decision stay local and strongly consistent. Providers are global, so each region needs its own credentials and rate budget and the quotas are split between them. Failing over a region means another region takes over the user shard, which needs fencing on the claim (an epoch on the lease) so that the old region cannot send after it lost ownership. Accept that during a failover a notification may be sent again, and rely on the guarantee per kind. Do not put a cross-region synchronous call on the send path.
Interviewer follow-upL7How do you know the system is healthy?How to answer
Watch the things users feel, per class: the time from accept to provider acceptance, the age of the oldest message in each lane, the provider success rate and breaker state, and the expiry and drop rates. Add the outcomes that show a design problem: the duplicate rate (found by auditing the ledger for two sends with one key), the share of notifications dropped by policy, and the unsubscribe and complaint rates, which are the product's own health signal. Alert on lane age and on conversion of login codes (codes entered over codes sent), which catches both outages and fraud.
- Clarify: channels, the kinds and their deadlines, duplicate against loss per kind, user controls, scheduling, build or buy.
- Estimate: the average, then the campaign as the sizing event, the provider ceiling, the SMS bill, the open storm.
- Contract and model: a send call with an idempotency key and a type (not a priority), a campaign job, the ledger, preferences, devices.
- Draw it: API and ledger, policy and routing, lanes per channel and class, workers with adapters and breakers, receipts.
- Go deep on duplicates: the key, the claim with a lease, and a guarantee per kind, then say what is left.
- Decide before queueing: consent, quiet hours in the user's zone, caps and expiry, checked again at send.
- Isolate and survive: lanes with a quota per sender, a breaker with a warm backup, expiry on everything.
- Operate it: campaigns as jobs with a canary and a kill switch, a spread-out send, digests, and the metrics that show the system is healthy.
A notification service is a pipeline around a ledger. The API accepts a request under an idempotency key built from the business event, and a worker must win a conditional claim before it may call a provider. A guarantee chosen per kind decides what a crash means: resend a login code, drop a promotion. Receipts move the status up a ladder and never down. Policy decides whether and when before queueing and again at send, with consent first, quiet hours in the user's zone, caps and expiry. Each class has its own lane, the class comes from the type, and quotas at the door matter more than the scheduler. A breaker in front of each provider and a warm backup keep a provider outage from consuming the workers. Digests turn bursts into one message. Campaigns are resumable jobs with a canary, a rate cap and a kill switch, and spreading the send protects your own API from the people who answer it.
Try answering out loud before you reveal each answer.
QuestionThe queue redelivers a message and two workers pick it up. What stops a second text, and what risk remains?Reveal answer
Each worker must win a conditional update from queued to sending in the ledger before it may call the provider. One wins and the other backs off. The risk that remains is a worker that sent the text and died before writing sent: when its lease ends, the notification is claimed again. For a login code that duplicate is accepted, and for a promotion the notification is dropped instead, so the guarantee is chosen per kind.
QuestionA user unsubscribes at 10:00. A campaign message for them has been queued since 9:30. What stops it, and why is checking at accept not enough?Reveal answer
The worker checks consent again just before the provider call and finds the opt-out, so it drops the message. A check at accept only reflects the preferences at 9:30, and a lane can hold messages for hours. A version number on the preferences lets the worker tell its cached copy is stale.
QuestionStrict priority protects login codes from a campaign. How can it still hurt, and what are two defences?Reveal answer
If the top lane floods, every lane below it starves. In the simulation a buggy sender made order updates wait 36 seconds behind a 30-second flood. Reserved shares keep the lower lanes moving but make the flooded lane wait longer (22 seconds against 7). The real fix is upstream: take the class from the registered type instead of the caller, and enforce a quota per sender and class at the API, which removed all waiting in the simulation.
QuestionThe primary SMS provider times out for an hour. Why is "fail over to the backup after each timeout" not enough, and what is?Reveal answer
Every message still waits out the timeout first, so the workers are stuck and the backlog grows: about 22% of the messages were late and the longest wait was 47 seconds. A circuit breaker stops sending to the primary after a few failures and probes it on a cooldown, so only about 100 calls waited out a timeout and nothing was late. Fail over before the call, because failing over after a timeout can deliver two copies.
- Brandur Leach, Implementing Stripe-like Idempotency Keys in Postgres (opens in a new tab): a worked schema for keys, locking and recovery points.
- Stripe, Designing robust and predictable APIs with idempotency (opens in a new tab): why a retry needs a key chosen by the caller.
- Amazon Builders' Library, Timeouts, retries and backoff with jitter (opens in a new tab).
- Martin Fowler, Circuit Breaker (opens in a new tab): the closed, open and half-open states.
- Google, Site Reliability Engineering: Handling Overload (opens in a new tab) (criticality levels) and Addressing Cascading Failures (opens in a new tab) (retry amplification).
- LinkedIn Engineering, Air Traffic Controller: Member-First Notifications at LinkedIn (opens in a new tab) (2018): one decision-maker above every channel.
- Firebase, Set the lifespan of a message (opens in a new tab), collapsible message types (opens in a new tab), message priority (opens in a new tab) and registration token management (opens in a new tab).
- Apple, Sending notification requests to APNs (opens in a new tab): expiration, priority and collapse identifiers.
- Amazon, SQS delay queues (opens in a new tab) and the SES account-level suppression list (opens in a new tab).
- Google, Email sender guidelines (opens in a new tab) and its FAQ (opens in a new tab), and RFC 8058 (opens in a new tab), one-click unsubscribe.
- Twilio, Preventing fraud in programmable messaging (opens in a new tab): artificially inflated traffic (SMS pumping).