System Design · Lesson 17
When Your App Needs to Ping Users
Learn scaling, estimation, interview frameworks, rate limiters, URL shorteners, consistent hashing, KV stores, and distributed IDs. Diagrams, labs, and mock interview links included.
On this page
Your Swiggy order arrived — but how did your phone know?
The delivery partner marks "delivered" at 8:14 PM. Four seconds later your phone buzzes: "Enjoy your biryani! Rate your order." You did not refresh the app. You did not poll a server every two seconds. Something pushed that message to you.
That is a notification system — take an event ("order delivered"), pick a channel (push, SMS, email), respect user preferences, and deliver through a third-party provider (FCM, Twilio, SES). Every app with "order updates" or "payment received" builds some version of this.
This chapter covers the core design: push vs pull, channels, event pipeline, templates, preferences, idempotency, and API shape. Fan-out to ten million users is the next lesson.

Swiggy delivery push notification arrives
You did not refresh. Something pushed.
Notification system architecture from event to device
Requirements — functional and non-functional
Functional
- Send notification — given user + event type + payload, deliver on appropriate channel(s)
- Multi-channel — push (mobile), SMS, email (at minimum)
- Templates — "Your order #{order_id} is {status}" with variable substitution
- User preferences — opt out of marketing; allow transactional SMS only
- Delivery status — track sent, delivered, failed per notification
- Idempotency — same event must not send duplicate notifications
Non-functional
- Low latency for transactional — "payment failed" should arrive in seconds, not minutes
- Reliability — at-least-once delivery with dedup on the consumer side
- Provider rate limits — FCM and SMS gateways cap requests/sec
- Scale hint — one user, one notification is easy; IPL score alert to 10M users is not
Clarify: are we building Swiggy transactional alerts or a marketing blast platform? I commit to transactional + templates + preferences + push/SMS/email. Skip in-app websocket unless asked.
Clarifying with the interviewer (say this out loud)
1You: "Example flow — order delivered event, user gets push notification?"
2 -> Interviewer: "Yes, like Swiggy or Zomato."
3
4You: "Which channels? Push, SMS, email — all three?"
5 -> Interviewer: "Push primary, SMS fallback if push fails."
6
7You: "Do users control preferences — marketing off, order updates on?"
8 -> Interviewer: "Yes."
9
10You: "What latency for transactional — seconds or minutes?"
11 -> Interviewer: "Under 10 seconds."
12
13You: "I will cover event queue, worker, template engine,
14 idempotency keys, and provider integration. Scale fan-out next."
Push vs pull — why your phone does not poll Swiggy every second
Pull model
App calls GET /notifications every N seconds. Simple, wasteful, battery killer. Works for email clients; bad for "your UPI payment succeeded."
Push model
Server initiates delivery when event happens. Mobile uses FCM (Firebase Cloud Messaging) on Android and APNs on iOS. Server sends to FCM; FCM delivers to device.
1Swiggy backend -> FCM -> your phone (even if app is killed)
Every modern notification system is push-first for real-time, pull as supplement (notification inbox API).
Channels — push, SMS, email
| Channel | Provider examples | Latency | Cost | Best for |
|---|---|---|---|---|
| Push | FCM, APNs | 1–5 sec | Free | Order updates, chat |
| SMS | Twilio, MSG91, AWS SNS | 5–30 sec | ₹0.15–0.25/msg | OTP, fallback |
| AWS SES, SendGrid | 10–60 sec | ~₹0.01/email | Receipts, digests |
Channel selection logic:
1def pick_channels(user, event_type) -> list[str]:
2 prefs = get_preferences(user.id)
3 if event_type == "order_delivered":
4 channels = []
5 if prefs.push_enabled:
6 channels.append("push")
7 if prefs.sms_enabled and "push" not in channels:
8 channels.append("sms") # fallback
9 return channels
10 if event_type == "marketing_offer" and not prefs.marketing_opt_in:
11 return []
12 return ["email"]
Transactional notifications (order, payment) bypass marketing opt-out. Legal and product teams care about this distinction — mention it.
High-level pipeline — event to device
1Event source -> Notification API -> Queue -> Worker -> Provider (FCM/SES/SMS) -> User device
2 | |
3 +-> Idempotency check +-> Delivery status DB
4 +-> Template render
5 +-> Preference filter
Never call FCM synchronously from the order service. Order marking "delivered" should return in 50 ms. Notification is async — fire event, return.
1# In order service — do NOT block on FCM
2def mark_delivered(order_id: str, user_id: str):
3 db.update_order_status(order_id, "delivered")
4 event_bus.publish("order.delivered", {
5 "order_id": order_id,
6 "user_id": user_id,
7 "idempotency_key": f"order-delivered-{order_id}",
8 })
9 return {"status": "delivered"}
Event queue — decouple producers from delivery
Use SQS, RabbitMQ, or Redis Streams for the MVP:
1{
2 "event_type": "order.delivered",
3 "user_id": "usr_abc123",
4 "payload": {
5 "order_id": "ord_xyz789",
6 "restaurant": "Meghana Biryani",
7 "total": 450
8 },
9 "idempotency_key": "order-delivered-ord_xyz789",
10 "created_at": "2026-08-28T20:14:00Z"
11}
Queue absorbs spikes — dinner rush at 8 PM sends 50K events/minute; workers drain at their pace without crashing the order API.
Same decoupling pattern as click analytics in URL Shortener Core and crawl events in Web Crawler at Scale.
Worker — template, preferences, send
1def process_notification_event(event: dict):
2 if already_sent(event["idempotency_key"]):
3 return # duplicate event — skip
4
5 user = get_user(event["user_id"])
6 channels = pick_channels(user, event["event_type"])
7 if not channels:
8 log_skipped(event, reason="preferences")
9 return
10
11 body = render_template(event["event_type"], event["payload"])
12 for channel in channels:
13 provider = get_provider(channel)
14 result = provider.send(user, body, metadata=event["payload"])
15 record_delivery(event["idempotency_key"], channel, result)
One worker process handles hundreds of notifications per minute on a single server. Scale workers horizontally in Lesson 18.
Templates — one definition, many messages
Store templates separately from code:
1{
2 "event_type": "order.delivered",
3 "push": {
4 "title": "Order delivered!",
5 "body": "Enjoy your meal from {{restaurant}}. Tap to rate."
6 },
7 "sms": {
8 "body": "Swiggy: Your order from {{restaurant}} (Rs {{total}}) was delivered."
9 },
10 "email": {
11 "subject": "Your Swiggy order is here",
12 "body_html": "<p>Order {{order_id}} delivered...</p>"
13 }
14}
1def render_template(event_type: str, payload: dict) -> dict:
2 tmpl = template_store.get(event_type)
3 return {
4 channel: render_string(tmpl[channel], payload)
5 for channel in tmpl
6 }
Product teams edit copy without deploys. Version templates (order.delivered.v2) for A/B tests.
User preferences
1CREATE TABLE notification_preferences (
2 user_id TEXT PRIMARY KEY,
3 push_enabled BOOLEAN DEFAULT true,
4 sms_enabled BOOLEAN DEFAULT true,
5 email_enabled BOOLEAN DEFAULT true,
6 marketing_opt_in BOOLEAN DEFAULT false,
7 quiet_hours_start TIME, -- no push between 11 PM and 7 AM
8 quiet_hours_end TIME,
9 updated_at TIMESTAMPTZ
10);
Cache preferences in Redis (prefs:{user_id}) — every notification read would crush Postgres.
Device tokens for push live separately:
1CREATE TABLE device_tokens (
2 user_id TEXT,
3 device_token TEXT,
4 platform TEXT, -- ios | android
5 PRIMARY KEY (user_id, device_token)
6);
Users have multiple devices (phone + tablet). Send push to all active tokens; prune invalid tokens when FCM returns NotRegistered.
Idempotency — never double-charge attention
Network retries duplicate events. Order service retries publish on timeout; worker must not send two "delivered" pushes.
Idempotency key = unique per logical notification:
1order-delivered-{order_id}
2payment-failed-{payment_id}
3otp-{request_id}
1CREATE TABLE sent_notifications (
2 idempotency_key TEXT PRIMARY KEY,
3 user_id TEXT,
4 event_type TEXT,
5 channels_sent TEXT[],
6 sent_at TIMESTAMPTZ DEFAULT now()
7);
1def already_sent(key: str) -> bool:
2 return db.exists("sent_notifications", idempotency_key=key)
3
4def mark_sent(key: str, user_id: str, channels: list):
5 db.insert("sent_notifications", ...) # unique constraint catches races
Insert-before-send, not after. If two workers race, one wins the unique constraint; the other skips.
Provider integration — FCM example
1def send_push(user_id: str, title: str, body: str, data: dict):
2 tokens = get_device_tokens(user_id)
3 for token in tokens:
4 response = fcm.send(
5 message={
6 "token": token,
7 "notification": {"title": title, "body": body},
8 "data": data,
9 }
10 )
11 if response.error == "NotRegistered":
12 delete_device_token(user_id, token)
FCM handles APNs routing for iOS. You talk to one API. Rate limits apply — batch sends where possible.
Protect FCM calls with a rate limiter — Rate Limiter Algorithms and Rate Limiter Architecture cover token bucket and sliding window patterns you apply per provider.
API design
Send notification (internal — service-to-service)
1POST /api/v1/notifications
2Authorization: Bearer <service_token>
3Idempotency-Key: order-delivered-ord_xyz789
4
5{
6 "user_id": "usr_abc123",
7 "event_type": "order.delivered",
8 "payload": {
9 "order_id": "ord_xyz789",
10 "restaurant": "Meghana Biryani",
11 "total": 450
12 }
13}
14
15202 Accepted
16{ "notification_id": "ntf_001", "status": "queued" }
Return 202 immediately — delivery is async.
Get delivery status
1GET /api/v1/notifications/ntf_001
2
3200 OK
4{
5 "notification_id": "ntf_001",
6 "status": "delivered",
7 "channels": [
8 { "channel": "push", "status": "delivered", "delivered_at": "..." }
9 ]
10}
User preferences (client-facing)
1PUT /api/v1/users/me/notification-preferences
2{ "marketing_opt_in": false, "push_enabled": true }
Register device token (mobile app)
1POST /api/v1/users/me/device-tokens
2{ "token": "fcm_token_...", "platform": "android" }
Delivery status lifecycle
1queued -> processing -> sent -> delivered
2 \-> failed -> retry (max 3) -> dead_letter
Store status per channel per notification. "Sent" means provider accepted; "delivered" means provider callback confirmed (FCM delivery receipt where available).
Napkin math — single server MVP
Swiggy-scale is not your MVP. Start with:
110,000 notifications/day
210,000 / 86,400 ~ 0.12/sec average
3Peak dinner rush (10x): ~1.2/sec
4One worker + one SQS queue handles this easily
FCM free tier covers millions of messages. SMS cost dominates if you lean on SMS:
110,000 SMS/day x Rs 0.20 = Rs 2,000/day if every notification is SMS
2Push-first saves real money
What a single-server MVP looks like
- Order service publishes to SQS/RabbitMQ
- One Python worker: dequeue → template → FCM/SES
- Postgres for preferences, device tokens, sent_notifications
- Redis cache for preferences
- FastAPI for internal send API + preference endpoints
- Deploy on Railway or single EC2 (~₹2,500/month)
Ship this for your startup before you design a fan-out engine for ten million IPL alerts.
Security and compliance (mention briefly)
- PII in payloads — do not put full card numbers in notification body
- OTP SMS — separate high-priority queue; shorter retry window
- Marketing — require explicit opt-in (TRAI DND rules in India)
- Service auth — only internal services call POST /notifications
Interview traps on the core design
| Question | Answer |
|---|---|
| "Why not call FCM from order service?" | Blocks order API; no retry; no template layer |
| "User has 3 devices?" | Send to all tokens; prune dead ones |
| "Push failed?" | Fallback to SMS if preferences allow |
| "Duplicate event?" | Idempotency key + unique constraint |
| "Quiet hours?" | Queue until window opens, or skip non-urgent |
Preview: why the next chapter exists
One Swiggy order → one user → one push. Fine.
IPL final: Cricbuzz sends "CSK wins!" to 10 million users in 60 seconds. That is fan-out — queue partitioning, thousands of workers, provider rate limits, dead-letter queues, and dedup at scale.
Continue here: Notification System at Scale.