Build a scalable alert delivery platform with multi-channel support
System DesignModel answerLast updated
Design an event-driven system that ingests alert events, fans out to subscribers, and delivers through push, email, SMS, and in-app channels with reliability and preferences.
You're tasked with architecting a platform that accepts alert events from upstream services and delivers them to end users through multiple channels: push notifications, email, SMS, and in-app messages.
The system must handle:
-
Event ingestion and subscriber resolution: Upstream services publish events (e.g., status updates, promotions, security alerts). The platform determines which users should receive each event based on topic subscriptions or explicit targeting.
-
Multi-channel delivery: Route each notification to the appropriate channels (push, email, SMS, in-app) based on the event type and user preferences.
-
Reliability patterns: Implement retry logic, handle provider failures gracefully, ensure idempotency, prevent duplicate deliveries, and use dead-letter queues for persistent failures.
-
User control: Support per-channel opt-outs, quiet hours (time windows when non-urgent notifications are suppressed), and frequency caps.
-
Priority tiers: Critical events (e.g., security codes, time-sensitive updates) must deliver within seconds, while lower-priority marketing messages can tolerate delays or batching.
-
Observability: Track delivery status, identify bottlenecks, and provide APIs for querying notification history.
Assume:
- ~10 million events per day, with peaks reaching 2,000 events/second
- Average fanout of 20 recipients per event, with occasional broadcasts to millions
- Third-party provider quotas and costs are real constraints
Present your design including APIs, data model, architecture diagram, and how you'd address reliability, deduplication, ordering, and rate limiting. Discuss trade-offs and operational considerations.
Hints
Hint 1
Separate ingestion volume from fanout volume—they have different scaling characteristics and the fanout is typically much larger
Hint 2
Use priority-based message queues or topics to prevent low-priority bulk campaigns from blocking urgent transactional alerts
Hint 3
Deduplication requires a deterministic identifier; consider hashing (alert_id, user_id, channel) to make retries idempotent
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is transforming a stream of alert events into millions of individual deliveries across heterogeneous channels, while maintaining reliability and respecting user preferences. The architecture separates concerns into distinct stages—ingestion, fanout, routing, and delivery—each with its own scaling and reliability strategy.
1. Requirements and Scale
Functional goals:
- Accept alert events from internal services
- Resolve subscribers per event (via topic subscriptions or direct targeting)
- Deliver via push (APNs/FCM), email, SMS, and in-app inbox
- Respect user preferences: channel opt-outs, quiet hours, frequency limits
- Provide delivery status tracking
Non-functional constraints:
- Latency SLAs by priority:
- P0 (critical/transactional): <5s end-to-end p99
- P1 (informational): <1 minute
- P2 (marketing/bulk): best-effort, may batch over hours
- Availability: 99.99% for ingestion; producers must never block on downstream provider failures
- Delivery guarantee: at-least-once internally, effectively-once to users via deduplication
Capacity estimates:
- Events: 10M/day ≈ 115/s average, ~2k/s peak
- Deliveries (assuming 20× fanout): 200M/day ≈ 2.3k/s average, ~25k/s peak
- Storage: ~100 GB/day for delivery logs, retained 30–90 days
Key insight: Ingestion throughput is modest, but fanout volume is large and provider capacity (Twilio rate limits, APNs quotas, email sending limits) becomes the bottleneck.
2. API Design
POST /v1/alerts
Body: {
idempotency_key: string (required),
alert_type: string,
priority: "P0" | "P1" | "P2",
targeting: { topic: string } | { user_ids: string[] },
payload: object,
template_id: string,
ttl_seconds: int,
dedup_key?: string
}
Returns: 202 Accepted { alert_id }
PUT /v1/users/{user_id}/preferences
Body: {
channels: { sms: bool, email: bool, push: bool },
quiet_hours: { start: "22:00", end: "07:00", timezone: string },
per_type_overrides: { promo: { push: false } }
}
POST /v1/subscriptions { user_id, topic }
DELETE /v1/subscriptions { user_id, topic }
GET /v1/alerts/{alert_id}/status
GET /v1/users/{user_id}/inbox?cursor=...
Publishing is asynchronous (202 response). The mandatory idempotency_key allows producers to retry safely.
3. Data Model
- alerts table:
alert_id(PK), type, priority, payload, ttl, created_at. Enforce dedup via unique constraint on(producer_id, idempotency_key)or atomic RedisSETNXwith TTL. - subscriptions (DynamoDB/Cassandra): partition by
topic_id, cluster byuser_idfor efficient fanout pagination. Maintain reverse index(user_id, topic_id)for user management UI. - preferences (key-value store + Redis cache):
user_id→ settings. Read on every delivery decision, so caching is critical. - devices:
user_id→ push tokens, platform, last active timestamp. - notification_log (wide-column store with TTL):
notification_id(hash of alert_id + user_id + channel) → status (queued/sent/delivered/failed/suppressed), attempts, provider message ID, timestamps. In-app inbox uses separate table partitioned byuser_id.
4. Architecture
Producers
↓
Ingestion API (validates, deduplicates, persists)
↓
Kafka topics partitioned by priority [alerts.p0 | alerts.p1 | alerts.p2]
↓
Fanout Workers (resolve subscribers, chunk for scale)
↓
Kafka [deliveries] partitioned by user_id
↓
Router/Filter (preferences, quiet hours, rate limits, dedup)
↓
Kafka per channel × priority [channel.push.p0, channel.email.p1, ...]
↓
Channel Workers → Provider Adapters (APNs/FCM, SendGrid/SES, Twilio)
↓
Status Updates (provider callbacks/webhooks) → notification_log
↓
Retry topics (30s, 5m, 1h delays) / Dead Letter Queue
Flow details:
-
Ingestion service: Validates payload, checks idempotency key, writes alert record, publishes to Kafka. Does minimal work to stay fast and available.
-
Fanout workers: For targeted events (
user_ids), emit one delivery task per user. For topic-based broadcasts, paginate subscribers in chunks (~1k users per chunk), emit chunk tasks, process in parallel. Checkpoint progress per chunk for resumability. Large broadcasts go to P2 queue and are rate-limited. -
Router/filter stage applies per-user logic:
- Check opt-outs (global and per-type; legally required for SMS/email)
- Select channels and apply fallback (e.g., push if device active, else SMS for P0, else email)
- Enforce quiet hours (defer P1/P2 to delay queue; P0 bypasses)
- Apply frequency caps (sliding window counters in Redis)
- Dedup check (conditional write on
notification_id)
-
Channel workers: Render templates (with localization), invoke provider APIs via adapter interface, write status to notification_log. Isolated worker pools per channel prevent cascading failures (SES outage doesn't block push).
5. Reliability and Retries
- At-least-once consumption: Commit Kafka offsets only after writing to notification_log.
- Error classification:
- Retryable (5xx, timeouts, 429): publish to tiered retry topics (retry-30s, retry-5m, retry-1h) with exponential backoff and jitter. Avoids head-of-line blocking.
- Permanent (invalid token, unsubscribed): mark failed, prune device token or flag phone number.
- After max attempts or TTL expiry, send to DLQ with full context for manual review and replay.
- TTL enforcement: Drop expired notifications (e.g., "delivery arriving in 2 min" sent 1 hour late is harmful).
- Provider failover: Maintain ≥2 providers per channel. Circuit breakers detect failures and route traffic to healthy provider.
6. Idempotency and Deduplication
- Deterministic ID:
notification_id = hash(alert_id, user_id, channel). Before sending, perform conditional write (e.g., DynamoDB condition on status transitionnull → queued) or RedisSETNXwith TTL. - Kafka redelivery becomes a no-op if notification already processed.
- Pass notification_id as idempotency key to providers that support it.
- Content dedup: Optional
dedup_key(e.g.,order_123_status) allows collapsing rapid updates. Use push notification collapse IDs or suppress duplicates within a time window.
Note: True exactly-once delivery to external SMS/email APIs is impossible. Design narrows the window and accepts rare duplicates.
7. Ordering
Global ordering is unnecessary and expensive. What matters:
- Per-user ordering for related events (e.g., "picked up" before "delivered").
- Partition delivery topics by
user_idor entity ID (e.g.,order_id). - Include sequence number or event timestamp in payload.
- In-app inbox sorts by timestamp. For push, compare event timestamp against last-sent state for that
dedup_keyto drop stale updates.
8. Rate Limiting
Three layers:
- Per producer (at ingestion): Token bucket to prevent runaway services from flooding the system.
- Per user per channel: e.g., ≤3 marketing pushes/day, ≤N SMS/hour. Use Redis sliding window counters. Excess messages either drop or accumulate into a digest.
- Per provider: Stay under Twilio/APNs/SES quotas using semaphores or rate-limiter middleware in channel workers.
9. Observability
- Metrics: Ingestion rate, fanout latency, per-channel delivery rates, retry/DLQ depth, provider error rates, p50/p99/p999 end-to-end latency by priority.
- Tracing: Distributed trace from alert ingestion through delivery, keyed by
alert_id. - Alerting: SLA violations (P0 >5s), DLQ buildup, provider circuit breaker trips, Kafka consumer lag.
- Status API: Query notification_log by
alert_idoruser_idto surface delivery state in dashboards.
10. Trade-offs and Alternatives
- Separate topics per priority adds operational complexity but is essential to prevent bulk campaigns from delaying critical alerts.
- Stateful vs. stateless workers: Stateless is simpler and scales horizontally. Stateful (e.g., Flink) can offer lower latency for dedup/aggregation but harder to operate.
- Push vs. pull for in-app: Store in inbox table and let clients poll/long-poll, or use WebSocket push. Polling is simpler; WebSocket reduces latency but requires connection management.
- Cost vs. latency: Batching (especially for email) reduces provider costs but increases latency. P0/P1 send immediately; P2 can batch.
Complexity
- Time: O(F × U) where F is fanout and U is average subscribers per event. Chunking and parallelism make this manageable.
- Space: O(A + D) where A is active alerts (small, TTL-based) and D is delivery log (200M/day, time-series pruned).
Common Mistakes
- Synchronous fanout in the ingestion path (blocks producers, kills availability).
- Single Kafka topic for all priorities (head-of-line blocking).
- No idempotency key enforcement (duplicate sends under retry).
- Ignoring TTL (delivering stale time-sensitive notifications).
- Not isolating channel workers (one provider failure cascades to all channels).