Design: notification system
Services emit events; the notification service dedups, checks preferences and caps, renders per channel, and queues sends by priority to channel workers that call APNs, FCM, email and SMS providers with retries.
Fundamentals you'll use
How it works
- Separate queues and workers per priority and channel, so a bulk campaign never delays an OTP.
- Dedup on an idempotency key (event, user, channel) before every provider call.
- Check preferences, opt-outs, quiet hours and caps centrally, at send time, not in each producer.
- Retry 429s and 5xx with backoff and jitter; stop on permanent errors like APNs 410 Unregistered.
- Exactly-once to a person doesn't exist: per category, decide whether a duplicate or a miss is worse.
Check yourself
Answer to mark it learned; your answers aren't scored.
During a marketing campaign to 30M users, login OTP texts arrive 8 minutes late. Every notification goes through one shared queue and one worker pool. What's the right fix?
Go deeper
Full explanation
Requirements
Functional: send push (iOS, Android), email, SMS and in-app messages; transactional (OTP, receipts, alerts) and marketing (digests, campaigns); per-user preferences by category and channel; scheduling and quiet hours; delivery status. Non-functional: OTPs and security alerts in seconds; never the same notification twice; never against an opt-out; survive provider outages; a campaign to millions must not delay an OTP.
Scale (assumed): 100M users × 10 notifications/day ≈ 1B/day ≈ 12k/s average; campaigns spike far higher.
Questions I'd ask:
- Which categories are critical (OTP, fraud) and which are bulk (marketing)?
- Who owns templates and localization: producers or the platform?
- For each category, what's worse: a duplicate or a miss?
API and data model
POST /notify {event_id, user_id, category, template, data}; event_id is the producer's Idempotency key. Tables: preferences(user_id, category, channel, enabled), devices(user_id, token, platform, last_seen), deliveries(event_id, user_id, channel, status, attempts).
Architecture
Ingest API → priority queues (critical, transactional, bulk) (Queues vs streams (Kafka)) → orchestrator: dedup on (event_id, user_id, channel), preferences and opt-outs, frequency caps, quiet hours, template render → per-channel queues → channel workers that call APNs, FCM, an email provider and an SMS provider → status events (sent, bounced, token invalid) feed the delivery log and the in-app inbox.
The hard parts
- No duplicates, no misses: idempotency keys and per-category delivery semantics.
- Isolation and provider limits: priorities, rate limits, retries and failover.
Code Idempotent channel worker with permanent vs retryable errors
import random
import redis
r = redis.Redis()
TTL = 7 * 86400 # longer than any producer or worker retry window
PERMANENT = {"BadDeviceToken", "ExpiredToken", "Unregistered"} # APNs: never retry
MAX_ATTEMPTS = 5
def deliver(n: dict, provider, queue) -> str:
key = f"notif:{n['event_id']}:{n['user_id']}:{n['channel']}"
attempt = n.get("attempt", 0)
# Claim first. A crash after the claim leaves "sending", so redeliveries
# are dropped (at-most-once); for OTPs a reaper resends stale claims.
if attempt == 0 and not r.set(key, "sending", nx=True, ex=TTL):
return "duplicate" # also stops duplicate producer events
if not preferences.allows(n["user_id"], n["category"], n["channel"]):
r.set(key, "suppressed", ex=TTL) # checked at send time, not schedule time
return "suppressed"
res = provider.send(n["address"], render(n), idempotency_key=key) # if supported
if res.ok:
r.set(key, "sent", ex=TTL)
return "sent"
if res.reason in PERMANENT:
devices.disable(n["user_id"], n["address"]) # e.g. APNs 410 Unregistered
r.set(key, "failed", ex=TTL)
return "failed"
if attempt + 1 >= MAX_ATTEMPTS:
queue.dead_letter(n)
return "dead_letter"
# 429 / 5xx: re-enqueue with exponential backoff and full jitter
delay = random.uniform(0, min(300, 5 * 2 ** attempt))
queue.enqueue(dict(n, attempt=attempt + 1), delay_s=delay)
return "retrying"Real example
A bank's payment service emits payment_received for user u_42, times out waiting for the ack and emits it again. Both copies carry event_id=evt_981. The orchestrator claims evt_981:u_42:push with SET NX (7-day TTL): the first copy passes, the second is dropped. Preferences say push yes, SMS no; it's 23:10, inside the user's quiet hours, but the category is transactional, so it goes now through the transactional queue. APNs returns 410 Unregistered for an old iPad token: the worker deletes that token, and the iPhone gets the push.
Trade-offs +3 · −3
+ You gain
- One place enforces preferences, opt-outs and caps: producers can't spam users by accident.
- Priority and channel queues isolate failures: an SMS outage doesn't stall push.
- Idempotency keys make producer and worker retries safe.
− You pay
- Another hop and queue between the event and the user's phone, compared with calling the provider inline.
- Exactly-once to a person is impossible; you choose duplicates or misses per category.
- Provider quirks (token churn, collapsing, quotas, deliverability rules) need constant care.
Use it when
Several producer teams or channels, user-facing preferences, or volumes where provider quotas, retries and deliverability start to matter.
Avoid it when
One app sending a few transactional emails: call the provider's API directly with its retries. A platform is overhead until there are many producers or channels.
Numbers to know 5
- Volume: 100M users × 10 notifications/day (assumed) = 1B/day ≈ 12k/s average; campaigns spike far above.
- Dedup keys: 1B/day × ~100 B ≈ 100 GB per day of TTL; a 7-day TTL ≈ 700 GB.
- APNs: payload ≤ 4 KB (VoIP 5 KB); stores an undeliverable push up to 30 days.
- FCM: TTL 0–28 days; 4 collapse keys per device; Android discards all after 100 pending non-collapsible messages.
- Gmail bulk senders (5,000+/day, since Feb 2024): SPF, DKIM, DMARC, one-click unsubscribe, spam rate under 0.3%.
Common pitfalls 4
- One shared queue for OTPs and campaigns: a 20M-user blast puts login codes minutes behind.
- Retrying every error: resending to unregistered tokens or invalid numbers burns quota and sender reputation.
- Checking preferences in each producer: one team forgets, and you message users who opted out.
- Dedup keyed on a message ID generated per attempt: every retry looks new.
Interview questions 3
Answer out loud first, then reveal.
How do you make sure a user never gets the same notification twice?Show answer
I can't guarantee it end to end, so I shrink the window and pick the failure per category. Producers send a stable event_id; before sending, the worker claims (event_id, user, channel) with SET NX and a TTL longer than any retry. That removes producer and queue duplicates. The remaining window is a crash between the provider accepting and my status write: for OTPs I resend, for marketing I drop.
A campaign to 50M users must go out at 9 a.m. local time without hurting OTPs. How?Show answer
I isolate it and pace it. The scheduler expands the audience in batches per time zone into a bulk queue with its own workers, so OTPs never wait behind it. Bulk workers are rate-limited below provider quotas, leaving headroom for critical traffic. Preferences, unsubscribes and caps are checked at send time, not when the campaign was built, because users opt out in between. I watch send rate, provider errors and unsubscribes live, with a kill switch.
Your SMS provider starts returning 5xx. What happens?Show answer
Workers retry with exponential backoff and jitter, so we don't hammer a struggling provider. When the error rate crosses a threshold, a circuit breaker opens and critical traffic such as OTPs fails over to the secondary provider; bulk SMS waits in its queue, or falls back to push or email when the category allows. Messages that exhaust retries go to a dead-letter queue for replay. I alert on queue age and OTP delivery latency, because that's what users feel.
Deep dive 3
Dedup and delivery semantics
Queues deliver at-least-once and producers retry, so duplicates are normal input. Claim (event_id, user_id, channel) with SET NX and a TTL longer than any retry window, then send. The unavoidable window is a crash after the provider accepted the message but before the status write. Choose per category: for OTPs and fraud alerts a duplicate beats a miss, so a reaper resends stale claims (at-least-once); for marketing a miss beats a duplicate, so stale claims are dropped (at-most-once). Pass the key to providers that accept idempotency keys. Never key dedup on an ID generated per attempt.
Priorities, rate limits and provider failures
Bulkheads: separate queues and worker pools per priority and per channel, so a 20M-user campaign or a slow SMS provider can't stall OTP pushes. Rate-limit in three places (Rate limiting): per provider account (stay under quotas), per user (frequency caps on marketing) and per producer (a buggy service can't flood users). Retry 429s and 5xx with exponential backoff and jitter (Retries, backoff & circuit breakers), then dead-letter. Keep a second SMS and email provider and fail critical traffic over when a circuit breaker opens. A scheduler releases campaigns in batches by time zone, and preferences are re-checked at send time.
Channel specifics
APNs: HTTP/2, JSON payload up to 4 KB (5 KB for VoIP); best-effort and may reorder; holds an undeliverable push up to 30 days per apns-expiration; 410 Unregistered means delete the token. FCM: TTL 0–28 days; a collapsible message replaces an undelivered one with the same collapse key, and only 4 keys are stored per device; Android keeps up to 100 pending non-collapsible messages, then discards them all. Email: since February 2024, Gmail requires bulk senders (5,000+ messages/day) to use SPF, DKIM and DMARC, offer one-click unsubscribe and keep spam rates under 0.3%. SMS costs money per message: a fallback for critical messages, not the default. The in-app inbox is the source of truth.