Build a Multi-Channel Alerting Pipeline for a Social App
System DesignModel answerLast updated
Design a backend that turns events from many product services into push and in-app alerts, with preferences, batching, rate limits, priority lanes, and safe retries.
You are designing the alerting backend for a large social network. Many internal product services (comments, reactions, friend requests, direct messages, event reminders) emit events that may need to become user-facing alerts.
Alerts must reach users in two ways:
- As push messages on their mobile devices, via third-party push providers.
- As entries in an in-app alert list, including an unread count.
Whether email or SMS are also needed is part of what you should clarify.
What to cover
- Clarifying questions you would ask and the assumptions you pick (channels, event volume and burstiness, latency per alert type, user controls, and whether a duplicate or a missed alert is worse).
- A high-level architecture and the main data flow from producer to device.
- How producers submit events, and how you make submission safe to retry.
- How you check user preferences and eligibility before sending.
- How you group related events and limit how many alerts a single user receives.
- How urgent alerts are kept from getting stuck behind bulk traffic.
- How you deliver through third-party push providers, and how you handle failures, bad device tokens, and stale alerts.
- How you store the in-app list and keep unread counts correct.
- How you avoid duplicates when components retry.
- Which metrics you would monitor.
State your scale assumptions explicitly and discuss the main trade-offs.
Hints
Hint 1
Start by splitting the system into stages joined by durable queues: ingest, decide (preferences, dedup, grouping, rate limit), render, and per-channel delivery. Each stage can then scale and fail on its own.
Hint 2
Think about where duplicates come from: producer retries, consumer redelivery, and provider timeouts where you do not know if the send succeeded. A deterministic notification ID used as an idempotency key at each hop helps with all of them.
Hint 3
Use separate queues, consumer pools, or quotas for urgent traffic (messages, security) versus bulk traffic (reactions, digests), and decide which stage applies per-user caps and collapsing so a viral post does not flood one person.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Channels: mobile push and in-app list at launch; email and SMS are extensions behind the same delivery interface.
- Scale: about 500M users, roughly 2B events per day (average ~25k events/s, peaks 10x that during viral moments).
- Latency targets: direct messages and security alerts under ~2 s end to end; social activity (reactions, comments) within ~10-30 s; digests and reminders on a schedule.
- Users can toggle alerts per type and per channel and set quiet hours.
- A duplicate is annoying, but a missed urgent alert is worse. So: at-least-once delivery with idempotent dedup, not at-most-once.
Architecture
Producers -> Ingest API -> Durable log (partitioned by recipient)
-> Decision workers (prefs, dedup, grouping, rate limit)
-> Priority queues (urgent / normal / bulk)
-> Channel workers: Push | In-app | (Email/SMS later)
-> Push providers (APNs, FCM)
Side stores: preference store, device-token store, in-app alert store, dedup/rate-limit cache, metrics pipeline.
1. Ingestion contract
Producers call a thin API (or publish directly to a topic) with: event_type, recipient_id, actor_id, object_ref, priority, payload, created_at, and an idempotency key (for example hash(event_type, actor, object, recipient)). The API validates the schema, writes to a durable log such as Kafka, and acknowledges. Ingestion is asynchronous so a slow downstream never blocks product services. Partition by recipient_id so all events for one user are ordered and handled by one consumer, which makes grouping and rate limiting local.
2. Preferences and eligibility
Decision workers check, in order:
- Is the recipient active, not blocked by or blocking the actor, and not muted for this thread?
- Does the user allow this type on this channel? Quiet hours?
- Is there at least one valid device token for push?
Preferences are read from a cache in front of a sharded store (read-heavy, rarely changed). Quiet hours do not drop alerts: they defer push but still write to the in-app list. Cache staleness of a few seconds on opt-outs is acceptable, except for legal opt-outs, which should be read-through.
3. Grouping and rate limiting
- Collapsing: "Ana and 14 others liked your photo" rather than 15 pushes. Keep a per-user, per-object aggregation key; hold the first event for a short window (for example 5-30 s for reactions, zero for messages), then emit one grouped alert and update it as counts grow.
- Per-user caps: a token bucket per user per channel per category (for example 5 social pushes per 10 min). Overflow is folded into the in-app list or a later digest rather than dropped.
- Global protection: per-producer quotas so one misbehaving service cannot starve others.
State lives in Redis keyed by user, which is safe because partitioning by recipient gives a single writer.
4. Priority isolation
Use separate topics and worker pools per priority class: urgent (messages, security, 2FA), normal (social activity), bulk (digests, marketing). Urgent consumers are over-provisioned and never share a pool with bulk. Under overload, shed or delay bulk first and apply backpressure at the producer quota. Each class has its own SLO and alerting.
5. Push delivery
Push workers look up device tokens, render localized text from a template, and call APNs/FCM with a TTL (a "friend request" push is worthless after a day; a reminder expires at the event time).
Failure handling:
- Transient errors / 5xx / throttling: retry with exponential backoff and jitter, honoring provider rate limits; a circuit breaker per provider prevents hammering during an outage.
- Invalid or unregistered token: delete the token immediately, because repeated sends hurt provider reputation.
- Timeouts (outcome unknown): retry using the same collapse ID / notification ID so the provider or client can replace rather than duplicate.
- Exhausted retries: dead-letter queue, with the in-app entry still present so the user can see it.
Connection pooling and HTTP/2 batching are needed to reach tens of thousands of sends per second.
6. In-app list and unread count
Store alerts in a wide-column or sharded KV store keyed by (user_id, created_at desc), with fields id, type, group_key, payload, read_at. Writes are idempotent upserts on the notification ID, so a redelivered event rewrites the same row. Keep a per-user unread counter in Redis, incremented on insert and decremented or reset on read. Reconcile periodically from the store because counters drift. Apply TTL or retention (for example 90 days) and paginate with cursors.
7. Deduplication under retries
Defense in depth:
- The ingest idempotency key is checked against a short-lived set (SET NX with TTL of hours).
- The decision stage derives a deterministic
notification_idfrom the grouping key and window. - Channel workers record "sent" for that ID before or atomically with the send where possible; the in-app upsert is naturally idempotent.
- The push collapse ID makes a duplicate send replace the previous one on the device.
Perfect exactly-once is not achievable across a third-party provider, so the aim is at-least-once plus idempotency, which yields effectively-once for users.
8. Metrics
- Pipeline: ingest-to-send latency per priority (p50/p99), queue lag, retry and DLQ rates, provider error rates.
- Product: delivery rate, open/click rate, opt-out and uninstall rate per type, notifications per user per day.
- Quality guardrails: duplicate rate, invalid token rate, and cap-hit rate. Rising opt-outs are the signal that you are over-notifying.
Trade-offs
- Longer grouping windows reduce noise but add latency; make them per-type.
- Fan-out at write time (precompute per-user lists) is fast to read but costly for viral content; for very large audiences, use a pull or lazily materialized model.
- Strong preference consistency costs latency; accept a short staleness for most types.
Common mistakes
- Sending synchronously from the product request path.
- One shared queue for all traffic, so a viral spike delays messages.
- Dropping capped alerts instead of routing them to the in-app list or a digest.
- Never pruning invalid device tokens.
- Treating a provider timeout as failure and resending without an idempotency or collapse ID.
- Ignoring quiet hours and time zones.