Notification System
A provider callback for an old attempt arrives after a newer successful attempt.
Topic tools
Layout updated
Problem statement
Design a service that sends email, SMS, push and in-app notifications. Applications can request an immediate or scheduled send, respect recipient preferences and track delivery status.
Functional requirements
- Accept immediate and scheduled notification requests durably.
- Apply tenant rules and recipient preferences, select templates and route to eligible channels.
- Deliver through email, SMS, push or the in-app inbox. Track attempts and provider outcomes.
Non-functional requirements
- Dispatch urgent messages within 5 s and bulk within 5 min.
- Isolate providers; retries must not bypass current consent.
Back-of-the-envelope estimates
| Illustrative estimate |
|---|
| 10M requests/day ≈ 116/s; assume 5k/s burst |
| 3 channel attempts/request × 10M = 30M attempts/day |
Entities
| Entity / logical owner | Minimal authoritative fields and boundary |
|---|---|
| Notification(tenantId, requestId, recipient, type, dueAt) | Unique per tenant and request ID. Commit acceptance and publication intent together. |
| Delivery(id, notificationId, recipient, channel, priority, templateVersion, status) | Unique notification, recipient and channel. Store retry deadline and the current state. |
| Attempt(deliveryId, attemptNo, provider, providerMessageId, outcome) | Record each external call and reconcile unknown sends. |
| Schedule(notificationId, dueAt, ownerEpoch) and (eventId, payload, publishedAt) | Claim a due job and release it in one transaction. Replay unpublished events. |
API design
| Operation / input | Response and retry contract |
|---|---|
POST/notifications {requestId, userId, type, templateId, sendAt?} | 202 {notificationId} after durable acceptance. Retry with the same request ID. |
GET/notifications/{id} | Return notification and per-channel delivery status. Provider acceptance is separate from confirmed receipt. |
PUT/preferences {expectedVersion, channels, quietHours} | Update preferences. Recheck rules and consent before dispatch. |
GET/inbox?cursor=… | List the authenticated recipient’s in-app notifications. |
High-level design
How to draw this design
- Accept a notificationBusiness services, Notification , and PostgreSQL
- Prepare deliveryOrchestrator, preferences, templates, and scheduler
- Send by channelPriority queues, worker pools, and providers
- Track the outcomeDelivery status processor, delivery-state PostgreSQL, and dead-letter queue
Commit the request, route by preference and schedule, then dispatch. Provider callbacks or the in-app inbox inform status.
- State ownership
- The acceptance store owns the request. Delivery state tracks each channel attempt.
- Scale
- Separate worker pools and retry budgets by channel and tenant.
- Correctness
- A durable acceptance is separate from delivery. Check preferences and use a stable attempt identity.
- Failure and recovery
- After a provider timeout, check the original attempt before risking a duplicate send.
Notification System · Interview Overview
Follow one password-reset email. First accept it durably, then plan the email delivery and enqueue it, then send and record what happened. The Notification DB owns request acceptance. The Delivery State DB owns each channel’s progress, attempts and outcomes. Both boxes can start as tables in the same PostgreSQL cluster. The detailed diagrams below cover scheduling, channel routing and callbacks.
- Edge
- State
- Compute
- Messaging
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 9 flow steps
A · Durable notification acceptance
Return HTTP 202 only after the notification and event commit together in PostgreSQL. The publisher retries independently. A broker acknowledgement records publication, while a 202 records acceptance.
- Edge
- State
- Compute
- Messaging
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 4 flow steps
B · Process rules and route by channel
The same PostgreSQL cluster can start with separate tables for acceptance, schedules and delivery state. When a scheduled job becomes due, the scheduler commits a release event once and the publisher sends it back to the event bus. The orchestrator evaluates eligibility at dispatch and commits each delivery with its queue intent.
- Messaging
- Compute
- State
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 13 flow steps
C · Deliver and track status
Each worker applies timeouts, rate limits, bounded retries and circuit breakers for its channel. Email and SMS providers may send callbacks; push uses the signals actually available. An external provider accepting a send is different from a confirmed delivery. In-app writes are idempotent by delivery ID.
- Messaging
- Compute
- State
- Edge
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 20 flow steps
End-to-end flow
A. Commit the notification and event, return 202, then publish asynchronously.
B. When due, resolve recipients, preferences, priority and template version. Commit delivery rows and their entries before routing work.
C. Workers record attempts, dispatch under quotas and update delivery state. Callbacks and refine external outcomes.
High-level design component walkthrough
Business Services
Request a notification.
Why, tradeoff and connected operations
Pass a stable request ID on every retry.
Tradeoff: The caller must reuse the ID for the same request.
Connected operations: 1. Request notification
Notification API
Validate requests and return 202 after commit.
Why, tradeoff and connected operations
Acceptance is independent of provider latency.
Tradeoff: A database outage prevents durable acceptance.
Connected operations: 1. Request notification; 2. Commit request +
PostgreSQL · Notification + Outbox
Own notification records and publication intent.
Why, tradeoff and connected operations
commits a notification and its event in one transaction. A unique request key makes retries return the original notification ID.
Tradeoff: The database must sustain acceptance and writes.
Connected operations: 2. Commit request + ; 3. Read accepted event
Outbox Publisher
Read committed rows and publish to the broker.
Why, tradeoff and connected operations
Retry after crashes and mark rows published only after broker confirmation.
Tradeoff: A crash after publish can produce duplicates.
Connected operations: 3. Read accepted event; 4. Publish via event bus
Notification Orchestrator
Check preferences, choose a template and decide which channels to use.
Why, tradeoff and connected operations
One delivery key per notification, recipient and channel keeps repeated events from creating extra work.
Tradeoff: A preference change can happen after planning.
Connected operations: 4. Publish via event bus; 5. Save delivery +
Delivery State DB · PostgreSQL
Own per-channel delivery records, attempts and outcomes. Store dispatch intent with each delivery row.
Why, tradeoff and connected operations
records delivery state and queue intents atomically. Unique delivery IDs and conditional status updates make replay safe.
Tradeoff: High fan-out increases transactional write load.
Connected operations: 5. Save delivery + ; 6. Publish delivery job; 9. Record attempt and status
Priority / Channel Queues
Isolate critical, transactional and bulk work by channel.
Why, tradeoff and connected operations
Separate lanes protect urgent work and allow tenant fairness.
Tradeoff: Capacity must be reserved across workers and provider quotas.
Connected operations: 6. Publish delivery job; 7. Consume job
Channel Worker Pools
Claim a delivery, record an attempt and dispatch it.
Why, tradeoff and connected operations
Separate pools apply provider quotas, timeouts and circuit breakers.
Tradeoff: An external timeout can leave the outcome unknown.
Connected operations: 7. Consume job; 8. Send or write to inbox; 9. Record attempt and status
Providers / In-App Inbox
Send externally or make the notification available in the recipient’s inbox.
Why, tradeoff and connected operations
Providers can report acceptance and some supply later delivery callbacks.
Tradeoff: Acceptance does not prove receipt.
Connected operations: 8. Send or write to inbox
Business Services
Request a notification.
Why, tradeoff and connected operations
Pass a stable request ID on every retry.
Tradeoff: The caller must reuse the ID for the same request.
Connected operations: Submit with request ID
Notification API
Validate requests and return 202 after commit.
Why, tradeoff and connected operations
Acceptance is independent of provider latency.
Tradeoff: A database outage prevents durable acceptance.
Connected operations: Submit with request ID; Commit request +
PostgreSQL · Notification + Outbox
Own notification records and publication intent.
Why, tradeoff and connected operations
commits a notification and its event in one transaction. A unique request key makes retries return the original notification ID.
Tradeoff: The database must sustain acceptance and writes.
Connected operations: Commit request + ; Read committed
Outbox Publisher
Read committed rows and publish to the broker.
Why, tradeoff and connected operations
Retry after crashes and mark rows published only after broker confirmation.
Tradeoff: A crash after publish can produce duplicates.
Connected operations: Read committed ; Publish and confirm
Notification Event Bus
Buffer accepted and scheduled notification events.
Why, tradeoff and connected operations
The orchestrator can catch up independently of traffic.
Tradeoff: Consumers must handle redelivery.
Connected operations: Publish and confirm
Notification Event Bus
Buffer accepted and scheduled notification events.
Why, tradeoff and connected operations
The orchestrator can catch up independently of traffic.
Tradeoff: Consumers must handle redelivery.
Connected operations: Consume notification event; Publish due event
Notification Orchestrator
Resolve recipients, type, priority and channels when due.
Why, tradeoff and connected operations
One delivery key per notification, recipient and channel keeps repeated events from creating extra work.
Tradeoff: A preference change can happen after planning.
Connected operations: Consume notification event; Check recipient eligibility; Pin template version; Save schedule or delivery +
Preference Service
Resolve tenant policy, consent and quiet hours.
Why, tradeoff and connected operations
Apply rules by notification type and recheck eligibility before send.
Tradeoff: Rule checks add latency to dispatch.
Connected operations: Check recipient eligibility
Template Service
Resolve the template version and locale.
Why, tradeoff and connected operations
A pinned version keeps retries consistent.
Tradeoff: Old versions must remain available for pending deliveries.
Connected operations: Pin template version
PostgreSQL · Delivery State + Outbox
Own delivery rows, attempt history, schedule claims and dispatch intents.
Why, tradeoff and connected operations
records delivery state and queue intents atomically. Unique delivery IDs and conditional status updates make replay safe.
Tradeoff: High fan-out increases transactional write load.
Connected operations: Save schedule or delivery + ; Claim due rows; Commit due event to ; Read due event ; Read delivery
Scheduler · Due Jobs
Claim due jobs from durable schedule rows.
Why, tradeoff and connected operations
A conditional claim and insert release work atomically.
Tradeoff: Clock skew and failover affect dispatch time.
Connected operations: Claim due rows; Commit due event to
Outbox Publisher
Read committed rows and publish to the broker.
Why, tradeoff and connected operations
Retry after crashes and mark rows published only after broker confirmation.
Tradeoff: A crash after publish can produce duplicates.
Connected operations: Read due event ; Publish due event
Channel Router · Outbox Relay
Publish committed delivery jobs into channel and priority lanes.
Why, tradeoff and connected operations
The router can retry broker publication without rerunning business rules.
Tradeoff: Workers must handle duplicate messages.
Connected operations: Read delivery ; Publish by channel + priority; Publish by channel + priority; Publish by channel + priority; Publish by channel + priority
Email Queue
Buffer email jobs by priority.
Why, tradeoff and connected operations
Buffer email jobs by priority.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Publish by channel + priority
SMS Queue
Buffer SMS jobs by priority.
Why, tradeoff and connected operations
Buffer SMS jobs by priority.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Publish by channel + priority
Push Queue
Buffer push jobs by priority.
Why, tradeoff and connected operations
Buffer push jobs by priority.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Publish by channel + priority
In-App Queue
Buffer inbox jobs by priority.
Why, tradeoff and connected operations
Buffer inbox jobs by priority.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Publish by channel + priority
Email Queue
Buffer email jobs by priority.
Why, tradeoff and connected operations
Buffer email jobs by priority.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Consume job
Email Workers
Apply email provider budgets and retry policy.
Why, tradeoff and connected operations
Apply email provider budgets and retry policy.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Consume job; Send with delivery ID; Record attempt / result; Quarantine exhausted work
Email Provider
Accept email jobs and report outcomes where supported.
Why, tradeoff and connected operations
Accept email jobs and report outcomes where supported.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Send with delivery ID; Delivery callback
PostgreSQL · Delivery State + Outbox
Own delivery rows, attempt history, schedule claims and dispatch intents.
Why, tradeoff and connected operations
records delivery state and queue intents atomically. Unique delivery IDs and conditional status updates make replay safe.
Tradeoff: High fan-out increases transactional write load.
Connected operations: Record attempt / result; Record attempt / result; Record attempt / result; Record attempt / result; Apply valid status transition
Dead-Letter Queue
Quarantine exhausted or invalid work.
Why, tradeoff and connected operations
Operators can inspect failures and replay eligible work using the original identity.
Tradeoff: Expired work must stay expired.
Connected operations: Quarantine exhausted work; Quarantine exhausted work; Quarantine exhausted work; Quarantine exhausted work
Provider Webhooks
Validate callback signatures and accept provider events.
Why, tradeoff and connected operations
Provider message IDs link callbacks to recorded attempts.
Tradeoff: Callbacks can be missing, duplicated or out of order.
Connected operations: Delivery callback; Delivery callback; Validate callback
SMS Queue
Buffer SMS jobs by priority.
Why, tradeoff and connected operations
Buffer SMS jobs by priority.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Consume job
SMS Workers
Apply SMS provider budgets and fallback policy.
Why, tradeoff and connected operations
Apply SMS provider budgets and fallback policy.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Consume job; Send with delivery ID; Record attempt / result; Quarantine exhausted work
SMS Provider
Accept SMS jobs and report outcomes where supported.
Why, tradeoff and connected operations
Accept SMS jobs and report outcomes where supported.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Send with delivery ID; Delivery callback
Push Queue
Buffer push jobs by priority.
Why, tradeoff and connected operations
Buffer push jobs by priority.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Consume job
Push Workers
Send push messages and track provider acceptance.
Why, tradeoff and connected operations
Send push messages and track provider acceptance.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Consume job; Send with delivery ID; Record attempt / result; Quarantine exhausted work
APNs / FCM
Accept push jobs and report synchronous outcomes.
Why, tradeoff and connected operations
Accept push jobs and report synchronous outcomes.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Send with delivery ID
In-App Queue
Buffer inbox jobs by priority.
Why, tradeoff and connected operations
Buffer inbox jobs by priority.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Consume job
In-App Workers
Insert the inbox item by delivery ID.
Why, tradeoff and connected operations
Insert the inbox item by delivery ID.
Tradeoff: Capacity and errors are isolated by channel.
Connected operations: Consume job; Insert once; Record attempt / result; Quarantine exhausted work
In-App Inbox · PostgreSQL
Store inbox entries visible to the recipient.
Why, tradeoff and connected operations
A unique delivery ID supports idempotent inserts in . The inbox write and internal delivery status can share a transaction.
Tradeoff: and unread queries add indexes and cleanup work.
Connected operations: Insert once
Delivery Status Processor
Deduplicate callbacks and reconcile unknown outcomes.
Why, tradeoff and connected operations
Conditional updates prevent older events from overwriting a newer delivery outcome.
Tradeoff: Some providers supply no reliable receipt confirmation.
Connected operations: Validate callback; Apply valid status transition
Engineering control room
Deep dives — decisions, failures and recovery
Open a deep dive to follow the steps, try an example and see how recovery works.
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Synchronous vs asynchronous send | Accept fast and send asynchronously to isolate provider latency. |
| Direct provider call vs queue | Queue delivery work so workers can apply and retries. |
| One queue vs channel and priority lanes | Use separate lanes to protect urgent work and isolate provider limits. |
| Exactly once vs at-least-once attempts | Deduplicate internal work and reconcile external sends. Providers vary in what they guarantee. |
| One provider vs fallback | Use secondary providers for eligible messages and reconcile uncertain sends first. |
| Delivery status source | Use provider signals and , plus durable inbox writes for in-app delivery. |
Production scars & failure modes
A provider callback for an old attempt arrives after a newer successful attempt.
Look for: Compare provider attempt identity, callback version and current delivery state.
Recovery and invariant: Apply callbacks idempotently to the matching attempt; prevent terminal-state regression. Reconcile ambiguous sends instead of immediately switching providers and duplicating delivery.
| Component / failure | Impact | Recovery mechanism | Alternative / tradeoff |
|---|---|---|---|
| Publisher crashes | Some events may be published twice | Replay the and deduplicate by request or delivery identity. | Broker confirmation and DB update are separate steps. |
| Provider call times out | Send outcome is unknown | Reconcile before retry or fallback. | Some providers cannot confirm the outcome. |
| One tenant floods a lane | Queue age rises | Throttle the tenant and reserve critical capacity. | Bulk delivery may be delayed. |
| Region fails before due time | Scheduled work pauses | Fence old ownership and recover durable schedules and rows. | Regional loss depends on replication lag. |
60-second interview summary
The validates a notification request and commits it with an event before returning 202. A publisher moves the event to the broker. Scheduled requests are released from durable state when due.
The orchestrator applies preferences, selects a template and records one delivery per recipient and channel. The channel router publishes committed jobs into priority lanes. Separate workers enforce quotas and retry limits, send to providers, or write to the in-app inbox.
Provider acceptance and confirmed delivery are separate states. We record attempts and process callbacks or reconcile uncertain outcomes. Stable delivery IDs make internal replay safe. During regional failover we fence the old owner and resume from replicated schedule, delivery and state.
Practice questions and answers
Illustrative exercises. Predict the outcome before revealing the explanation.
SMTP is down. Should push delivery slow down too?
No, if provider queues, worker concurrency and retry budgets are isolated. Email backlog grows; push continues. Alert on email age and bound retries by message deadline. A shared saturated pool would violate that isolation.
The provider timed out after accepting an email. Is immediate failover safe?
The outcome is unknown. Persist the attempt identity and reconcile with the same provider using its status or support. Switching providers can duplicate delivery. Without that support, explicitly choose between possible loss and duplicates.
The API committed the notification, then crashed before enqueueing. Is 202 safe?
Only if durable dispatch intent was committed atomically with the notification, such as an . A relay retries publication and consumers deduplicate. A database write followed by an unprotected queue publish leaves a loss window.
Explain it without looking
Explain at-least-once attempts and duplicate prevention
Reveal answer
Give each request and each delivery a stable identity.
Transactions and unique keys protect internal state across retries.
An external provider may still deliver twice if it cannot deduplicate or confirm a send.
Explain provider outages and fallback
Reveal answer
Open the circuit and fall back only when policy allows.
A failed provider should consume a bounded amount of worker capacity.
Fallback adds cost and can duplicate a message after an uncertain send.
Explain priority queues and tenant fairness
Reveal answer
Reserve capacity for urgent messages and share capacity within each class.
An OTP can leave promptly even when tenants launch bulk campaigns.
Strict priority can starve bulk work, so give it a controlled share.
Explain retry storms and
Reveal answer
Pace retries and cap the amount of work waiting.
A recovering provider needs spare capacity to handle new sends and retries together.
Backoff improves stability at the cost of delayed delivery.
Explain multi-region failures and scheduled jobs
Reveal answer
Recover durable schedules and fence the old dispatch owner.
A conditional claim under the active region prevents competing owners from releasing the same due job.
Asynchronous cross-region replication can lose recently accepted work. Synchronous replication adds acceptance latency.
Revision checklist
Revision checklist
- Reconstruct at-least-once attempts and duplicate prevention: Give each request and each delivery a stable identity.
- Reconstruct provider outages and fallback: Open the circuit and fall back only when policy allows.
- Reconstruct priority queues and tenant fairness: Reserve capacity for urgent messages and share capacity within each class.
- Reconstruct retry storms and : Pace retries and cap the amount of work waiting.
- Reconstruct multi-region failures and scheduled jobs: Recover durable schedules and fence the old dispatch owner.
- Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
- Explain one alternative and exactly which guarantee you would relax.
- Redraw the request and recovery paths without looking; mark what required a hint.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope channels, scheduling, consent and what delivery status means. |
| 15–30 min | High-level design | Draw durable acceptance, orchestration and isolated delivery lanes. |
| 30–45 min | Deep dives | Walk through duplicate sends, provider fallback and fairness. |
| 45–55 min | Failure and recovery | Explain retry pacing and scheduled recovery after regional failure. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |
On this page
- Problem statement
- Functional requirements
- Non-functional requirements
- Back-of-the-envelope estimates
- Entities
- API design
- High-level design
- End-to-end flow
- High-level design component walkthrough
- Engineering control room
- Deep dives — decisions, failures and recovery
- Tradeoffs and alternatives
- Production scars & failure modes
- 60-second interview summary
- Practice questions and answers
- Explain it without looking
- Revision checklist
- 60-minute interview walkthrough