Notification System
- Design a notification platform that serves OTPs, transaction alerts and marketing blasts without one starving the other
- Apply idempotency, retries with TTL, dedup and DLQs to at-least-once delivery pipelines
- Design SMS/push provider failover driven by delivery receipts
- Model user preferences, mandatory categories, quiet hours and frequency caps
- Keep email out of spam: warmed-up dedicated IPs, separate streams, SPF/DKIM/DMARC and bounce/complaint suppression
TL;DR
- Treat notifications as three different products on one platform: OTP (seconds, must arrive, short TTL), transactional alerts (must arrive, minutes OK), marketing (best effort, cheap, regulated).
- Isolate by priority: separate queues/topics, worker pools and provider quotas. A 10M-user campaign must never delay an OTP.
- Delivery is at-least-once end to end; make sends idempotent with a producer-supplied key and a dedup store. Providers themselves are not exactly-once — design so a rare duplicate is harmless.
- Every message has a TTL: an OTP retried after it expired is noise; a flash-sale push after the sale ended is a complaint.
- Provider failover uses health scores from latency and delivery receipts (DLRs), with circuit breakers and per-carrier routing.
- Preferences decide whether and where; templates decide what; rate limits decide how fast. Security alerts and OTPs cannot be opted out.
Why it matters
For a bank, notifications are part of the security model and of the customer contract: OTP delivery latency directly hits login and transfer success rates, and balance-change alerts are how customers detect fraud. SMS is also a real cost line — Vietnamese banks have moved many alerts and OTPs to in-app push and "Smart OTP" partly for cost and partly because SMS can be intercepted (SIM swap).
For e-commerce, notifications drive revenue (cart reminders, flash-sale countdowns, order status) and are the first thing that melts on 11.11: one campaign can enqueue tens of millions of pushes in minutes. Advertising messages are also regulated — in Vietnam, anti-spam rules (Decree 91/2020/NĐ-CP) cover consent, opt-out and sending-time windows; check the current version with compliance.
1. Clarify requirements
| Question | Assumption |
|---|---|
| Channels? | iOS/Android push (APNs/FCM), SMS (brandname via aggregators), email, in-app inbox |
| Who sends? | Internal services via API/events: auth (OTP), core banking/ledger (alerts), order service, marketing tool |
| Latency? | OTP p95 under 5 s to the provider; transactional under 1 min; marketing within the campaign window |
| Volume? | ≈ 50M notifications/day normal; campaign bursts of 10M pushes in 10 minutes |
| Personalisation? | Templates with parameters, Vietnamese/English |
| Preferences? | Per category and channel; quiet hours; mandatory categories |
| Tracking? | Sent, delivered, opened/clicked where the channel supports it |
| Out of scope | Generating OTP codes (auth service owns them), campaign segmentation UI |
2. Estimate
- Average: 50M/day ÷ 86,400 ≈ 580/s.
- Campaign burst: 10M ÷ 600 s ≈ 16,700/s for push — the real sizing driver.
- OTP: say 3M/day, peak ≈ 300/s at payday and lunch hour; tiny volume, highest priority.
- Provider limits: an SMS aggregator account typically allows a contracted throughput (often hundreds of messages/s per account — confirm in the contract). That cap, not your servers, bounds SMS speed.
- Storage: notification log ≈ 1 KB/message × 50M/day ≈ 50 GB/day. Keep 90 days hot (≈ 4.5 TB), archive longer for audit (banks often need years).
- Cost: at roughly a few hundred VND per SMS, 3M OTP SMS/day is a material monthly bill — a good reason to prefer push with SMS fallback.
3. API and data model
POST /v1/notifications
Idempotency-Key: txn-alert-7f3a91
{
"userId": "u_102938",
"category": "TRANSACTION_ALERT",
"template": "balance_change",
"params": {"amount": "-1,250,000", "account": "****4821", "balance": "18,400,000", "time": "14:02 17/10"},
"priority": "HIGH",
"ttlSeconds": 900,
"channels": ["PUSH", "SMS"],
"strategy": "FALLBACK"
}
202 Accepted
{"notificationId": "ntf_01HF8...", "status": "QUEUED"}
strategy is FALLBACK (try push, SMS if not delivered within N seconds) or ALL (send on every channel). Return 202 — the API only promises durable acceptance.
4. High-level design
- Notification API: authenticates the producer, validates payload, applies the idempotency check, writes the notification record, publishes to the topic for its priority. Producers can also publish domain events (e.g.
TransferCompleted) that a consumer converts into notifications — use the transactional outbox on the producer side so alerts are never lost when a transfer commits. - Per-priority topics and worker pools: the isolation boundary. Marketing workers can be scaled to zero during an incident without touching OTP.
- Router (a library inside workers, not a separate hop): resolve preferences → choose channel(s) → render the template → apply rate limits → pick a provider → send → record the attempt.
- Status log: append-only, partitioned by day; source for the in-app inbox, customer support lookups and audit.
5. Deep dives
5.1 Priority isolation
The classic failure: marketing enqueues 10M messages into the same queue as OTPs, and a customer waits 20 minutes for a login code. Separate at every shared resource:
- Topics/queues per priority, so ordering in one never blocks another.
- Worker pools per priority, with their own autoscaling and concurrency limits.
- Provider quotas: reserve throughput. If the SMS account allows 500 msg/s, cap marketing at 300 and leave 200 for OTP/alerts — or use separate accounts/sender names for OTP and advertising (often required anyway: advertising brandnames are registered separately from customer-care ones).
- Database connection pools and Redis rate-limit keys namespaced by priority.
5.2 Idempotency and dedup
Duplicates come from producer retries, consumer redelivery (at-least-once), and worker crashes after sending but before committing the offset.
- The producer supplies an idempotency key derived from its business event (
txn-alert-<transferId>), not a random UUID per attempt. - The API does
SET dedup:<key> <notificationId> NX EX 86400in Redis (or an insert on a unique index). If it exists, return the originalnotificationId. - Workers record each attempt
(notificationId, channel)before calling the provider and check it on redelivery. The remaining window — crash after the provider accepted but before the record — can still produce a duplicate. That is acceptable for alerts and OTPs (the second SMS carries the same code); it is why the OTP code is generated and stored by the auth service, not by the notification service.
See Idempotency & Exactly-Once.
5.3 Retries, TTL and DLQ
- Classify errors: retryable (timeout, 5xx, throttled) vs permanent (invalid phone number, unregistered device token, template error). Permanent errors go straight to failed; unregistered push tokens are deleted.
- Retry with exponential backoff and jitter, a max attempt count, and always check
expires_atfirst. An OTP with a 3-minute TTL gets maybe 2 quick retries and a provider switch, never a retry at minute 10. - Use delay topics (retry-30s, retry-5m) or a scheduler rather than sleeping inside a consumer, which blocks the partition.
- After the last attempt, publish to a DLQ with the reason; alert on DLQ rate per category. See Resilience Patterns.
5.4 Provider failover
- Health score per provider per carrier (Viettel, Vinaphone, Mobifone…) from: API error rate, API latency, and — most important — delivery receipt ratio and delay. An aggregator can return
200 OKwhile messages silently stall at a carrier; only DLRs reveal it. - Circuit breaker per provider; half-open probes with low-priority traffic.
- Routing policy by category: OTP → fastest healthy provider regardless of cost; marketing → cheapest provider within quota; transactional → primary with failover.
- Failover can cause a duplicate SMS if provider A was merely slow. For OTP that is the right trade: two identical codes beat none.
- Push has no real "second provider" (APNs and FCM are the only paths to the OS), so failover for push means channel fallback: push not delivered/acked by the app in 30–60 s → send SMS.
5.5 Rate limiting and frequency caps
Three different limits, all token buckets in Redis (Rate Limiting):
| Limit | Key | Purpose |
|---|---|---|
| Producer quota | producer + category | A buggy service cannot flood customers |
| Per-user frequency cap | user + category + day | Marketing: e.g. at most 3 promos/day; OTP: at most 5 per 15 min (also an anti-abuse control — "SMS pumping" fraud abuses OTP endpoints) |
| Provider throughput | provider account | Stay within contracted TPS to avoid throttling or blocking |
Messages that hit a marketing cap are dropped, not delayed; transactional ones are never capped by marketing rules.
5.6 Preferences, quiet hours and compliance
- Preference lookup is on the hot path for every message: cache per user in Redis with write-through on change.
- Mandatory categories (OTP, security alerts, legally required notices) ignore opt-outs; marketing requires explicit consent and a working unsubscribe.
- Quiet hours apply to marketing only; messages are deferred to the next allowed window, and dropped if their TTL expires first. Store user timezone; default
Asia/Ho_Chi_Minh. - Content: mask PII in templates (
****4821), avoid full balances on lock-screen push for users who enabled privacy mode, and never log OTP codes in plain text. Under Vietnam's Personal Data Protection Law (Law 91/2025/QH15) and PCI DSS (Compliance) the status log must not become a PII leak.
5.7 Templates
Versioned templates per (template, locale, channel); producers send parameters, never final text. Render with a safe engine (no code execution), validate SMS length (Vietnamese with diacritics needs UCS-2 encoding: ≈ 70 characters per segment versus 160 for GSM-7, so many banks send unaccented SMS to halve cost). Template changes for regulated messages go through review — treat them like code.
5.8 Status tracking
Customer support needs this: "Did the customer receive the OTP at 14:02?" must be answerable in seconds, with provider message IDs to escalate to the aggregator.
5.9 Email deliverability
Your email provider accepting a message says nothing about where it lands. Gmail, Outlook and Yahoo pick inbox, Promotions or spam from the reputation of your sending IPs and domain, so reputation is something you build and protect.
- Dedicated IPs, warmed up. At steady high volume, use dedicated IPs so another tenant of your provider cannot spoil your reputation. At low or bursty volume a shared pool is usually safer, because a dedicated IP needs regular traffic to keep its standing. A new IP has no history: ramp its daily volume over roughly 2–6 weeks (rough; AWS SES guidance), most engaged recipients first. For 11.11, warm extra IPs weeks ahead; an IP that jumps from 50k to 5M emails a day looks like a spammer.
- Separate streams. Send transactional mail (statements, order confirmations, security notices) and marketing from different subdomains and IP pools, e.g.
alerts.bank.exampleandnews.bank.example. Marketing draws most complaints and is what providers file as promotional; on a shared IP and domain, one bad campaign drags statements into Promotions or spam. Give each stream its own quota too (5.1). - Aligned authentication. SPF lists the servers allowed to send for a domain, DKIM signs each message so receivers can verify it with a public key in DNS, and DMARC requires one of them to pass for the same domain as the visible From and tells receivers what to do when neither does. Watch DMARC aggregate reports, then move to
p=reject(DNS). Gmail and Yahoo require bulk senders to authenticate this way, offer one-click unsubscribe on marketing and keep spam complaints under 0.3% (as of 2026, verify). - Feedback into a suppression list. Provider webhooks and ISP feedback loops report three outcomes; handle each on its own queue:
The router checks the suppression list before every email (the Suppressed state in 5.8). For a bank, a hard bounce is also a stale-contact signal: flag it for a contact-data refresh and deliver regulated notices such as statements through the in-app inbox meanwhile.
What a bank never puts in email. No OTP codes, balances or full account numbers in the subject or preview text, which show on lock screens. Email is also a poor OTP fallback: greylisting and retries can push delivery past a 3-minute TTL, so keep OTP on push or Smart OTP with SMS fallback (5.4). Never link to a login page; telling customers "we never email login links" is the cheapest anti-phishing control you have. Statements go out as a "ready in the app" notice, or as an encrypted PDF where an attachment is required.
6. Bank vs e-commerce at a glance
| Aspect | Bank OTP / alerts | E-commerce marketing |
|---|---|---|
| Priority | Highest; separate pool and quota | Lowest; preemptible |
| Latency | Seconds | Minutes to hours |
| TTL | 2–5 min (OTP), hours (alerts) | Campaign end time |
| Duplicates | Tolerable, preferable to loss | Annoying; dedup strictly |
| Channel | Push first, SMS fallback | Push/email/in-app; SMS sparingly (cost, consent) |
| Opt-out | Not allowed for security | Must be honoured |
| Audit | Long retention, PII-safe | Shorter; analytics focus |
| Peak | Payday, Tết, salary runs | 9.9, 11.11, 12.12, flash sales |
7. Trade-offs to state out loud
| Decision | Choice | Why |
|---|---|---|
| One platform vs separate OTP service | One platform, hard isolation | Shared templates/preferences/audit; isolation gives the safety of separation. Some banks still run OTP separately for blast-radius reasons — defensible. |
| Kafka vs RabbitMQ/SQS | Kafka for volume and replay; delay queues via retry topics | RabbitMQ's per-message TTL/priority is convenient at lower scale (Message Queues) |
| Failover duplicates | Accept for OTP | Loss is worse than a duplicate |
| Preference check location | At send time, not at enqueue | Users who opt out mid-campaign are respected |
Interview angle
- Strong answers separate priorities early, mention TTL on every message, and know that DLRs — not HTTP 200 — define delivery.
- Follow-ups: How do you send 10M pushes in 10 minutes without hurting OTP? How do you know aggregator A is degraded? What if the same transfer alert is published twice? How do you handle a user who changes phone numbers mid-flight? How would you cut SMS cost by half?
- Red flags: one queue for everything, retrying forever, the notification service generating OTP codes, no mention of opt-out or quiet hours.
Self-check
1. Why must OTP and marketing be isolated, and at which layers?
They have opposite requirements (seconds vs hours, must-arrive vs best-effort) and share bottlenecks. Isolate topics/queues, worker pools, provider throughput (reserved quota or separate accounts), and rate-limit keys. Otherwise a campaign backlog delays logins and transfers.
2. Walk through how a duplicate transaction alert is prevented — and where duplicates can still happen.
The producer uses a business-derived idempotency key; the API stores it with SET NX and returns the original ID on repeats; workers record attempts before sending and skip completed ones on redelivery. A crash after the provider accepted but before recording the attempt, or a failover after a slow provider, can still duplicate — accepted because loss is worse.
3. Aggregator A returns 200 OK but customers report missing OTPs. How would your design detect and react?
Track DLR ratio and delay per provider per carrier. A drop in delivered-within-30s ratio lowers A's health score and opens its circuit for OTP traffic, routing to B. Alert on the DLR metric, not only on API errors.
4. A flash-sale push campaign is still draining 40 minutes after the sale ended. What design elements prevent this?
Per-message expires_at set to the sale end, checked before every send and retry; campaign-level cancel that marks the batch expired; worker capacity sized for the burst; and frequency caps that drop rather than delay.
5. How would you reduce SMS cost for a bank without hurting security?
Push-first with SMS fallback only when the app has not acknowledged within N seconds; move OTP to in-app Smart OTP / device binding for active app users; unaccented templates to fit one GSM-7 segment; cost-aware routing for non-OTP traffic; and monitoring of SMS pumping fraud on OTP endpoints.
6. Where do you check user preferences — at enqueue or at send — and why?
At send time (with a cached lookup), so opt-outs and quiet hours are honoured for messages already queued. Optionally pre-filter at enqueue for large campaigns to avoid wasted work, but the send-time check is authoritative.
7. A bank's statement emails start landing in spam right after an 11.11 partner campaign. What is the likely cause and the fix?
The campaign most likely went out on the same IPs and domain as the statements, and its volume spike and complaints dragged the shared reputation down. Split marketing and transactional mail onto separate subdomains and IP pools with aligned SPF, DKIM and DMARC, warm up the new pool, suppress complainers and hard bounces, and ramp future campaigns per mailbox provider. Meanwhile, point customers to the statement in the app.
Exercise
Build a minimal notification worker in Go: consume from a Kafka (or Redpanda) topic, dedup with Redis SET NX, call two fake SMS providers (one randomly slow), and implement a health score with a circuit breaker. Inject 30% timeouts on provider A. Done when OTP p95 stays under 5 s, no message is sent after its TTL, and your metrics show attempts, failovers and duplicates per minute.
Further reading
- System Design Interview — An Insider's Guide (Vol. 1), Alex Xu — "Design a Notification System".
- Apple Developer documentation — APNs; Firebase documentation — Cloud Messaging.
- Release It!, Michael Nygard — circuit breakers and bulkheads.
- Google, Email sender guidelines (Gmail Help); Amazon SES Developer Guide, dedicated IP warm-up — current bulk-sender rules and warm-up schedules.
Related
- Message Queues & Event Streaming — topics, delay queues, DLQs.
- Idempotency & Exactly-Once — why at-least-once + dedup is the realistic goal.
- Resilience Patterns — retries, backoff, circuit breakers, bulkheads.
- Transactional Outbox & CDC — never losing a transaction alert.
- Rate Limiting — token buckets for caps and provider quotas.
- Fraud & Risk Systems — OTP abuse and SIM-swap signals.
- Bank Transfer System — the producer of balance alerts.
- Ch 8 · Distributed Email Service — email pipelines, deliverability and bounce/complaint handling.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).