System Design - Notification Service
1. Requirements and clarification
Design a notification service for several million users. Business events may trigger notifications by email, mobile push, or in-app messages.
Preferences: notifications are enabled by default, but users can disable categories (messages, activity, promotions) and choose their channels. Essential security alerts follow a specific policy and are not suppressed by a marketing unsubscribe; their channel must be appropriate and comply with applicable obligations.
Questions to ask: average and peak throughput? Number of recipients per event? Acceptable latency by priority? Required ordering? Provider SLAs? Retention and expiration? Regulatory constraints? Budget?
2. Proposed overall architecture
flowchart TB
App[Business applications] -->|Business events| Bus[(Event Bus / Pub-Sub)]
Bus --> Ingest[Notification Service: ingestion]
Ingest --> Dedup[(Event registry / idempotency)]
Ingest --> Fanout[Recipient resolution / fan-out]
Pref[(Users and preferences DB)] --> Fanout
Fanout --> Policy[Policy: categories, channels, priorities, TTL]
Policy --> DB[(Notifications and attempts DB)]
Policy --> CQ[(Critical queue)]
Policy --> NQ[(Normal queue)]
CQ --> CW[Dedicated critical workers]
NQ --> NW[Normal workers]
NW --> Rate[Global and per-provider rate limiter]
CW --> Rate
Rate --> CB[Circuit breaker / provider routing]
CB --> Primary[Primary email / push provider]
CB --> Secondary[Secondary email / push provider]
NW --> InApp[In-app service]
CW --> InApp
Primary --> Status[Delivery results / callbacks]
Secondary --> Status
InApp --> Status
Status --> DB
NW --> Retry[(Delayed retry queue)]
CW --> Retry
Retry -->|After delay| NQ
Retry -->|Critical according to policy| CQ
NW --> DLQ[(Dead Letter Queue)]
CW --> DLQ
DB --> API[API: preferences, history, status]
Client[User client] --> API
Metrics[Logs / Metrics / Traces / Alerts] -.-> Ingest
Metrics -.-> NW
Metrics -.-> CW
Metrics -.-> RateReading the diagram: a business event is distinct from individual notifications. Fan-out determines recipients and their channels. Queues decouple production from delivery. Expiration policies and provider limits still apply to retries.
The diagram is conceptual: the in-app service may have its own queue, and retries should ideally be separated by channel and priority. Status transitions must be atomic and consistent with job publication, for example through a transactional outbox.
3. Respecting user preferences
The database stores preferences by category × channel, together with the policy for essential notifications. Each event is not automatically broadcast to every user.
flowchart LR
Event[MessagePublished groupId=42] --> Resolver[Resolve group members]
Resolver --> Preferences[Read preferences and exclusions]
Preferences --> Filter{Notification allowed?}
Filter -->|No| Skip[Skip]
Filter -->|Yes| Channels[Determine enabled channels]
Channels --> Jobs[Create one job per recipient and channel]Watch points: paginate or stream fan-out for 100,000 members, handle unsubscribes, snapshot preferences or check them at send time according to the chosen policy, and minimize personal data.
4. Handling 100,000 recipients
How can we handle 100,000 recipients without blocking critical alerts? Use batched fan-out, separate queues, dedicated workers, and controlled autoscaling. Rate limiting protects downstream systems.
flowchart TD
E[Event for 100,000 members] --> B[Split into batches / paginate]
B --> P[Evaluate preferences and priority]
P --> Critical[(Critical queue)]
P --> Normal[(Normal queue)]
Critical --> WC[Dedicated critical pool]
Normal --> WN[Scalable normal pool]
WC --> Provider[Provider throughput budget]
WN --> ProviderTradeoff: isolating critical resources reduces the risk of starvation, but reserves capacity that may sit unused. Priority within a single queue does not by itself guarantee low latency when all workers are busy.
5. Preventing duplicates after a crash
A queue may deliver a job more than once (at-least-once). Internal operations must be idempotent, for example using a unique key (eventId, userId, channel) and an atomic PENDING → SENDING transition.
sequenceDiagram
participant Q as Queue
participant W as Worker
participant DB as DB
participant P as Email provider
Q->>W: notificationId=123
W->>DB: Reserve attempt (atomic / lease)
DB-->>W: Reserved
W->>P: Send (idempotency-key=123 if supported)
P-->>W: 200 accepted
Note over W: Crash before persisting success
Q->>W: Redelivery of the same job
W->>DB: Check state / lease
W->>P: Retry with the same key if necessary
P-->>W: Deduplicated response if guaranteed by provider
W->>DB: Mark ACCEPTED
W->>Q: ACKEssential limitation: without a provider-recognized idempotency key or a reconciliation API, a crash between external acceptance and local persistence creates an ambiguous outcome. Retrying may duplicate the message; not retrying may lose it. A stable worker-side key alone cannot guarantee external exactly-once delivery.
Additional measures: attemptCount, leaseUntil, the provider message ID, delivery webhooks, an attempt log, and atomic deduplication. ACCEPTED does not necessarily mean DELIVERED.
6. Handling HTTP 429 and 503
- 429: respect Retry-After when present, and limit throughput globally and per provider.
- 503 / timeout: use exponential backoff with jitter, a maximum delay, and bounded retry counts and timing.
- Persistent outage: use a circuit breaker to avoid useless calls; retain valid messages in a durable queue.
- Permanent failure or exhausted retry policy: send to a DLQ for inspection and reprocessing, with alerts.
flowchart TD
Q[(Delivery queue)] --> W[Worker]
W --> Limit[Rate limiter]
Limit --> Provider[Provider]
Provider --> Result{Result?}
Result -->|Success| Done[Persist state, then ACK]
Result -->|429 / 503 / timeout| RetryPolicy{Retry allowed and TTL valid?}
RetryPolicy -->|Yes| Delay[(Delayed retry + backoff + jitter)]
Delay --> Q
RetryPolicy -->|No| DLQ[(DLQ / expiration according to cause)]
Result -->|Permanent error| DLQAvoid: sleeping inside a worker for several minutes; immediately retrying in a loop; sending 500 workers simultaneously to a provider capped at 1,000 requests/s.
7. Handling a 30-minute outage
Situation: 2 million normal notifications, 5,000 critical notifications, and a secondary provider that costs three times as much.
Decision: prioritize the secondary provider for critical notifications according to SLOs, budget, and capacity; keep normal notifications in a durable queue, rather than sending them to the DLQ solely because the provider is down. Expire obsolete messages.
flowchart TD
Q{Message priority?}
Q -->|Critical| C[Critical queue]
Q -->|Normal| N[Durable normal queue]
C --> Health{Primary available?}
Health -->|Yes| P[Primary provider]
Health -->|No| S[Secondary provider]
N --> Hold[Wait / delayed retries]
Hold --> Expired{TTL expired?}
Expired -->|Yes| Cancel[Mark EXPIRED]
Expired -->|No and primary recovered| PNuance: some critical notifications may justify multiple channels or a fallback, but avoid unintended duplicate sends.
8. Draining the backlog
How can we drain the backlog without penalizing new messages? Separate new notifications from the backlog, with a weighted scheduler and a shared rate limiter.
flowchart TD
New[(New notifications)] --> Scheduler[Weighted scheduler]
Backlog[(Backlog)] --> Scheduler
Scheduler --> TTL[Filter expired messages]
TTL --> Rate[Global rate limiter: 1,000 requests/s]
Rate --> Workers[Workers]
Workers --> Provider[Provider]Example budget: reserve 300 requests/s for new notifications and 700 requests/s for the backlog. If only 100 new notifications/s arrive, reallocate the unused 200 requests/s to the backlog, which then reaches about 900/s. For 2 million messages, the theoretical duration is 2,000,000 / 900 ≈ 2,222 seconds, or 37 minutes, excluding failures, overhead, and additional backlog messages.
Measure: queue depth, oldest message age, incoming and outgoing throughput, 429/503 rates, latency by priority, expired notifications, cost per provider, retries, DLQ, and delivery success.
9. Transactional outbox
Making notification creation reliable: if a notification is persisted before publishing a queue job, a crash between the two operations can lose the send. Store the notification and an outbox event in the same database transaction, then publish asynchronously.
sequenceDiagram
participant S as Notification Service
participant DB as DB + Outbox
participant Pub as Outbox Publisher
participant Q as Delivery Queue
S->>DB: BEGIN
S->>DB: INSERT notification + outbox event
S->>DB: COMMIT
Pub->>DB: Read unpublished outbox events
Pub->>Q: Publish job
Q-->>Pub: Broker ACK
Pub->>DB: Mark published
Note over Pub,Q: A crash may cause duplicates: handle with idempotency10. Minimal data model
Users(id, ...)
NotificationPreferences(user_id, category, channel, enabled, updated_at)
Notifications(id, event_id, user_id, category, priority, status, expires_at, created_at)
NotificationDeliveries(id, notification_id, channel, provider, status,
attempt_count, lease_until, provider_message_id, updated_at)
Outbox(id, event_type, payload, published_at, created_at)Useful constraints: uniqueness on the business deduplication key, an index on (status, priority, created_at) or actual access patterns, an index on expires_at for cleanup, and an index on expired leases. Indexes speed up some reads but increase write costs.
11. Decisions and tradeoffs
| Problem | Initial approach | Tradeoff / limitation |
|---|---|---|
| Coupling to business events | Event Bus + notification service | Event contracts and schema evolution |
| One event → many recipients | Paginated / batched fan-out | Latency and job volume |
| Delayed critical alerts | Dedicated queues and workers | Reserved capacity cost |
| Traffic spikes | Durable queue + autoscaling | Backpressure and downstream limits |
| Redelivered messages | Idempotent consumer | External exactly-once is not guaranteed |
| Crash after a provider call | Provider idempotency key / reconciliation | Depends on provider guarantees |
| HTTP 429 / 503 | Delayed retry, backoff, jitter, circuit breaker | Delays and expiration |
| Provider unavailable | Critical failover, normal backlog | Secondary provider cost ×3 |
| Recovery after an outage | Weighted scheduling + TTL | Freshness versus catch-up |
| Non-atomic database and queue operations | Transactional outbox | Additional publisher and deduplication |
12. Design checklist
- Clarify: channels, preferences, volumes, SLOs, ordering, priority, expiration.
- Separate: business events, fan-out, delivery jobs, providers.
- Explain the normal flow: event → recipients → preferences → jobs → send → status.
- Identify guarantees: at-least-once, idempotency, and the limits of exactly-once.
- Plan for failures: 429/503, retries, circuit breaker, failover, DLQ.
- Size the system: incoming and outgoing throughput, backlog, message age, provider capacity.
- Justify each choice through a business constraint and explain the tradeoffs.