Practice: Notification System
Design a multi-tenant notification service for transactional alerts and bulk campaigns across email, SMS, and push. Show durable acceptance, frozen audience expansion, fair bounded dispatch, and the lifecycle through a reconciled outcome.
Design a multi-tenant notification service for transactional alerts and bulk campaigns across email, SMS, and push. Show durable acceptance, frozen audience expansion, fair bounded dispatch, and the lifecycle through a reconciled outcome.
Write your own design before opening hints or the solution review. The numbers below are exercise assumptions, not claims about any company’s production traffic. You may challenge an assumption, but record the replacement and explain which decision changes.
Scenario and constraints
- Largest campaign: one million recipients.
- Email provider budget: 500 submissions/s globally.
- Average provider call time: 200 ms; quotas are illustrative.
- Consent may change after expansion; urgent alerts outrank bulk work.
Your deliverables
- Model campaign, delivery, attempt, preference, and receipt identities.
- Calculate the dispatch lower bound and expected in-flight provider work.
- Draw durable acceptance, paged expansion, fair dispatch, and receipts.
- Define queued, suppressed, submitted, delivered, failed, and unknown states.
Reason about this sequence
Read the diagram
Intent accepted durably → Recipient opts out → Worker checks current consent → Suppress before provider call → Record auditable outcome
For every step, annotate what is durable, what the caller knows, and which identity survives a retry. Identify the point where two concurrent actors could disagree. Do not assume a timeout means failure or a cache value grants ownership.
Interviewer follow-ups
- The database commits but queue publication fails.
- The provider accepts a send but its response is lost.
- Replay a campaign page, then let the recipient opt out before send; exhaust the provider quota and lose the acknowledgement for a call the provider accepted. Explain each state transition and whether another external call can occur.
Answer each follow-up using the same design first. If it breaks, change the smallest boundary that repairs the invariant and explain the new cost. Show whether the change adds latency, storage, coordination, or operational work.
Staged hints
Hint 1 — reveal
Answer: Hint 1 — Invariant: never admit a new provider call without current channel consent and shared quota, and never create two logical deliveries for the same intent/recipient/channel. Use separate identities for logical delivery and each provider attempt. A queue record does not prove whether a timed-out provider request succeeded; keep it unknown until authenticated evidence or a safe dedupe-aware reconciliation resolves it.
Hint 2 — reveal
Answer: Hint 2 — A queued audience snapshot is not permanent permission to send. Recheck current consent and suppression rules close to the provider call, and document the unavoidable boundary between that check and an external send. Apply quiet hours, channel preferences, and per-tenant fairness before consuming scarce provider capacity.
Hint 3 — reveal
Answer: Hint 3 — The database commits a campaign but the process crashes before publishing to the broker. Without an outbox, accepted work can disappear. A transactionally stored outbox event can be published later. Publication may repeat, so recipient expansion and dispatch still need stable identities. The outbox closes one gap; it does not create exactly-once external delivery.
Evidence-based self-review
- Acceptance cannot lose committed intent at the broker boundary; campaign cursor and unique recipient/channel deliveries advance atomically.
- Global provider capacity is enforced across all workers.
- Consent and suppression are checked under a stated dispatch policy.
- Unknown provider outcomes are reconciled with stable identities.
Score each item 0 if absent, 1 if named without an enforceable mechanism, or 2 if the mechanism and a failure are explained. Record evidence from your own diagram beside the score. Then choose one weak decision, revise it, and repeat the relevant follow-up. This rubric is a learning tool, not a hiring forecast.
Read the diagram
Campaign + outbox → Audience expansion: durable event; Audience expansion → Delivery queue: stable deliveries; Delivery queue → Consent + quotas: bounded dispatch; Consent + quotas → Provider attempts: permitted send; Provider attempts → Receipt reconciler: reference / timeout; Receipt reconciler → Delivery queue: state updates
Worked resolution
There is no separate review activity for this prompt. Open the explanation after saving your attempt.
Show answer and explanation
Answer: A school queues a million notices at 09:00. A parent opts out at 09:10, before their delivery reaches dispatch. The worker checks current preference and suppresses that delivery with an audit reason. Another delivery times out after provider submission; it stays unknown until lookup or callback resolves it. The dashboard should count suppressed and unknown separately from delivered. Use durable intent and paged expansion, enforce a provider-wide dispatch budget, recheck live consent, retain attempt identities, and reconcile unknown results. Track acceptance latency, oldest queue age, suppressed counts, provider error rate, and unresolved attempt age separately.
Show answer and explanation
Answer: Capacity check — one million / 500 per second = 2,000 seconds before retries and overhead. At 200 ms average provider latency, 500/s implies about 100 in-flight operations in a stable system. Global quotas still constrain every worker pool together.
Clarify this prompt before choosing components
Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.
| Ask the interviewer | Why the answer changes the design |
|---|---|
| Transactional, marketing or both, and which channels? | Priorities, consent and provider limits differ. |
| Acceptance, provider delivery or user read guarantee? | The service cannot claim a provider receipt is a human read. |
| Expiry, quiet hours, retries and duplicate tolerances? | Policy must run at dispatch; unknown provider outcomes require reconciliation. |
Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.
Reveal the full worked solution
Save your attempt before continuing.
Notification System: Understand the building blocks
Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.
Notification System: Quick vocabulary
| Term | Meaning and role in this exercise |
|---|---|
| API: Application Programming Interface | The contract for requests, responses and errors between components. An API route does not itself enforce every business invariant. |
| SMS: Short Message Service | A carrier-mediated text-message channel with provider capacity and delivery-status constraints; acceptance is not proof the user read it. |
| PK: Primary Key | The declared row identity in a database schema; it does not automatically enforce every cross-row business rule. |
Notification System: Transactional outbox
What it means: An outbox is a table of pending events written in the same local transaction as business state. It closes the local database/event-publication gap.
Why this problem needs it: An accepted notification should not disappear between database commit and publication.
How to use it: Commit the business row and outbox row together; a publisher retries delivering events and tracks progress. Consumers deduplicate logical event identities.
Example in this design: Commit notification N7 and its event intent together; retry the publisher with the same event identity.
When it fits: Useful when a database commit must eventually cause downstream work.
Alternative and limits: Direct database-then-broker writes can lose or duplicate publication around failure. An outbox does not make its external delivery atomic with every subscriber.
Notification System: Durable work queue and backpressure
What it means: A queue separates accepted work from execution. Backpressure limits admission or consumption when downstream capacity is finite.
Why this problem needs it: Provider capacity is finite while bulk demand can burst.
How to use it: Persist a stable job identity, consume with bounded concurrency, acknowledge after the required durable transition, and cap retries/backlog according to policy.
Example in this design: Reserve 100/s urgent capacity and 400/s bulk from a declared 500/s total.
When it fits: Useful for asynchronous work that must survive worker failure or absorb a finite burst.
Alternative and limits: A synchronous call is simpler for short bounded work. A queue does not create capacity, strict global ordering or exactly-once external effects.
Notification System: Idempotency key and stored operation result
What it means: Idempotency means replaying the same logical operation produces no additional business effect. A key identifies that operation under a defined scope.
Why this problem needs it: Delivery workers can retry after uncertain provider responses.
How to use it: Atomically associate a request key and payload fingerprint with its effect and result. Return the stored result on replay; reject incompatible payload reuse.
Example in this design: Preserve the recipient/channel effect ID; reconcile a timeout rather than creating a second send.
When it fits: Needed when a timeout can hide a successful commit or a queue can redeliver.
Alternative and limits: Unique business identities can enforce selected effects. A cache of recent requests alone may expire too early or race; local keys cannot control an uncooperative external provider.
Notification System: Dead-Letter Queue (DLQ)
What it means: A DLQ isolates jobs that cannot complete under the configured retry policy so they do not block healthy work indefinitely.
Why this problem needs it: Invalid recipients must not monopolize the bulk pipeline.
How to use it: Store the original job identity, failure reason and retry history; alert and inspect before a deliberate replay that preserves effect identity.
Example in this design: Isolate repeated permanent failures and inspect before replay.
When it fits: Useful for poison inputs or persistent provider errors.
Alternative and limits: A finite retry with a terminal recorded failure can fit small systems. A DLQ is not recovery by itself, and blindly replaying everything can repeat effects.
Interview scope and guarantees
Accept notification intent, resolve recipients, apply current channel preferences and quiet hours, send through providers, and expose attempt/delivery status. Separate urgent from bulk traffic. Provider acceptance, delivery and user reading are different outcomes.
Capacity worksheet
Assume 10 million recipients receive 2 channels: 20 million delivery jobs. At a combined provider limit of 10,000/s, the theoretical drain time is 2,000 seconds, about 33.3 minutes, before retries. At 200 ms mean provider latency that throughput needs about 2,000 in-flight calls. Increasing workers beyond the provider quota adds contention, not throughput.
Concrete API contract
POST /notifications {requestKey,audienceId,templateId,channels,expiresAt} -> 202 {notificationId}
GET /notifications/{id}/status
POST /provider-events {providerEventId,attemptId,status}
PUT /preferences {channels,quietHours,timeZone}Data model and access paths
intents(id PK,tenant_id,request_key,template_version,state); UNIQUE(tenant_id,request_key)
deliveries(id PK,intent_id,recipient_id,channel,state); UNIQUE(intent_id,recipient_id,channel)
attempts(id PK,delivery_id,provider,key,state)
provider_events(provider,event_id); UNIQUE(provider,event_id)
audience_snapshots(intent_id,snapshot_version,criteria,watermark)
expansion_shards(intent_id,shard,cursor,state); PK(intent_id,shard)
preferences(tenant_id,user_id,channel,version,quiet_hours,time_zone); PK(tenant_id,user_id,channel)
templates(id,version,locale,content_hash); PK(id,version,locale)Evolve a solution and explain each change
Read the diagram
Accept intent / Persist recipient, channel, template version, and deduplication identity. / Acceptance is not delivery and can precede user opt-out changes.; Apply policy and dispatch / Enforce current preferences and quotas before a provider attempt. / Providers can timeout after accepting the message.; Reconcile ambiguous attempts / Track attempt identity, provider references, retry classes, and final state. / Blind retries can send duplicate irreversible messages.
Step 1: Accept intent
Persist recipient, channel, template version, and deduplication identity. Acceptance is not delivery and can precede user opt-out changes.
Step 2: Apply policy and dispatch
Enforce current preferences and quotas before a provider attempt. Providers can timeout after accepting the message.
Step 3: Reconcile ambiguous attempts
Track attempt identity, provider references, retry classes, and final state. Blind retries can send duplicate irreversible messages.
Responsibility overview
Read the diagram
Producer to Notification API: submit event identity; Notification API to Intent DB: commit notification intent; Intent DB to Attempt queue: due attempt; Attempt queue to Dispatcher: claim under quota; Dispatcher to Provider: stable provider identity; Dispatcher to Intent DB: reconciled attempt state
Worked end-to-end scenario
A payment event requests email n17. The API commits notification intent and returns accepted. Before dispatch, the worker checks template/version, recipient preferences, and channel policy; transactional and marketing rules can differ. It calls the provider with a stable message identity where supported. The provider accepts but the response is lost. Mark the attempt unknown and query provider status or reconcile a callback instead of immediately treating it as failed. If no idempotency/status mechanism exists, document the at-least-once duplicate risk. A permanent invalid-address error is not retried like a temporary rate limit.
Why these access paths matter
Intent is keyed by producer event, recipient, and purpose. Attempts carry provider, attempt ID, response class, and external reference. Index due attempts by next eligible time; apply quota globally across workers. A delivery webhook is untrusted until verified and deduplicated. Preserve accepted, sent, delivered, bounced, and suppressed as distinct outcomes.
Build the baseline first
Read the diagram
Intent transaction → outbox → audience expansion; Delivery queue → preferences and quota → provider; Webhook or reconciler → attempt status → reporting
- Intent transaction → outbox → audience expansion.
- Delivery queue → preferences and quota → provider.
- Webhook or reconciler → attempt status → reporting.
Evolve the design under load
Read the diagram
Tenant/channel queues → weighted fair dispatch; Provider token budgets → bounded worker pools; Chunked audience snapshot → checkpointed expansion
- Tenant/channel queues → weighted fair dispatch.
- Provider token budgets → bounded worker pools.
- Chunked audience snapshot → checkpointed expansion.
Defend the hardest decision
Freeze the intended audience or define live membership semantics, but recheck opt-outs and legally relevant preferences before sending. Give every recipient/channel delivery a stable ID and reuse its provider idempotency key on ambiguous retries. Quiet-hour delays require timezone-aware due times and message expiry. An expired emergency alert should not be sent hours later merely because the queue recovered.
Failure and recovery analysis
The provider accepts an SMS but the response is lost. Blind failover to a second provider may duplicate the message. Query the first provider by the stable request reference when supported, otherwise wait and reconcile under a documented duplicate-risk policy. A webhook may arrive before the synchronous response and later events may be out of order; use a transition table rather than blindly replacing status.
Security and privacy boundary
Encrypt addresses, verify webhook signatures, authorize tenant templates and audiences, and redact message bodies from routine logs.
Interview follow-ups with reasoning
Question: How do you isolate a large district or tenant?
Show answer and explanation
Answer: Allocate a fair share of dispatch slots and quota with reserved urgent capacity.
Question: How do you recover a partial expansion?
Show answer and explanation
Answer: Store chunk checkpoints and unique delivery keys.
Question: What proves observability?
Show answer and explanation
Answer: Reconcile intent counts to pending, suppressed, accepted, delivered and failed outcomes.
Operate and verify the design
Oldest pending delivery, provider quota usage, uncertain attempts and intent-to-outcome reconciliation.
Lose a provider response and verify the system reconciles before sending through a second provider.
A second scenario to test transfer
A school queues a million notices at 09:00. A parent opts out at 09:10, before their delivery reaches dispatch. The worker checks current preference and suppresses that delivery with an audit reason. Another delivery times out after provider submission; it stays unknown until lookup or callback resolves it. The dashboard should count suppressed and unknown separately from delivered.
Write a design for a million-recipient campaign that includes queue age, opt-outs, and provider timeouts.
Show answer and explanation
Answer: Use durable intent and paged expansion, enforce a provider-wide dispatch budget, recheck live consent, retain attempt identities, and reconcile unknown results. Track acceptance latency, oldest queue age, suppressed counts, provider error rate, and unresolved attempt age separately.
Compare alternatives
| Boundary | Mechanism | Remaining risk |
|---|---|---|
| API to queue | Transactional outbox | Duplicate publication |
| Worker to provider | Stable provider identity | Provider-specific support |
| Consent | Near-dispatch policy check | Race with external submission |
| Callbacks | Authentication + dedupe | Delayed or missing receipts |
A design-changing exercise
The provider returns 202. Can the service report delivered?
Show answer and explanation
Answer: No. Provider acceptance, actual transmission, and delivery confirmation are separate states; expose the evidence available at each boundary.
Design workshop: expand recipients, then enforce current policy
Core scope is email, SMS and auto-call intents, user preferences, provider dispatch and outcome tracking. Exactly-once human receipt is not promised. Choose durable acceptance under 500 ms, a specified campaign delivery window and zero unauthorized new sends under the chosen consent-admission contract. Preference changes after a provider has accepted a message cannot retract it.
Add audience_snapshots(intent_id,snapshot_version,criteria,watermark), expansion_shards(intent_id,shard,cursor,state), preferences(tenant,user,channel,version,quiet_hours,time_zone), and templates(id,version,locale,content_hash). Freeze who belongs to the campaign at a declared snapshot, then evaluate current channel consent/quiet hours near dispatch. Expander inserts deliveries unique(intent,recipient,channel) with its checkpoint in one transaction. A crash repeats a page without creating duplicate logical deliveries.
Read the diagram
Commit intent, template version and audience watermark W; Enumerate next recipient page at W; Insert unique deliveries and advance checkpoint together; Claim bounded batch; rotate tenants and reserve urgent capacity; Recheck current consent/timezone immediately before provider call; Reserve provider quota and invoke stable attempt identity; Store accepted/unknown outcome for reconciliation
Acceptance and dispatch are separate boundaries. The API commits an intent and its outbox work in one transaction; a relay can publish repeatedly because intent and delivery keys are stable. Workers claim only a bounded number of rows, and each provider call obtains a global channel budget at the final admission boundary. The model in examples/system-design/notification_system.py exercises these rules; tests/test_notification_system_model.py covers duplicate acceptance, replayed pages, opt-out races, quota exhaustion and unknown outcomes.
Read the diagram
POST with tenant idempotency key and pinned template version; Commit intent, channel deliveries and outbox records atomically; Publish outbox records at least once into channel and priority lanes; Return stable intent ID after durable commit
Preference is authoritative at send admission, not at campaign snapshot time. A missing or disabled channel preference suppresses the delivery; quiet hours defer it to the next local end time. Equal quiet-hour bounds mean the feature is disabled. At the provider boundary, check preference again so a change after queue selection cannot authorize a send. If the deferral moves beyond expiry, expire the delivery without sending.
Read the diagram
Current channel preference / Local quiet-hours result / Admission action; Missing / Not evaluated / Suppress with auditable no-consent reason; Disabled / Not evaluated / Suppress; do not call provider; Enabled / Outside quiet interval / Continue to quota and provider admission; Enabled / Inside quiet interval / Keep queued until local interval ends; expire if deadline passes first; Enabled / Equal start and end / Treat quiet window as disabled
A provider quota scheduler combines channel/provider/tenant budgets. At 500 requests/s and 200 ms response latency, Little's Law gives about 100 in-flight API calls, plus headroom bounded by timeout and quota. Auto-calls differ: a two-minute active call duration at 10 new calls/s implies about 1,200 active calls, so connection/concurrent-call quotas may dominate request rate. A 1.5-billion-recipient theoretical school population is not one provider batch; freeze/partition and define a feasible campaign window against purchased limits.
Use weighted tenant rotation, bounded batches and scheduled retry times rather than workers repeatedly hammering a provider. Retry delay=min(cap,base×2^attempt) with jitter; respect Retry-After and expiry. Definitive invalid-address errors are terminal, throttling retries later, timeouts become unknown until the original provider identity/status can be resolved. A failover provider is a new external operation and may duplicate a message if the first outcome remains unknown; do not silently switch on timeout. Reserve only a configured slice of worker starts for urgent work so bulk sends make progress when urgent traffic is idle, and keep per-tenant queues fair within each class.
Read the diagram
Persist attempt ID and stable delivery idempotency key; Submit message; request times out after provider may accept; Mark attempt and delivery unknown; never enqueue blind retry; Query by original reference or await authenticated callback; Resolve accepted/delivered, or retry only under dedupe contract
Read the diagram
Current state / Incoming evidence / Action; Queued / Authenticated accepted callback for matching attempt / Record accepted reference; Unknown / Verified delivered receipt for original attempt / Resolve delivered; suppress fresh retry; Delivered / Duplicate same provider/event ID / No new state or count; Delivered / Older accepted callback / Keep delivered; never regress; Accepted / Hard bounce or terminal failure / Channel-specific terminal outcome; audit reason; Unknown / No query capability before campaign expiry / Remain uncertain; apply disclosed manual/duplicate-risk policy
Authenticate callback signatures and deduplicate provider/event ID. Separate accepted, delivered, bounced, read where supported, and unknown; provider email accepted is not human read. Persist raw outcome evidence with privacy-aware retention, and derive per-delivery terminal state under provider-specific ordering rules. A reconciler polls old unknown attempts where supported and raises aged ambiguity for operations.
A delivery-count conservation report uses logical recipient/channel deliveries: created = queued+leased+accepted_pending+unknown+delivered+failed+suppressed+expired, with mutually exclusive current categories. Attempt counts are separate; retries must not inflate recipient totals. Reconcile sampled provider records against internal attempt IDs. Track audience lag, preference suppressions, oldest queue age, quota utilization, unknown age and DLQ reason distribution.
Data, APIs, and capacity choices
The intent record owns tenant, idempotency key, template version, creation time, expiry, audience watermark and requested channels. The campaign cursor is an ordered continuation point into an immutable audience snapshot. A delivery key is unique on (intent_id, recipient_id, channel). Each provider attempt adds its attempt number, provider, idempotency key, start time and outcome evidence without changing the logical delivery identity. Preference rows are versioned by tenant, recipient and channel. Callback inbox uniqueness is (provider_id, event_id). These keys make retries and replays observable instead of relying on worker memory.
Suggested interfaces are POST /notifications and POST /campaigns with a required tenant-scoped idempotency key, PUT /preferences/{channel} with an expected version, GET /deliveries/{id}, and an authenticated provider callback endpoint carrying the exact attempt identity. Acceptance returns the stable intent ID only after intent, deliveries or campaign snapshot reference, and outbox work are committed. A repeated request with the same key and same canonical payload returns the same ID; reuse with a different payload is a conflict. Keep content behind immutable template versions so an accepted campaign cannot render differently halfway through expansion.
For the exercise assumptions, one million recipients at 500 provider submissions per second has a raw lower bound of 2,000 seconds, or 33 minutes 20 seconds. Real completion takes longer because of provider errors, retries, quiet hours, quota shares, campaign staggering and safety headroom. At 500 requests/s with 200 ms average latency, Little's Law estimates 100 concurrent calls (500 × 0.2); a 2× headroom factor suggests a 200-call concurrency ceiling, still subordinate to the provider's contract. Partitioning only the campaign expander does not increase the provider's global quota. Enforce quota in shared state or a centralized token allocator so every worker observes the same limit.
The reference model serializes transitions with a lock to make crash points and invariants easy to test. A production design replaces that lock with database transactions, unique constraints, leases and an atomic shared quota reservation. Its synchronous request path must not wait for a campaign expansion or provider call. Bound request payloads, snapshot page size, claimed rows, per-worker in-flight calls and retry attempts. Queue storage and retention should have explicit caps; reject or pause new bulk campaigns when backlog age predicts that their requested delivery window is infeasible.
State and race table
| Event | Delivery transition | External effect allowed? | Required evidence |
|---|---|---|---|
| Durable intent commits | absent → queued or campaign accepted | No | Intent plus outbox transaction |
| Current preference is missing/disabled | queued → suppressed | No | Preference version and reason |
| Quiet interval is active | queued → queued with due time | No | IANA timezone, local rule and expiry |
| Shared quota reservation succeeds | queued → in-flight | Yes, once under attempt identity | Quota grant and durable attempt |
| Provider says accepted | in-flight → accepted | Already submitted | Provider response/reference |
| Request times out | in-flight → unknown | No retry until reconciled | Original provider attempt ID |
| Authenticated delivery receipt arrives | unknown/accepted → delivered | No additional send | Signature and deduplicated event ID |
| Retryable rejection | in-flight → queued with backoff | Later, after all checks | Error classification and next-attempt time |
Exercise: Email attempt A times out, a failover send B is queued, then A's delivered callback arrives. What happens?
Show answer and explanation
Answer: Reconcile A first and cancel B if it has not crossed its provider admission boundary. If B was already accepted, record possible duplicate delivery honestly. A stable internal delivery identity cannot make two unrelated providers share one external effect.
Read the diagram
Path / Authoritative state or limit / Sync or async / Correctness rule; Accept / Intent, pinned template and outbox transaction / Synchronous response after commit / Retry returns same intent; publish is at-least-once; Campaign / Frozen audience watermark and checkpoint cursor / Asynchronous bounded pages / Unique intent/recipient/channel key plus atomic cursor; Dispatch / Current preference, expiry, quota and tenant scheduler / Bounded worker batch and in-flight cap / Recheck consent at provider admission; Outcome / Attempt ledger, callback inbox and reconciliation state / Asynchronous callback/query / Timeout remains unknown until evidence resolves it
Read the diagram
Commit page deliveries and cursor in one transaction; replay creates no duplicate key; Recipient opts out after expansion but before provider admission; Suppress at final consent check; no provider request is made; Exhaust shared quota; defer with next eligible time, without creating an attempt; Provider accepts but acknowledgement is lost; persist unknown attempt; Query original reference; resolve receipt or retry only if provider dedupe makes it safe; Persist reconciliation evidence and final delivery state
Operations and practice
SLIs: durable-accept latency and failure rate; oldest queued age by tenant, channel and priority; campaign expansion lag; provider quota utilization and throttling; delivery success and suppression counts; unknown-attempt age; callback/reconciliation lag; and expiration rate. Do not call provider acceptance a human delivery.
Overload and recovery: admission rejects or delays campaigns when the declared campaign window cannot fit the purchased provider budget. Cap page size, provider concurrency, retries and per-tenant work; preserve urgent reserve and use delayed retries with jitter. On provider outage, pause that provider lane, retain queued work until its expiry, and reconcile unknown attempts before resuming or failing over. Alert on growing unknown age and provide an audited manual resolution path.
Access and cost: encrypt recipient addresses and rendered payloads, minimize callback retention, restrict preference and campaign access by tenant, authenticate provider callbacks, and never log secrets or message bodies. Provider submissions, carrier fees and voice minutes dominate variable cost; campaign throughput must be budgeted against contracted quotas.
Practice prompt: Design a multi-tenant email/SMS/push service with a 500 submissions/s provider limit, one-million-recipient campaigns, opt-outs that must take effect before provider admission, and urgent transactional alerts. Show durable acceptance, campaign checkpointing, fair bounded dispatch, provider attempts and callback reconciliation.
Failure follow-up: A campaign page is replayed, its recipient opts out, the provider quota is exhausted, and a provider accepts a request whose acknowledgement is lost. Walk through each state transition and identify which action can still send externally.
Rubric: A strong design makes the invariant explicit: no new provider call is admitted without current consent and quota, and each logical recipient/channel/intent delivery is unique. It advances campaign cursors atomically with idempotent delivery insertion, applies bounded fair scheduling, represents timeout as unknown, and resolves ambiguity using the original attempt identity before retry. It explains expiry, audit evidence and duplicate risk when provider deduplication is unavailable.
Stripe webhook guidance illustrates authentication, duplicate and order handling for one provider; email/SMS/call providers require their own documented contracts.
Requirement trace and verification
| Requirement | Implementing design block | Verification link |
|---|---|---|
| R1 — Complete the primary user journey within the stated scope. | P01–P04; P09–P10. | V1 — Exercise the successful journey and the excluded/boundary case stated in the scope. |
| R2 — Preserve the problem's authoritative data invariant under concurrency. | P05–P06; P11–P12; DD1. | V2 — Run the race/replay case below and assert the invariant at the durable authority. |
| R3 — Meet the declared scale and API behavior without unbounded work. | P05–P08; P13–P14; relevant overload deep dives. | V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity. |
| R4 — Recover from the named failure without losing or duplicating the user-visible outcome. | P15–P16; deep dives; Operations contract. | V4 — Replay a campaign batch, change opt-out before send, exhaust provider quota, and lose an acknowledgement; no silent loss or unbounded retry storm. |
Operational contract
| Area | Decision and signals |
|---|---|
| SLIs | Intent-to-dispatch lag; provider acceptance/delivery outcomes; unknown-attempt age; suppression and bounce rates. |
| Overload limits | Cap campaign expansion pages, per-provider concurrency/rate, tenant budgets, and retry/DLQ depth. |
| Recovery | Resume recipient cursors; reconcile unknown provider attempts by stable delivery identity; replay outbox safely. |
| Access controls | Recheck consent/quiet hours before dispatch; restrict message bodies and provider credentials in logs/secrets. |
| Dominant cost | Per-message provider fees, campaign fanout, and retained delivery records. |
Senior-level interviewer follow-ups
Question: A user changes channel preferences after a campaign audience was expanded. Which policy wins?
Show answer and explanation
Answer: Define whether policy is frozen at acceptance or checked at dispatch. For consent-sensitive delivery, check current eligibility at send time and retain an auditable reason for suppression.
Question: How do you stop one tenant's bulk campaign from starving urgent transactional alerts?
Show answer and explanation
Answer: Use separate priority classes with reserved capacity, per-tenant quotas, weighted fair scheduling, and a global provider budget. Prevent priority inversion and cap each worker's in-flight calls.
A 60-second design answer
I would durably accept a notification intent, freeze or version the intended audience, and expand it into bounded per-recipient deliveries. Dispatch rechecks channel eligibility, applies tenant fairness and provider quotas, and records each attempt with an idempotency key. Provider callbacks reconcile uncertain outcomes. I would monitor queue age, suppression reasons, provider errors, duplicate risk, and end-to-end delivery states.
Related concepts to revisit
Technical references
Provider idempotency contract example.
PostgreSQL transaction isolation and concurrent updates.
Protect urgent work while bulk work is admitted
Assume a provider quota of 500 operations/s. Reserve an exercise budget of 100/s for urgent notifications and allow bulk up to 400/s, with a declared borrowing policy. Independent worker pools cannot each spend 500/s. Queue age and dispatch deadlines are per priority; bulk storage durability does not establish the urgent five-second objective.
total quota: 500/s
urgent reserved share: 100/s
bulk eligible share: 400/s
recipient r7: selected preference v4; current opt-out v5
queued SMS: suppress under dispatch policyRead the diagram
total quota: 500/s; urgent reserved share: 100/s; bulk eligible share: 400/s; recipient r7: selected preference v4; current opt-out v5; queued SMS: suppress under dispatch policy
Intent, recipient/channel delivery and provider attempt are separate records. Schedule/campaign snapshots preserve who was selected, while live preferences govern current dispatch under a stated cutoff. A preference change racing an already-started external call cannot be undone by a local check alone. Provider acceptance is not recipient receipt, and an unknown timeout enters reconciliation under a stable attempt/provider identity.
Show answer and explanation
Answer: Provider capacity, urgency fairness and consent correctness are three boundaries. A fast urgent path still needs current policy and effect deduplication; a bulk retry cannot starve it.
Decision review: Notification System
Notification System: What it is
A notification service accepts communication intent, expands eligible deliveries, bounds submission and tracks external outcomes separately.
Notification System: Why it is needed
Large bursts, changing preferences and uncertain provider replies require more than placing messages on a queue.
Notification System: When to use it
Use asynchronous dispatch when audience expansion or provider capacity exceeds the API deadline. Give urgent work a declared admission and reserved-budget policy.
Notification System: How to use it
Commit campaign intent and publication obligation, derive stable delivery identities, enforce current policy at its agreed boundary and submit under shared tenant/provider limits. Preserve unknown outcomes for reconciliation.
Notification System: Compare an alternative
A single work pool is simpler but can let bulk traffic delay urgent work. Separate classes require fairness and a shared aggregate limit so reservations do not multiply the provider budget.
Notification System: Worked decision exercise
The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.
With a shared 500/s budget, reserve up to 100/s for urgent work and leave 400/s for bulk under this exercise policy. One million bulk submissions need at least 2,500 seconds at 400/s, before retries or provider delivery time.
Read the diagram
Global provider budget 500/s; Policy reserves up to 100/s urgent; bulk gets 400/s; 1,000,000 bulk / 400/s = 2,500 s minimum; Unknown submission keeps its original delivery ID
Can every worker enforce its own 500/s limit after the fleet grows?
Show answer and explanation
Answer: No: independent limits multiply the aggregate. Enforce the declared shared budget, decide whether unused urgent capacity is borrowable, and state the reclaim rule. A timed-out provider submission retains its delivery identity; quota compliance does not resolve its outcome.
Notification System: Check the design
Reconcile accepted intent to expanded, suppressed, pending, unknown and terminal deliveries. Monitor queue age by class, policy revision at submission and provider budget use.
Screenshot variant: Durable reminders at set times
For the beginner prompt, support create, cancel and reschedule of one-time reminders. Ask which channel, timezone, tolerated lateness and cancellation boundary apply. Use schedule(id,owner,due_at,time_zone,version,state) and occurrence(schedule_id,version,due_at,state,lease_generation) plus an outbox/delivery identity. POST /reminders persists intent, PATCH /reminders/{id} requires a version, and DELETE /reminders/{id} records cancellation rather than relying on deleting a queue item.
Assume 100,000 reminders/day with a morning burst of 1,000/s. A due index and bounded worker pool are enough for an initial design; a 500/s provider quota cannot deliver a simultaneous 100,000-reminder burst instantly. Even without retries the dispatch needs at least 200 seconds. State a due-to-provider lateness target and show admission or smoothing if the product demands a narrower window.
A worker claims reminder v2, then the owner reschedules to v3. Before provider submission it rechecks v2 against current schedule state and skips stale work. If cancellation arrives after the provider accepted the send, the system can stop future attempts but cannot promise recall. For ambiguous provider timeouts, retain one operation key and reconcile according to the provider's capabilities.
Store instants in UTC and preserve the user's timezone if recurrence is later added. Daylight-saving gaps and repeated times need an explicit product rule. Reminder execution is at least once internally; deduplicate business delivery where possible and document provider limitations.
Show answer and explanation
Answer: A process timer alone loses work on restart. A durable due index plus leases recovers unfinished occurrences, while version checks reject obsolete schedules. Track due lag, provider throttles, cancellation races and unknown-outcome age rather than reporting only that the scheduler process is healthy.
Deep dive: dispatch authorization is not proof of delivery
The basic reminder baseline persists a due occurrence and uses bounded workers. Extend it to email, SMS or push by separating scheduled intent, current preference eligibility, provider submission and user-visible delivery evidence. Start with one channel and one provider; adding a fallback provider changes duplicate and uncertainty semantics. This exercise's figures and states are original assumptions, not a provider service guarantee.
Carry identities across the whole path
schedule(id, tenant_id, owner_id, version, due_at, state)
occurrence(id, schedule_id, version, nominal_due_at, state)
delivery(id, occurrence_id, recipient_id, channel, purpose, provider,
operation_key, authorized_policy_version, state, provider_message_id)
attempt(delivery_id, attempt_number, claim_generation, outcome)
provider_event(provider, event_id, delivery_id, provider_message_id, type)
UNIQUE(occurrence_id, recipient_id, channel, purpose)
UNIQUE(provider, event_id)Occurrence identifies the scheduled business action, delivery identifies one recipient/channel purpose, and attempt identifies worker/network work. Preserve the delivery operation key across retries to the same provider under its supported deduplication contract and retention horizon. A fresh lease or DLQ redrive attempt must not create a fresh business send identity. Fingerprints pin the recipient destination, approved template/content version and relevant parameters; changed meaning is a new authorized action, not a compatible retry.
Schedule creation/reschedule/cancel commits its current version and publication intent together. Due scanning and duplicate queue delivery may create repeated work, but the authoritative occurrence/delivery transition and uniqueness guard choose one accepted identity. A lease only assigns execution work; it does not grant permission to send an obsolete schedule or to contact someone whose preferences changed.
Choose one policy decision boundary
Immediately before first dispatch authorization, atomically check current schedule version/state, tenant/recipient access, channel/purpose preference and destination validity, and persist authorized intent. If an opt-out or cancellation wins first, suppress the unstarted delivery. If dispatch authorization wins first, a later preference change cannot guarantee that an already submitted message is recalled. UI wording must reflect that boundary. A best-effort recheck reduces some races but cannot atomically commit with an arbitrary external provider.
The first version may serialize the delivery decision and preference mutation through a recipient-scoped authority. A check in a stale gateway cache is not the same guarantee. Transactional/service-critical categories need an explicitly separate product policy; do not bypass all opt-outs merely by labelling a payload important. Authentication and tenant ownership remain mandatory for those categories too.
Read the diagram
Later opt-out suppresses new intent; it does not erase evidence of an uncertain submitted effect.
An authorized-but-unknown delivery needs reconciliation even if the schedule was later cancelled. Prefer querying known provider identity/status. If the contract permits retry under the same dedupe key, verify its actual dedupe lifetime before doing so. Without safe retry/status support, choose an explicit hold/manual-resolution or duplicate-risk policy. Do not silently route an unknown email to a second provider with a new key: provider B cannot know whether provider A already sent it. Cross-channel fallback also requires declared consent and duplicate/message semantics.
Preserve independent provider evidence
| Evidence | Meaning | Recovery or presentation |
|---|---|---|
| Submission authorized | Service permitted an external attempt | Not yet provider accepted or delivered |
| Provider result unknown | Acceptance may have happened | Reconcile the original delivery |
| Provider accepted | Provider accepted processing | Do not label recipient delivery complete |
| Delivered callback | Provider reports delivery under its definition | Preserve authenticated callback evidence |
| Bounce/failed callback | Provider reports a failure event | Apply declared retry/suppression policy and retain contradictory evidence |
Authenticate callback origin using the provider's mechanism, correlate tenant/provider/message identity and deduplicate event ID with the local effect. Unknown message callbacks are quarantined/reconciled; never let a claimed delivery ID mutate another tenant's row. Callback receipt time is not necessarily provider event order. A delayed “accepted” event must not overwrite delivered with a weaker state. A delivery and a later complaint can coexist as distinct facts; one enum ordered by arrival time loses information. Keep delivery evidence, failure/complaint evidence and future-contact policy separate, with explicit rules for ambiguous or contradictory events.
Budget useful capacity including retries
Suppose a provider permits 500 submissions/s and 100/s is reserved for retry/reconciliation, leaving at most 400/s for new sends under these assumptions. A burst of 100,000 new reminders needs at least 250 seconds to submit even before network/service overhead. If recovery continues to receive 350 new sends/s, only 50/s of that new-send budget drains an existing new-work backlog; a 100,000-item backlog then needs about 2,000 seconds. Use the actual admission split and avoid counting retries twice as fresh capacity.
Use per-tenant/channel quotas, bounded queue age/depth, request deadlines and provider concurrency. Defer, coalesce or expire reminders according to purpose-specific misfire policy; ten old reminders are not always useful as ten immediate messages. Backoff with jitter and bounded attempts, then route exhausted work to a DLQ retaining business identity and uncertainty. Redrive requires current policy and original-effect reconciliation before new submission. Monitor due-to-authorization, authorization-to-provider evidence, oldest unknown, callbacks pending correlation, opt-out suppressions and provider throttles independently.
Notification assessment: stop at the honest evidence
Question: A worker leased v2, but reschedule v3 commits before first dispatch authorization. May it submit because it already owns the lease?
Show answer and explanation
Answer: No. Recheck authoritative version/state and recipient policy before first dispatch. Scheduling ownership cannot authorize stale intent.
Question: Provider A may have accepted D before timeout. The recipient then opts out. Is provider B a safe automatic retry?
Show answer and explanation
Answer: No. Reconcile the original D/provider identity under its supported contract, preserve the later preference boundary and avoid a new fallback effect. A different provider cannot deduplicate A's unknown outcome.
Question: A delivered callback is followed by an older accepted callback. Should the visible state become accepted again?
Show answer and explanation
Answer: No. Deduplicate and correlate authenticated events, preserve stronger delivery evidence and process separate complaint/failure facts under policy. Arrival order is not a business state machine.
Score one point for occurrence/delivery/attempt identities, policy/dispatch arbitration, unknown-outcome reconciliation, callback correlation/evidence and bounded provider/recovery capacity. For the calendar/version mechanics, reuse Job Scheduler and To-do Reminders instead of inventing another due-time contract.
Shared foundation: Idempotency and Delivery Semantics
Idempotency and Delivery Semantics: Scope operation identities, couple deduplication to effects and resolve uncertain provider outcomes. Work its failure history before extending this design.
Shared foundation: Outbox, Inbox, Sagas and Reconciliation
Outbox, Inbox, Sagas and Reconciliation: Recover publication gaps, duplicate deliveries and uncertain compensation using durable business state. Work its failure history before extending this design.
Shared foundation: Reliability and Overload Control
Reliability and Overload Control: Bound deadlines, queues, concurrency and retry work; calculate safe admission and recovery. Work its failure history before extending this design.
Shared foundation: SLOs, Observability and Capacity
SLOs, Observability and Capacity: Define measurable user outcomes, calculate error budgets and diagnose finite-capacity failures with safe telemetry. Work its failure history before extending this design.
Write a design for a million-recipient campaign that includes queue age, opt-outs, and provider timeouts.
Your design draft
Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.
Self-review checklist
Self-guided practice. Automated AI feedback and code execution are not connected.