Building a Multi-Channel Alerting Pipeline at Billion-Scale
System DesignModel answerLast updated
Design a platform that takes events from internal services and delivers them to users through push, SMS, email and an in-app inbox, with retries, deduplication and celebrity-scale fanout.
Problem
A large social network wants a single alerting platform that every internal microservice can call. Services emit events such as a like on a photo, a direct message, a friend request, a login verification code, or a platform-wide announcement. The platform must turn those events into messages and deliver them to users over:
- mobile push (APNs for iOS, FCM for Android),
- SMS through third-party aggregators,
- email through an email gateway,
- an in-app notification center (inbox).
Functional requirements
- Channel routing: send each message to the right external provider or write it to the user's inbox.
- Preferences and collapsing: honor per-user channel opt-outs and quiet hours (Do Not Disturb). Merge bursts of similar events into one message, for example "Alice and 14 others liked your photo".
- Fanout: support single-recipient events (a direct message) and broadcast events (a creator with 20 million followers publishes a video).
- Inbox: users can page through their notification history and mark items as read.
Scale and quality targets
- 10 billion notifications per day: roughly 120K requests/s on average and 500K/s at peak.
- Latency: critical alerts (verification codes, DMs) must reach the external gateway within 2 seconds. Bulk traffic such as digests may take several minutes.
- Reliability: at-least-once delivery, no data loss once a request has been accepted, and no cascading backpressure when a third-party provider is slow or down.
- Idempotency: if an upstream service retries a trigger, the end user must not receive duplicate alerts.
What to cover in your answer
- API design: how internal services trigger notifications, and how clients read and update their inbox.
- Architecture: ingestion, queue layout, worker pools, preference evaluation, and provider dispatchers.
- Data model: inbox storage, user preferences, device tokens, and delivery status tracking.
- Failure handling and trade-offs: retries, dead-letter queues, slow providers, and how to handle very high-follower accounts.
State your assumptions and back-of-the-envelope numbers explicitly.
Hints
Hint 1
Start with capacity math: convert 10B/day into per-second rates, estimate payload size and inbox row size, and use them to justify a partitioned log and a wide-column inbox store. Also split traffic into priority tiers so urgent messages never wait behind bulk ones.
Hint 2
Make idempotency a two-layer idea: dedupe producer retries at ingestion with a key, and dedupe consumer redeliveries at dispatch with a conditional status write. Acknowledge that exactly-once to a phone is impossible and use provider collapse identifiers to hide the remaining duplicates.
Hint 3
For failures, isolate each provider with its own queue, rate limiter, circuit breaker and bulkhead; retry via delayed retry topics with jittered backoff instead of blocking a partition; and for a 20M-follower account avoid synchronous expansion by chunking, filtering to engaged users, throttling, and using a read-time merge for the rest.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
State assumptions first.
- Throughput: 10B/day is about 116K/s average and 500K/s at peak. Provision ingestion for around 1M/s so celebrity bursts do not cause rejections.
- Log volume: about 1 KB per trigger gives about 10 TB/day. Three days of retention at replication factor 3 is roughly 90 TB.
- Inbox: about 300 B per rendered row, times 10B rows/day, times 90 days of retention, is about 270 TB raw and 800 TB replicated. That calls for a horizontally partitioned wide-column store.
- Priority tiers: P0 (verification codes, DMs) under 2 s; P1 (likes, comments) seconds to tens of seconds; P2 (digests, marketing) minutes.
- Guarantee: at-least-once with deduplication, which gives effectively-once on the device. Exactly-once through APNs/FCM cannot be guaranteed, so the goal is to make duplicates rare and collapsible.
2. APIs
Trigger (internal, gRPC or REST):
POST /v1/notifications
{ "idempotency_key": "like:post123:user456",
"type": "POST_LIKE", "priority": "P1",
"recipients": {"user_ids": [789]} // or {"audience": {"followers_of": 42}}
"template_id": "like_v3", "params": {...},
"collapse_key": "likes:post123", "ttl_seconds": 86400 }
-> 202 Accepted { "notification_id": "..." }
202 means "durably accepted", not "delivered".
Inbox (client):
GET /v1/inbox?cursor=&limit=20returns items andnext_cursor.GET /v1/inbox/unread_countPOST /v1/inbox/readwith{"ids": [...]}or{"up_to": "<notif_id>"}. Theup_toform makes "mark all read" a single cheap operation.
3. Architecture
Producers -> Ingestion API -> Kafka (critical / standard / bulk, keyed by recipient)
-> Fanout service -> Processing workers
-> Channel queues (push / sms / email / inbox)
-> Provider dispatchers -> Status store
\-> retry topics -> DLQ
- Ingestion API (stateless): authenticate and validate, claim the idempotency key with
SET NXand a 24 h TTL, write to Kafka withacks=allandmin.insync.replicas=2, and only then return 202. Acknowledging after the durable write is what gives zero loss at ingestion. - Priority topics with separate consumer pools: a flood of digests cannot delay a verification code.
- Fanout service: expands audiences into recipient chunks (around 5K each) that are independently retryable and checkpointed.
- Processing workers: per recipient, load cached preferences, apply quiet hours and frequency caps, apply the aggregation window, pick channels and devices, render the localized template, write the inbox row, and emit one message per (channel, device). Quiet-hours items go to a delay queue rather than being dropped, except P0.
- Dispatchers: one pool per provider, each with its own token-bucket rate limiter, circuit breaker and bulkhead. If FCM degrades, only the FCM queue grows; Kafka absorbs the lag and nothing upstream blocks.
4. Data model
- Inbox (wide-column, e.g. Cassandra): partition key
user_id, clustering keynotif_id(time-ordered, descending); columns for type, actor list (for aggregation), object id, rendered text, collapse key, read flag, created time; 90-day TTL. One partition read serves a page and cursor pagination comes from the clustering order. - Unread counter: separate Redis hash or counter table keyed by user; incremented on insert, reset or decremented on read.
- Preferences (relational + read-through cache):
user_id, category, channel, enabled, quiet_start, quiet_end, timezone, freq_cap. - Device tokens:
user_id, device_id, platform, token, app_version, last_seen, status. Mark tokens invalid when a provider reports them as unregistered. - Delivery status (key-value, 30-day TTL): key
(notif_id, channel, device_id); state (PENDING, SENT, FAILED, DLQ), attempts, provider message id, last error, updated time.
5. Deep dives
Idempotency in two layers
- Ingestion: the idempotency key stops producer retries from creating new notifications.
- Dispatch: consumers can be redelivered after a crash or rebalance, so before calling the provider the dispatcher performs a conditional write on the delivery key and skips the send if it is already SENT.
- Residual window: a worker may die after the provider call but before the status write. Use
apns-collapse-idand FCMcollapse_keyso the device replaces rather than duplicates the alert.
Celebrity fanout (20M followers)
Never expand 20M recipients synchronously.
- Push path: page through the follower graph and emit chunk jobs to the bulk topic.
- Filter: push only to engaged followers (for example active in the last 7 days with notifications enabled), typically 10-20%.
- Throttle: spread sends over minutes to protect providers and avoid a thundering herd of users opening the app simultaneously.
- Pull path: do not write inbox rows for everyone else. Store one broadcast record per creator and merge it at read time with the user's personal partition. This is the fan-out-on-write versus fan-out-on-read trade-off: cheaper writes, slightly costlier reads.
Retries and DLQ
- Transient failures (429, 503, timeouts) go to tiered retry topics (for example 30 s, 5 min, 1 h) with exponential backoff and jitter, honoring
Retry-After. Never retry inline, since that blocks the partition. - Drop messages whose TTL has expired; a stale verification code has no value.
- After N attempts, route to a DLQ with alerting and a replay tool.
- An open circuit breaker pauses consumption for that provider so retries do not hammer a failing endpoint.
Slow providers
Bulkheads and per-provider queues keep failures local. Optionally fail over SMS or email to a secondary vendor, and for P0 consider falling back to another channel.
6. Trade-offs and common mistakes
- Returning 202 before the durable write, which loses data.
- One shared queue for all priorities, causing head-of-line blocking.
- Retrying inline or without jitter, which creates retry storms.
- Claiming exactly-once delivery instead of explaining dedupe plus collapse keys.
- Writing 20M inbox rows per celebrity post.
- Dropping quiet-hours messages instead of delaying them.
Operational metrics worth naming: end-to-end P0 latency, queue lag per provider, delivery success rate, DLQ depth, and duplicate rate.