The problem, stated properly
Design a notification platform that any product team can call with one API ("notify user U about event E") and that handles everything after: choosing the channel (push, SMS, email, in-app), personalizing and localizing the message, respecting user preferences and quiet hours, rate-limiting so users do not uninstall, retrying through flaky third-party providers, and tracking delivery. The trap in this question is treating it as plumbing: the hard parts are fan-out scale, third-party dependency management, and not annoying the user, which is a correctness problem of its own.
Scale first
- Volume: a large consumer product sends ~10-100 million notifications/day (order updates, likes, reminders, promos). That is ~1,000/sec average, 50-100x that when a marketing blast or a breaking-news event lands: design for ~100K/sec bursts.
- Fan-out: one trigger can mean millions of notifications (a celebrity posts; every follower gets one). A single API call can turn into hours of queued work, so the ingest path must decouple from delivery instantly.
- Latency classes: OTPs and security alerts need delivery in seconds; a promo can wait an hour. One size of queue fits nothing: priorities are a first-class design element.
The pipeline, stage by stage
- Ingest API: receives the request, validates it, stamps an idempotency key, writes it durably, and returns. Nothing slow happens here.
- Decision/orchestration service: for each notification, resolve the user, check preferences (does this user want marketing pushes at all?), quiet hours (batch it for morning), template + locale (render the final text), and channel selection (push first, SMS fallback if push is undeliverable and the message is critical, email for long content).
- Priority queues: one queue per (priority class, channel). A Kafka topic or SQS queue per lane keeps OTPs from queueing behind a 10-million-message promo blast.
- Channel workers: pools per channel that render final payloads and call providers: FCM/APNs for push, Twilio-class aggregators for SMS, SES-class services for email. Workers respect per-provider rate limits with token buckets.
- Delivery tracking: providers webhook back accepted/delivered/failed/bounced. These events update a delivery store that powers retries, fallbacks, and analytics.
The parts that are actually hard
- Idempotency and dedup: producers retry, queues deliver at-least-once, providers accept duplicates. You need dedup at every layer: idempotency key at ingest, message-ID dedup in workers (a Redis SETNX with a 24h TTL is enough), and provider-side idempotency keys where supported. A user who gets the same "your order shipped" push 3 times files it under spam, permanently.
- Provider failure and fallback: FCM is down, APNs is throttling, an SMS route to a country degrades. Circuit breakers per provider, automatic failover to a secondary provider for critical lanes, and dead-letter queues for messages that exhaust retries. SMS in particular has per-country routes with wildly different reliability and cost; routing tables are their own subsystem at scale.
- Token lifecycle (push-specific): device tokens rot constantly (app uninstalls, OS refreshes, device changes). Providers return invalid-token errors that must feed a cleanup loop, or you keep paying to send into the void. iOS delivery is especially opaque: APNs confirms acceptance, not display.
- Rate limiting the user, not the server: per-user caps (max N notifications/day by category) and fatigue models (if the last 5 pushes were never opened, demote this user). This is the difference between a notification system and an uninstall generator.
Preferences and quiet hours: the correctness problem nobody diagrams
Preference checks sound trivial until you enumerate them: global opt-outs, per-category toggles, per-channel toggles, quiet hours in the user's timezone (with DST), and legal compliance (marketing consent is revocable and must propagate fast; GDPR/Indian DPDP-style rules make this a hard requirement, not a nicety). The standard shape is a preference service with a read-optimized cache, because the decision service queries it for every single notification. Quiet hours convert "send now" into "send at 8 AM user-local," which means the scheduler (a delayed-delivery queue) is part of the core design, not a bolt-on.
Tradeoffs worth naming
- Push vs SMS vs email: push is free-ish and instant but silent if permissions are off (~50% of Android users globally deny them); SMS works everywhere but costs real money per message (~$0.05-0.10 in India, more internationally) and has carrier-level filtering; email is cheapest and richest but slowest and lands in tabs nobody opens. Critical alerts justify SMS cost; promos never do.
- Build vs buy: nobody builds their own APNs gateway, but owning the decision/orchestration layer in-house is what lets you do fatigue modeling and cross-channel logic that off-the-shelf tools do badly.
- Ordering: per-user ordering matters ("ride arrived" before "ride completed" is nonsense) but global ordering is impossible across channels. Sequence per user per channel, accept cross-channel races.
Production failure modes
- The retry storm: a provider outage makes every message retry, queues balloon, and when the provider recovers your backlog hits it like a DDoS and trips its rate limits again. Defenses: exponential backoff with jitter, max-age expiry (a 3-hour-old OTP is worthless, drop it), and admission control on retries.
- Duplicate delivery: at-least-once everything means duplicates are guaranteed eventually. Dedup windows and client-side suppression (same message ID within N minutes) are mandatory.
- Blast-induced self-DoS: a promo to 50M users at once also wakes 50M apps that then call your APIs. Stagger sends (bucket users over 15-30 minutes) or your notification system takes down your own product.
- Template regressions: a broken template variable ships "{user_name} your order {order_id}..." to a million users. Template validation and canary sends exist because this has happened at every company.
Common interview traps
- Designing one queue for everything. Priority lanes are the first thing the interviewer probes.
- Calling providers synchronously from the API. Third-party latency belongs behind a queue, always.
- Forgetting preferences and quiet hours entirely. It reads as never having used a phone.
- Treating "sent to provider" as "delivered." Delivery tracking is what separates a system from a hope.
Interview Q&A
Q: How do you guarantee a user is not spammed even if five different product teams all decide to notify them today?
A: Centralize the decision: every notification, from every team, flows through one orchestration layer that enforces per-user budget (say, max 3 marketing + unlimited transactional per day), fatigue scoring (demote users who never open), and dedup by content hash within a window. Individual teams can request anything; the platform owns the user's attention. This is why notification platforms get built as internal products with real authority, not as libraries.
Q: An OTP must arrive in under 10 seconds, 99.9% of the time. Walk me through the design.
A: OTP lane gets its own top-priority queue with a dedicated worker pool that no blast can starve. Two SMS providers behind a circuit breaker: on slow ack or failure from the primary, the worker fails over within ~2 seconds. Delivery SLA is measured from ingest to provider-ack via the tracking webhooks, and anything breaching it pages. Voice-call fallback for the residual failures. And OTPs expire from the queue itself: a message older than 60 seconds is dropped, because a stale OTP only confuses.
Problem ko sahi se samjho
Ek notification platform design karo jise koi bhi product team ek API se call kar sake ("user U ko event E ke baare mein notify karo") aur jo uske baad ka sab kuch handle kare: channel choose karna (push, SMS, email, in-app), message personalize aur localize karna, user preferences aur quiet hours respect karna, rate-limit karna taaki user uninstall na kare, flaky third-party providers ke through retry karna, aur delivery track karna. Is sawaal ki trap ye hai ki ise plumbing samajh liya jaaye: mushkil cheezein hain fan-out scale, third-party dependency management, aur user ko annoy na karna, jo apne aap mein ek correctness problem hai.
Pehle scale
- Volume: ek bada consumer product ~10-100 million notifications/day bhejta hai (order updates, likes, reminders, promos). Matlab ~1,000/sec average, jab marketing blast ya breaking news aaye to 50-100x: ~100K/sec bursts ke liye design karo.
- Fan-out: ek trigger ka matlab millions of notifications ho sakta hai (ek celebrity post kare; har follower ko ek). Ek API call ghanton ka queued work ban sakta hai, isliye ingest path ko delivery se turant decouple karna zaroori hai.
- Latency classes: OTPs aur security alerts ko seconds mein delivery chahiye; promo ek ghanta wait kar sakta hai. Ek size ki queue kisi pe fit nahi aati: priorities first-class design element hain.
Pipeline, stage by stage
- Ingest API: request receive karta hai, validate karta hai, idempotency key lagata hai, durably likhta hai, aur return. Yahan kuch slow nahi hota.
- Decision/orchestration service: har notification ke liye: user resolve karo, preferences check karo (kya ye user marketing pushes chahta hi hai?), quiet hours (subah ke liye batch karo), template + locale (final text render karo), aur channel selection (pehle push, agar push undeliverable hai aur message critical hai to SMS fallback, lambi content ke liye email).
- Priority queues: har (priority class, channel) ke liye ek queue. Har lane ka Kafka topic ya SQS queue rakhta hai ki OTPs 10-million-message promo blast ke peeche queue na karein.
- Channel workers: har channel ke pools jo final payloads render karke providers call karte hain: push ke liye FCM/APNs, SMS ke liye Twilio-class aggregators, email ke liye SES-class services. Workers per-provider rate limits token buckets se respect karte hain.
- Delivery tracking: providers wapas webhook karte hain accepted/delivered/failed/bounced. Ye events delivery store update karte hain jo retries, fallbacks aur analytics chalata hai.
Jo parts asal mein mushkil hain
- Idempotency aur dedup: producers retry karte hain, queues at-least-once deliver karti hain, providers duplicates accept karte hain. Har layer pe dedup chahiye: ingest pe idempotency key, workers mein message-ID dedup (24h TTL wala Redis SETNX kaafi hai), aur jahan supported ho wahan provider-side idempotency keys. Jo user "your order shipped" push 3 baar paata hai, wo ise hamesha ke liye spam mein daal deta hai.
- Provider failure aur fallback: FCM down hai, APNs throttle kar raha hai, kisi desh ka SMS route degrade ho gaya. Har provider pe circuit breakers, critical lanes ke liye secondary provider pe automatic failover, aur retries exhaust karne wale messages ke liye dead-letter queues. SMS ke per-country routes ki reliability aur cost wildly alag hoti hai; routing tables scale pe apna subsystem hain.
- Token lifecycle (push-specific): device tokens lagatar rot hote hain (app uninstall, OS refresh, device change). Providers invalid-token errors return karte hain jinka cleanup loop mein jaana zaroori hai, warna tum khaali mein bhejte rahoge. iOS delivery khaas taur pe opaque hai: APNs acceptance confirm karta hai, display nahi.
- Server nahi, user ko rate limit karna: per-user caps (max N notifications/day by category) aur fatigue models (agar pichle 5 pushes kabhi khule hi nahi, is user ko demote karo). Yehi farak hai notification system aur uninstall generator ke beech.
Preferences aur quiet hours: wo correctness problem jo koi diagram nahi karta
Preference checks trivial lagte hain jab tak enumerate na karo: global opt-outs, per-category toggles, per-channel toggles, user ke timezone mein quiet hours (DST ke saath), aur legal compliance (marketing consent revocable hai aur jaldi propagate hona chahiye; GDPR/Indian DPDP jaise rules ise hard requirement banate hain, nicety nahi). Standard shape ek preference service hai read-optimized cache ke saath, kyunki decision service ise har ek notification ke liye query karta hai. Quiet hours "abhi bhejo" ko "subah 8 baje user-local bhejo" mein badal dete hain, matlab scheduler (delayed-delivery queue) core design ka hissa hai, bolt-on nahi.
Tradeoffs jo naam dene layak hain
- Push vs SMS vs email: push free-ish aur instant hai par permissions off ho to khamosh (globally ~50% Android users deny karte hain); SMS har jagah kaam karta hai par per message asli paisa lagta hai (India mein ~$0.05-0.10, internationally zyada) aur carrier-level filtering hai; email sabse sasta aur richest par sabse slow aur un tabs mein jaata hai jo koi nahi kholta. Critical alerts SMS cost justify karte hain; promos kabhi nahi.
- Build vs buy: koi apna APNs gateway nahi banata, par decision/orchestration layer in-house own karna hi wo cheez hai jo fatigue modeling aur cross-channel logic deti hai jo off-the-shelf tools bura karte hain.
- Ordering: per-user ordering matter karti hai ("ride arrived" "ride completed" se pehle, warna bekaar) par channels ke across global ordering impossible hai. Per user per channel sequence karo, cross-channel races accept karo.
Production mein kya tootta hai
- Retry storm: provider outage se har message retry karta hai, queues phool jaati hain, aur provider ke recover hote hi tumhara backlog us pe DDoS ki tarah girta hai aur uske rate limits phir trip. Defenses: exponential backoff with jitter, max-age expiry (3 ghante purana OTP bekaar hai, drop karo), aur retries pe admission control.
- Duplicate delivery: at-least-once everything ka matlab duplicates kabhi na kabhi guaranteed hain. Dedup windows aur client-side suppression (N minutes ke andar same message ID) mandatory hain.
- Blast-induced self-DoS: 50M users ko ek saath promo 50M apps ko bhi jagaata hai jo phir tumhare APIs call karte hain. Sends stagger karo (users ko 15-30 minute mein bucket karo) warna tumhara notification system tumhara apna product gira dega.
- Template regressions: ek toota template variable million users ko "{user_name} your order {order_id}..." bhej deta hai. Template validation aur canary sends isliye exist karte hain kyunki ye har company mein ho chuka hai.
Common interview traps
- Sab kuch ke liye ek queue design karna. Priority lanes interviewer ka pehla probe hai.
- API se providers ko synchronously call karna. Third-party latency hamesha queue ke peeche rehti hai.
- Preferences aur quiet hours bilkul bhoolna. Ye padta hai jaise kabhi phone use hi nahi kiya.
- "Provider ko bheja" ko "delivered" maanna. Delivery tracking hi system aur umeed ke beech ka farak hai.
Interview Q&A
Q: Guarantee kaise do ki user spam na ho, chahe aaj 5 alag product teams use notify karna hi kyun na decide kar lein?
A: Decision centralize karo: har notification, har team se, ek orchestration layer se guzarta hai jo per-user budget enforce karta hai (maan lo max 3 marketing + unlimited transactional per day), fatigue scoring (jo users kabhi nahi kholte unhe demote), aur window ke andar content hash se dedup. Individual teams kuch bhi request kar sakti hain; user ki attention platform own karta hai. Isliye notification platforms libraries ki tarah nahi, real authority wale internal products ki tarah bante hain.
Q: OTP ko 99.9% baar 10 second ke andar pahunchna hai. Design walk through karo.
A: OTP lane ko apni top-priority queue milti hai dedicated worker pool ke saath jise koi blast bhookha nahi maar sakta. Circuit breaker ke peeche do SMS providers: primary se slow ack ya failure pe worker ~2 second mein failover. Delivery SLA ingest se provider-ack tak tracking webhooks se measure hota hai, aur breach pe page. Residual failures ke liye voice-call fallback. Aur OTPs khud queue se expire hote hain: 60 second purana message drop, kyunki stale OTP sirf confuse karta hai.