Notification System - HLD

Difficulty: Intermediate · Prerequisites: Message Queues, Fan-Out, and Caching


TL;DR

A multi-channel notification platform that delivers push, SMS, email, and in-app messages. It decouples “something happened” from “tell the user” using an event bus.

flowchart LR
    SERVICES["Internal Services<br/>order placed and payment etc"]
    BUS["Kafka"]
    NS["Notification Service<br/>template and routing"]
    PUSH["Push<br/>FCM APNs"]
    SMS["SMS<br/>Twilio"]
    EMAIL["Email<br/>SES"]
    USER["User"]

    SERVICES -->|"1. publish event"| BUS
    BUS -->|"2. route by channel"| NS
    NS --> PUSH
    NS --> SMS
    NS --> EMAIL
    PUSH -->|"3. deliver"| USER
    SMS --> USER
    EMAIL --> USER

In 3 sentences: Backend services emit events (“order confirmed”) to Kafka. The notification service consumes these, renders a template, picks the channel (push/SMS/email based on user preferences), and dispatches. Delivery tracking, retries, and send-time optimization ensure messages reach users when they’re most likely to engage.


1. Understanding the Problem

A notification system lets product surfaces across a company send messages to users across multiple channels - push (mobile), email, SMS, in-app - without every team re-implementing delivery, preferences, retries, and rate limiting. The system must handle billions of events per day, respect user preferences, dedupe noisy senders, and prove delivery.


2. Naive First Cut

The whiteboard sketch before any real thought:

flowchart LR
    APP["Product Service"]
    NS["Notification Sender"]
    APNS["APNs / FCM / SES / Twilio"]
    DB[("Users DB")]

    APP --> NS
    NS --> DB
    NS --> APNS

Why it breaks under real load:

  • One synchronous hop - if APNs is slow, the product service blocks. A single downstream hiccup freezes every checkout / signup / message-send.
  • No retries - APNs drops a packet, the user never hears back. No receipt, no replay.
  • No user preferences - customer unsubscribed from marketing but still gets marketing. Legal problem (the EU’s General Data Protection Regulation, the US CAN-SPAM Act), trust problem.
  • No rate limiting - batch job fires a million sends in a minute, exceeds APNs quota, APNs throttles us for everyone.
    💡 Note whose limit this is: Apple’s, applied to our whole account. A marketing batch and a one-time password are spending from the same budget, which is why Deep Dive 3 has to separate them.
  • No deduplication - two product teams both decide to welcome the user; they get two welcomes.
  • No quiet hours - user in Sydney gets a 3am push.
  • No observability - something failed for 10% of users today. Which 10%? We don’t know.

The rest of the doc evolves this into a queue-based, multi-channel, preference-aware notification platform.


3. Prior Art We’re Drawing From

  • Uber Consumer Communication Gateway (CCG) - central intelligence layer that manages quality, ranking, timing, and frequency of push notifications at the per-user level. Introduced after Uber hit 15+ hours a week of manual coordination trying to keep internal teams from stepping on each other. (blog)
  • Airbnb notification platform - channel abstraction + per-user preference service, feeding multiple providers. Treats the sender API as a single pipe regardless of channel.
  • LinkedIn Air Traffic Control - deduping + frequency capping layer that rides on top of all outbound member communications to prevent over-notification.
  • Stripe Webhooks - the canonical “reliable delivery via outbox + retry” pattern that applies directly to transactional notifications: persist before send, deliver asynchronously, expose attempt history.
  • Courier, Braze, OneSignal, SendGrid - commercial templates for how this kind of platform is exposed to product teams: a single send(user, template, data) API on top of a multi-channel router.

4. Functional Requirements

Core (top 3)

  1. Send a notification to a user through one or more channels (push, email, SMS, in-app) given a template ID and template variables.
  2. Respect user preferences - channel opt-ins, category opt-ins (marketing vs transactional), quiet hours, locale.
  3. Guaranteed at-least-once delivery with retries for transient failures, and exposed per-attempt status for debugging.
    💡 At-least-once = keep retrying until the provider confirms, and accept that a message may go out twice. The alternative, at-most-once, would mean silently losing one-time passwords, which is never the right trade.

Below the line (out of scope)

  • Rich content creation (images, carousels, deeplink generation).
  • Campaign management UI / marketer console.
  • ML-driven send-time optimization (Uber CCG’s specialty - we’ll mention it but not build it).
  • Reply handling (SMS 2-way conversations).
  • Delivery receipts beyond what the provider returns.

5. Non-Functional Requirements

Core

  • Scale - 1B notifications/day peak, ~50k/sec sustained, bursts to 500k/sec (campaign).
  • Latency - transactional (one-time password, security): P95 (the delay 95% of sends beat) end-to-end < 5s. Marketing: P95 < 5 min.
  • Reliability - at-least-once delivery, no silent loss. Acceptable duplicate rate < 0.1%.
  • Multi-region - failover; user in EU hits EU stack.

Below the line

  • Cost optimization (provider routing for cheapest path).
  • Per-tenant isolation (if multi-tenant SaaS).
  • Compliance reports (opt-in audit trails for the US Telephone Consumer Protection Act and the EU’s GDPR).

6. Scale Estimation (Back-of-Envelope)

  • Users: 500M DAU (daily active users), generating events across all product surfaces
  • Write QPS: 1B notifications/day averages ~11.5K/sec, but the load tracks waking hours, so treat 50K/sec as the sustained peak. A marketing campaign is a different shape entirely: 10M sends in a minute is ~170K/sec, and a large one bursts to 500K/sec. Two numbers, two problems.
    💡 QPS = queries per second. The gap between the 11.5K average and the 500K burst is the whole design problem: you cannot size for the average and you cannot afford to size for the burst, so the burst has to be absorbed by a queue. Learn more →
  • Read QPS: one preference lookup per notification, so reads track writes at ~50K/sec sustained, plus ~10K status queries/sec
  • Storage: a notification row plus its delivery attempts is ~640 bytes, so 1B/day is ~640GB/day – roughly 230TB/year. That rules out keeping it all in Postgres: retain ~30 days hot (~19TB) and ship older rows to object storage for the compliance trail.
  • Bandwidth: ~10 Gbps outbound to providers at peak campaign burst

7. Core Entities

  • Notification - one logical message intended for a user, with a template ID, variables, channels, and priority.
  • User - the recipient. Has channel identifiers (device tokens, email, phone), preferences, locale, time zone.
  • Template - a channel-specific content template with variable interpolation ({{firstName}}).
  • Preference - per-user, per-category, per-channel opt-in/out. Quiet hours.
  • Delivery Attempt - one try to hand off a notification to a channel provider. Status: SENT / DELIVERED / FAILED / THROTTLED.
  • Campaign (optional) - a batch of notifications sharing a template, targeting a segment.
  • Channel Provider - APNs, FCM, SES, Twilio, etc. Adapter per provider.

8. API / System Interface

One primary send API. Callers are internal product services, authenticated via a service-to-service JSON Web Token (JWT).
💡 The Idempotency-Key header on the send call is what makes a caller’s retry safe: we record the key, and a repeat of the same key returns the original receipt instead of sending a second notification. Learn more →

Send a notification

POST /v1/notifications                    -> NotificationReceipt
  Header: Idempotency-Key: <uuid>
  Header: Authorization: Bearer <service-jwt>

Request body:

{
  "userId": "u_1293847",
  "templateId": "order_shipped_v3",
  "variables": {
    "orderId": "A-88273",
    "trackingUrl": "https://tr.ck/X7Y8Z",
    "carrier": "BlueDart"
  },
  "channels": ["PUSH", "EMAIL"],
  "category": "TRANSACTIONAL",
  "priority": "HIGH",
  "dedupKey": "order-A-88273-shipped",
  "deeplink": "myapp://orders/A-88273",
  "overrides": {
    "sendAt": null,
    "expireAt": "2026-05-05T10:00:00Z"
  }
}

Response (202 Accepted):

{
  "notificationId": "n_7a3f2e91",
  "state": "ACCEPTED",
  "createdAt": "2026-05-04T12:01:33.412Z"
}

Get status and attempts (for support / debugging)

GET /v1/notifications/:id                 -> Notification + attempts

Response:

{
  "id": "n_7a3f2e91",
  "userId": "u_1293847",
  "templateId": "order_shipped_v3",
  "state": "DELIVERED",
  "category": "TRANSACTIONAL",
  "attempts": [
    { "channel": "PUSH", "provider": "APNs", "status": "SENT",      "at": "2026-05-04T12:01:33.900Z", "providerResp": "200 APNs accepted" },
    { "channel": "PUSH", "provider": "APNs", "status": "DELIVERED", "at": "2026-05-04T12:01:34.102Z", "receipt": "apns-receipt-abc" },
    { "channel": "EMAIL","provider": "SES",  "status": "SENT",      "at": "2026-05-04T12:01:34.200Z", "providerResp": "250 OK" },
    { "channel": "EMAIL","provider": "SES",  "status": "OPENED",    "at": "2026-05-04T12:04:11.512Z", "userAgent": "Mail.app iOS 17" }
  ]
}

User preferences

GET  /v1/users/:id/preferences            -> Preference
PUT  /v1/users/:id/preferences            -> Preference

Preference shape:

{
  "userId": "u_1293847",
  "channels": { "PUSH": true, "EMAIL": true, "SMS": false, "IN_APP": true },
  "categories": {
    "TRANSACTIONAL": { "enabled": true,  "channels": ["PUSH","EMAIL","SMS"] },
    "SECURITY":      { "enabled": true,  "channels": ["PUSH","EMAIL","SMS"] },
    "MARKETING":     { "enabled": false, "channels": ["EMAIL"] }
  },
  "quietHours": { "start": "22:00", "end": "07:00", "timezone": "Asia/Kolkata" },
  "frequencyCaps": { "MARKETING": 5, "SOCIAL": 20 },
  "locale": "en-IN"
}

Device registration (push)

POST   /v1/users/:id/devices              -> register token
DELETE /v1/users/:id/devices/:token       -> revoke
{
  "deviceToken": "apns-token-base64=",
  "platform": "IOS",
  "appVersion": "12.3.0",
  "timezone": "Asia/Kolkata"
}

Campaigns

POST /v1/campaigns                        -> Campaign
{
  "name": "diwali_offers_2026",
  "templateId": "promo_diwali_v1",
  "segment": { "query": "country=IN AND active_last_7d=true AND age BETWEEN 18 AND 34" },
  "scheduledAt": "2026-10-28T09:00:00+05:30",
  "rateLimit": { "perSec": 20000, "perMin": 600000 },
  "useSendTimeOptimization": true
}

Real-time subscription (in-app)

WSS /v1/users/:id/stream                  -> WebSocket
    Header: Authorization: Bearer <user-jwt>

Server pushes JSON frames as notifications fire:

{ "type": "notification", "id": "n_7a3f2e91", "title": "Your order shipped", "body": "...", "at": "2026-05-04T12:01:33.412Z" }

Security notes:

  • All HTTP APIs require service JWT; product services pass the end-user’s ID as data, not identity.
  • The /stream WebSocket uses the end-user’s JWT - authenticates the subscriber against the userId in the path.
  • Templates are pre-approved and versioned; raw text body isn’t accepted from callers to prevent content injection and compliance bypass.
  • Device tokens stored encrypted at rest; tokens rotate when app reinstalls.
  • Idempotency key is scoped per (service, key) and kept 24h in Redis.

9. High-Level Design

We’ll grow the architecture in three passes - one per core functional requirement.

FR1: Send a notification through multiple channels

Start with the minimum viable pipeline: accept, enqueue, fan out per channel, dispatch to the provider.

New components we need:

  1. Notification API - the single entry point for all product services. Receives “send a notification to user X” requests, validates them, and enqueues for processing.
  2. Message Broker (Kafka) - decouples notification intake from delivery.
    💡 Kafka here acts as a buffer - if push notifications are slow today, the queue absorbs the backlog instead of slowing down the checkout flow that triggered the notification. Learn more →
  3. Router - reads each notification event, decides which channels to use (push? email? SMS?), and fans out one message per channel to channel-specific topics.
  4. Channel Workers (Push, Email, SMS) - each specialized worker renders the template and calls the external provider. Isolated so a Twilio outage doesn’t affect push delivery.
  5. External Providers (APNs, SES, Twilio) - the actual delivery services. We don’t send emails ourselves - we hand them to Amazon’s Simple Email Service (SES) or Mailgun, which handles the Simple Mail Transfer Protocol (SMTP) complexity and the reputation management that decides whether our mail lands in inboxes or spam folders.
    💡 FCM (Firebase Cloud Messaging) and APNs (Apple Push Notification Service) are the only way to send push notifications to Android and iOS devices respectively. Your server can’t push directly to phones - it must go through these gateways.
flowchart TD
    APP["Product Service"]
    API["Notification API"]
    Q["Message broker<br/>Kafka"]
    ROUTE["Router"]
    PUSH["Push Worker"]
    EMAIL["Email Worker"]
    SMS["SMS Worker"]
    APNS["APNs / FCM"]
    SES["SES / Mailgun"]
    TWIL["Twilio"]

    APP -->|"1. POST notification request"| API
    API -->|"2. Enqueue for routing"| Q
    Q -->|"3. Route by channel"| ROUTE
    ROUTE -->|"4. Deliver via push"| PUSH
    ROUTE -->|"5. Deliver via email"| EMAIL
    ROUTE -->|"6. Deliver via SMS"| SMS
    PUSH -->|"7. Send via APNs FCM"| APNS
    EMAIL -->|"8. Render template"| SES
    SMS -->|"9. Render template"| TWIL

Step-by-step flow:

  1. Order Service calls POST /v1/notifications → “Hey, order A-88273 shipped, tell the user via push + email”
  2. Notification API validates the payload, looks up the user’s preferences and locale, and persists the intent to a notifications table so there is a durable record of what was asked for
  3. API publishes an event to Kafka and returns 202 Accepted in ~20ms - the product service is free to move on
  4. Router consumes the event, checks template rules + user preferences, and fans out: one message to push topic, one to email topic
  5. Push Worker picks up its message, renders the template in the user’s locale (“Your order has shipped! 📦”), and POSTs to APNs/FCM
  6. Provider response (accepted/rejected) is recorded as a delivery attempt for debugging (“why didn’t my user get their notification?”)

Why async? The product service call path has a strict latency budget (checkout is running). Hitting APNs synchronously is a timebomb - provider slowness becomes product slowness. Enqueueing gives us 10-50ms end-to-end on the hot path; the actual send happens on the worker’s clock.

Why persist before publish? Safety net. If the broker is down, we still have the row.

What FR1 leaves broken: the pipeline delivers, and the intake step is doing two writes to two systems on the hot path of every notification.

  • The Postgres insert and the Kafka publish are not atomic. 50K/sec of synchronous row insert plus publish, and the gap between them is a real failure mode in both directions: commit then crash and the notification exists but is never sent; publish then fail the commit and we send something with no audit record. Nothing here detects either case. Deep Dive 1.
  • The insert is also the write that will hurt first. Notification intake is append-only at 50K/sec against a table that FR3 will add a second high-volume table beside, and Postgres is carrying both the hot write path and the audit history.
  • Channel workers render templates with no statement about where templates come from. If the answer is “strings in the worker”, every copy change is a deploy and marketing cannot ship a word without an engineer. Deep Dive 8.

FR2: Respect user preferences

Preferences live in a dedicated service. Both the Notification API (at intake) and the Router (before fan-out) consult it.

New components we need (in addition to the ones above):

  1. Preference Service - owns all user notification settings: which channels are on/off, which categories they’ve opted out of, quiet hours, locale, and frequency caps.
    💡 This is the “do not disturb” brain - it prevents us from waking someone at 3am with a marketing push.
  2. Preference Cache (Redis) - since every single notification triggers a preference lookup (50K/sec!), we cache preferences in Redis for microsecond reads instead of hammering Postgres.
  3. Preference DB (Postgres) - the durable source of truth for preferences. Updated when users change settings.
flowchart LR
    API["Notification API"]
    ROUTE["Router"]
    PREFS["Preference Service"]
    PREFDB[("Postgres<br/>user_preferences")]
    PREFCACHE[("Redis<br/>pref cache")]

    API -->|"1. Load user preferences"| PREFS
    ROUTE -->|"2. Check user preferences"| PREFS
    PREFS -->|"3. Lookup cached prefs"| PREFCACHE
    PREFCACHE -. miss .-> PREFDB

What preferences capture:

  • Channel opt-ins - SMS: off. Email: on. Push: on.
  • Category opt-ins - Marketing: off. Transactional: always on (legally required in many jurisdictions). Security: always on.
  • Quiet hours - per-user time window in the user’s local time. Non-urgent notifications must not arrive inside it; urgent ones (security, fraud, OTP) bypass it entirely.
  • Locale + time zone - for template localization and quiet-hour computation.
  • Frequency cap - max N marketing notifications per day.

Step-by-step flow (Router consulting preferences):

  1. Router receives the event: “send MARKETING notification to user U via PUSH and EMAIL”
  2. Router asks Preference Service: “What are U’s notification preferences?”
  3. Preference Service checks Redis cache (hit 99% of the time) → returns preferences
  4. Router filters: user has Marketing=on, Push=on, Email=on - both channels stay. If they’d opted out of Marketing, the notification would be silently dropped here
  5. Router checks quiet hours: the user’s timezone says it’s 2:30am, so this non-urgent notification is dropped. (Security and transactional notifications bypass quiet hours - your OTP still arrives at 3am)
  6. Router checks the frequency cap by counting today’s marketing rows for this user in Postgres: 4 so far, under the limit of 5, proceed
  7. Fans out to the push and email channel topics

Why cache preferences in Redis? Every notification triggers a preference lookup. 50k/sec sustained = 50k/sec reads minimum. Postgres can do it, but Redis drops the latency from millis to microseconds and takes load off the DB for campaigns.

Write path: user updates prefs → API writes Postgres → invalidates Redis entry (write-through not worth the complexity; read-through handles the miss).

What FR2 leaves broken: the preference model is right and two of the rules it promises are enforced by throwing work away.

  • Quiet hours silently delete the notification. Step 5 drops a notification because it is 2:30am for that user. But “do not disturb me at 2:30am” means send it later, not do not send it – the user still wants to know their order shipped. A marketing team watching a campaign land for 60% of its audience will reasonably conclude the system is broken, and they will be right. Deep Dive 5 is where deferral becomes real.
  • The frequency cap is a count query on the send path. Step 6 runs SELECT count(*) FROM notifications WHERE user_id = ? AND category = 'MARKETING' AND created_at > ... for every single marketing send. At campaign scale that is one aggregate query per recipient against the table we are concurrently inserting into. It is also racy: two Routers handling the same user at the same moment both read 4, both proceed, and the user gets 6. Deep Dive 4.
  • Nothing dedupes. Two product teams that both emit a welcome_user event produce two welcomes, because the Router has no notion that it has already sent this thing. Also Deep Dive 4.

FR3: Guaranteed at-least-once delivery with retries

Channel workers own the retry logic: classify the provider’s response, back off on transient failures, give up on permanent ones.

New components we need (in addition to the ones above):

  1. Retry Queue (delayed Kafka topic) - when a provider returns a transient error (timeout, 5xx, rate-limit 429), the failed message goes here with exponential backoff timing.
    💡 Exponential backoff means: wait 2s, then 10s, then 60s, then 5min before each retry. This prevents hammering a struggling provider. Learn more →
  2. Dead Letter Queue (DLQ) - where permanently-failed messages go after exhausting all retries. These get reviewed by a human or an automated reconciler.
  3. Delivery Attempts table (Postgres) - records every single attempt to deliver a notification, including the provider’s response. Essential for debugging “why didn’t user X get their OTP?”
flowchart LR
    PUSH["Push Worker"]
    APNS["APNs"]
    ATTEMPT[("Postgres<br/>delivery_attempts")]
    RETRY["Retry Queue<br/>delayed topic"]
    DLQ["Dead Letter Queue"]

    PUSH -->|"1. Send via APNs FCM"| APNS
    PUSH -->|"2. Record delivery attempt"| ATTEMPT
    PUSH -.timeout or 5xx.-> RETRY
    RETRY -->|"3. Retry delivery"| PUSH
    PUSH -.permanent failure.-> DLQ

How a channel worker handles each notification (with retries):

What a worker does for each message:

  1. Read from channel topic.
  2. Render template with user variables + locale.
  3. POST to provider (APNs / SES / Twilio) with a timeout (2s for push, 5s for email/SMS).
  4. Write a delivery_attempts row: status (SENT / FAILED / THROTTLED), provider response code, timestamp.
  5. Classify the outcome:
    • Success → commit Kafka offset, move on.
    • Transient failure (5xx, timeout, 429 throttle) → publish to a delayed retry topic with exponential backoff (2s → 10s → 60s → 5min → 30min; max 5 retries).
    • Permanent failure (400 bad token, invalid phone) → revoke the token in our user device table, send to DLQ.

Why not just retry forever? Permanent failures (invalid device token, phone number doesn’t exist) will never succeed no matter how many times we retry. Sending to DLQ and revoking the bad token prevents infinite loops and keeps the queue healthy. Transient failures (provider overloaded) usually resolve within minutes, so retries with backoff are the right call.

Why at-least-once, not exactly-once? Distributed systems can’t do exactly-once delivery across a network boundary - only at-least-once plus idempotency on the receiving side. Which means a retry can and will produce a second banner on the device, and nothing here prevents that yet.

Why persist every attempt? So that the provider’s answer is not lost. A 429 from APNs or a BadDeviceToken is the only signal we get, and it arrives once.

DLQ ownership: a sweeper runs every 5 minutes, reviews DLQ messages, and either retries with longer backoff, or surfaces to a human dashboard after N tries.

What FR3 leaves broken: retries make delivery durable. They also make it rude, and they do not make it answerable.

  • Retrying is how we create duplicates. A push that timed out may well have been delivered – the timeout tells us nothing about what APNs did. Retry and the user gets two banners for one event. The fix is cheap and specific (pass our notification id as apns-collapse-id / FCM collapse_key so the device coalesces them) and it is not here.
  • Backoff protects us from the provider, not the provider from us. Exponential retry handles a 429 after it arrives. Nothing shapes our outbound rate, so a campaign still blasts APNs at whatever rate the workers can manage, and APNs throttles the whole tenant – which 429s the transactional OTPs queued behind it. Deep Dive 3.
  • “Did user X get their OTP?” is still a log-grep. We now record every attempt, which is the raw material, but there is no notification-level view that joins intake to attempts to the provider’s eventual verdict. And the provider’s verdict is the part we never hear: SENT means APNs accepted it, not that a phone displayed it. Deep Dive 6 is the difference between recording attempts and proving delivery.

10. Technology Choices

Vendor-agnostic with alternatives. Swap to a specific cloud’s services if you’re targeting one.

Tier / purpose What it stores Access pattern Primary pick Alternatives
Notification primary notifications - intent, template ID, state, dedupKey high write on send, index by (user, createdAt), point-read by id PostgreSQL partitioned by day MySQL, CockroachDB, Aurora
Delivery attempts one row per provider call, with response insert-heavy, query by notification_id for support PostgreSQL monthly-partitioned, or Cassandra at very high rates DynamoDB with TTL
User preferences channel + category opt-ins, quiet hours, frequency state low write, very high read (every send) PostgreSQL + Redis cache DynamoDB + DAX
Device registry push tokens per user per device medium write (registrations), high read PostgreSQL sharded by user_id DynamoDB, Cassandra
Event backbone notification.requested, notification.dispatched, etc. ordered per user_id, replayable, at-least-once Kafka Kinesis, Google Pub/Sub, Pulsar
Delayed queue (quiet hours, retries) messages keyed by wake-up time producer writes with a readyAt; consumer only pulls ready ones Redis sorted sets keyed by timestamp, or Kafka with timer-topic wheel SQS with visibility delay, RabbitMQ delayed exchange
Template store rendered templates per channel per locale read-heavy, versioned S3 / object storage + Postgres metadata Git-backed templates (GitOps)
Rate-limit counters per-user / per-tenant counters very high read+write, TTL’d Redis token bucket / sliding window DynamoDB with atomic counters
Analytics / reporting daily sends, delivery rates, opt-out trends OLAP (online analytical processing — big columnar aggregate scans), dashboards Snowflake / BigQuery / ClickHouse via change data capture (CDC) Redshift, Druid
Secrets provider API keys, APNs certs very low read, high sensitivity Vault / AWS Secrets Manager 1Password Connect, Parameter Store

Why Postgres for notifications + attempts, not Cassandra or DynamoDB?

You get ACID within a send — a group of writes that either all land or none do — so the notification and its initial state are persisted atomically. Support queries hit an indexed point lookup, not a full table scan. Partition by day to keep hot data in tiny tables. For companies sending 10B+/day, Cassandra becomes the right call because append-only writes beat Postgres’ write-ahead log (WAL). Below that, Postgres is simpler and has full SQL.
💡 The write-ahead log is the record of every change, written to disk before the change is applied, that lets a crashed database recover. Every Postgres write pays for it; Cassandra’s design does less of that work per write, which is the whole trade here.

Why Redis for the delayed queue?

Redis sorted sets (ZSET) give O(log N) insert and O(log N) range query by score. “Give me everything with score ≤ now()” → pop them. This is the cleanest delayed queue pattern. Kafka timer-topic wheels work too but are harder to get right; use them only when volumes exceed what a Redis cluster handles.

Why Kafka for the event backbone?

  • Ordering per partition - critical for “this user’s notifications” to stay in order.
  • Replayable - if the Push Worker had a bug yesterday, we reprocess the topic.
  • Durable - tolerates consumer downtime; messages persist until we ACK.

Kinesis and Pub/Sub are equivalent on managed clouds.


11. Data Modeling

Postgres (Notification Primary — intent and state):

CREATE TABLE notifications (
    notification_id UUID NOT NULL,
    user_id UUID NOT NULL,
    channel VARCHAR(10) NOT NULL,    -- push, email, sms, in_app
    template_id VARCHAR(64) NOT NULL,
    category VARCHAR(30),            -- marketing, transactional, alert
    status VARCHAR(15) NOT NULL,     -- PENDING, DISPATCHED, DELIVERED, FAILED, SUPPRESSED
    dedup_key VARCHAR(128),
    payload JSONB NOT NULL,
    created_at TIMESTAMP NOT NULL,
    dispatched_at TIMESTAMP,
    -- Postgres requires every unique/primary key on a partitioned table to
    -- include the partition key, so created_at is part of the PK.
    PRIMARY KEY (notification_id, created_at)
) PARTITION BY RANGE (created_at);
CREATE INDEX idx_notifs_user ON notifications(user_id, created_at DESC);
CREATE INDEX idx_notifs_status ON notifications(status) WHERE status IN ('PENDING', 'DISPATCHED');

Redis (Rate-Limit Counters + Delayed Queue):

-- Rate limiting
Key: "rl:notif:{userId}:{category}:{window}" → Integer (count in current window)
TTL: window_size (e.g., 3600s for "max 5 marketing per hour")

-- Delayed queue (quiet hours, scheduled sends)
Key: "notif:delayed" → Sorted Set (score = send_at_timestamp, member = notification_id)

Postgres (User Preferences + Device Registry):

CREATE TABLE user_preferences (
    user_id UUID NOT NULL,
    channel VARCHAR(10) NOT NULL,
    category VARCHAR(30) NOT NULL,
    enabled BOOLEAN DEFAULT true,
    quiet_hours_start TIME,
    quiet_hours_end TIME,
    PRIMARY KEY (user_id, channel, category)
);

CREATE TABLE device_tokens (
    user_id UUID NOT NULL,
    device_id VARCHAR(128) NOT NULL,
    platform VARCHAR(10) NOT NULL,  -- ios, android, web
    push_token TEXT NOT NULL,
    is_active BOOLEAN DEFAULT true,
    updated_at TIMESTAMP NOT NULL,
    PRIMARY KEY (user_id, device_id)
);

Access Patterns:

Query Data Source How
Send notification (dispatch) Kafka → Workers Consume from notification.requested topic, check prefs + rate limit, call provider
Check user preferences Redis (cached) → Postgres Cache prefs in Redis with 5-min TTL; fallback to DB
Rate limit check Redis INCR rl:notif:{userId}:{category}:{window} — if > limit, suppress
Quiet hours handling Redis ZSET If in quiet hours: ZADD notif:delayed <quiet_end_timestamp> notifId — pick up later
Get notification history Postgres SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 20

How a Notification Is Rate-Limited and Delayed for Quiet Hours:

  1. Marketing notification triggered for user X → API inserts to Postgres with status=PENDING, publishes to Kafka
  2. Worker consumes event → checks Redis: INCR rl:notif:{X}:marketing:1h — returns 6
  3. Rule says max 5/hour → SUPPRESSED. Update Postgres status, stop here.
  4. If count was 3 (under limit): check user preferences. User has quiet hours 10pm-8am and it’s 11pm.
  5. Worker adds to delayed queue: ZADD notif:delayed <8am_timestamp> notifId
  6. A scheduler worker runs every minute: ZRANGEBYSCORE notif:delayed 0 <now> → pops ready notifications and re-publishes to Kafka for delivery
  7. On delivery: call FCM/APNs/SMTP, update status to DELIVERED, publish notification.delivered event

12. Deep Dives

Running the flows above against the checklist surfaces eleven worth doing. Deep Dives 1-6 cover the core delivery mechanics; 7-11 address real-time delivery, template management, send-time optimization, engagement tracking, and broadcast.

Deep Dive 1 - Two writes, two systems, no transaction. Which notification goes missing?

Problem: 50K/sec sustained and 500K/sec on a campaign burst, and the intake step writes to two different systems that cannot be committed together.

In simple terms: Imagine 500K “send this notification” requests arriving every second. If each one requires a database write before responding, the database melts. We need a way to accept requests instantly and process them asynchronously.

Bad: FR1’s intake – insert the notifications row, then publish to Kafka. Two writes, no transaction spanning them.

  • Commit the row and crash before the publish, and the notification exists in our audit trail and will never be sent. Nobody is looking for it. The user’s OTP simply never arrives and our own records say we accepted the request.
  • Publish and then fail the commit, and we deliver something we have no record of – which is the version that ends up in a compliance conversation.
  • Neither failure is rare at 50K/sec. Both are invisible, which is what makes this the first deep dive: the throughput problem is obvious and this one is not.
  • (Doing it the other way round, with the product service writing the row itself and publishing and writing an audit log, is three writes on a caller’s critical path and worse on every axis. Not a contender.)

Good: keep the two writes but make the gap recoverable. Insert with status PENDING_PUBLISH, publish, then mark published. A reconciler sweeps rows stuck in PENDING_PUBLISH and re-publishes them.

  • This genuinely closes the hole, and it is the right answer if you are not allowed to change the storage layer. Two costs: the window is now bounded by the reconciler’s period rather than eliminated, so a crash means minutes of delay on a 5-second OTP budget. And intake is still two synchronous round trips plus a status update, so the campaign burst still lands on Postgres at 500K/sec.

Great - outbox + CDC:

  • Notification API writes one row in Postgres in a transaction that includes the event payload in an outbox table.
  • Debezium / logical replication tails the WAL and emits to Kafka - exactly once from WAL to Kafka.
    💡 Debezium is a tool that reads a database’s own change log and republishes each committed row change as an event. Because it reads what the database already durably recorded, there is no second write to lose — which is exactly the gap the “Bad” option had. Learn more →
  • The product-facing API returns immediately after the DB commit (~5ms).
  • Campaign batch writer uses COPY FROM to bulk-insert millions of rows in seconds.
flowchart LR
    API["Notification API"]
    DB[("Postgres<br/>notifications + outbox")]
    CDC["Debezium"]
    KAFKA["Kafka"]
    ROUTE["Router"]

    API -->|"1. Persist notification"| DB
    DB -->|"2. CDC stream"| CDC
    CDC -->|"3. Stream changes"| KAFKA
    KAFKA -->|"4. Route by channel"| ROUTE

Deep Dive 2 - One shipped order, four devices. Is that one notification or four?

Bad: FR1’s Router, which fans out per channel and says nothing about devices – so the Push Worker looks up tokens inline and sends to each.

  • A user with four devices (phone, tablet, desktop, kiosk) gets four pushes for one shipped order. That is defensible for a transactional alert and absurd for a campaign: 50M recipients becomes 200M provider calls, and the amplification factor is a number we do not control because users add devices.
  • Worse, the four sends have no shared identity. The user reads it on their phone and the tablet rings 30 seconds later anyway, because nothing connects the four deliveries to one logical notification. There is no row that represents “this notification” as distinct from “these four attempts”.

Good: Router fans out once per device into the push topic. Each device is an independent delivery attempt. Works until we need to dedupe across devices for the same notification (e.g., user opens on phone, don’t ring the tablet 30s later).

Great - logical notification + per-device attempts + device-collapse:

  • One notification row, N delivery_attempts rows.
  • apns-collapse-id = notification_id: if the same notification retries, APNs replaces rather than stacking.
  • A “read receipt” from the client marks the notification read and any still-pending retries are cancelled.
  • For campaigns: partitioned bulk insert, each partition processes in parallel by a pool of Router workers.

Deep Dive 3 - A marketing blast gets APNs to throttle us. Why did the OTPs stop too?

Bad: FR3’s retry-on-429, which handles throttling after the fact and never limits what we send.

  • Channel workers scale to drain their topic, so a campaign blasts APNs as fast as the worker pool can manage – up to the 500K/sec burst. APNs throttles the tenant, not the campaign, so every transactional push queued behind it gets 429’d too.
  • The retry logic then makes it worse rather than better: those 429s go to the retry topic and come back, so we respond to being throttled by sending more. A marketing send and an OTP are competing for the same provider quota with no notion that one of them has a 5-second budget and the other has five minutes.

Good: Token bucket per provider, per channel. Workers pull from the channel topic only when a token is available.
💡 A token bucket refills at a fixed rate and each send costs one token, so an empty bucket means the worker waits rather than piling more load onto the provider. Learn more →

Great - weighted bucket + priority lanes:

  • Two topics per channel: push.transactional (high priority), push.marketing (bulk).
  • Transactional workers have higher bucket capacity and refill rate.
  • Marketing workers share a smaller bucket, self-throttle.
  • When provider returns 429, workers exponential-backoff the bucket refill rate for that provider - system-wide TTL’d override in Redis.
  • Noisy-neighbor isolation: per-tenant token buckets on top of the per-provider limit, so one product team can’t starve others.
    💡 This is the hot-partition pattern in a shared-quota form: load is never spread evenly across tenants, so without a per-tenant cap the busiest one sets everyone else’s latency.
flowchart LR
    KAFKA1["push.transactional<br/>(high priority)"]
    KAFKA2["push.marketing<br/>(bulk)"]
    BUCKET1["Bucket: 10k/s"]
    BUCKET2["Bucket: 2k/s"]
    WORKERS1["Txn Workers"]
    WORKERS2["Mkt Workers"]
    APNS["APNs"]

    KAFKA1 -->|"1. Deliver"| BUCKET1
    BUCKET1 -->|"2. Read file"| WORKERS1
    KAFKA2 -->|"3. Deliver"| BUCKET2
    BUCKET2 -->|"4. Read file"| WORKERS2
    WORKERS1 -->|"5. Deliver via APNs"| APNS
    WORKERS2 -->|"6. Deliver via APNs"| APNS

Deep Dive 4 - Two teams emit the same event. How does the user get one welcome?

Bad: FR2’s cap – a count(*) on the send path – and no dedup at all.

  • Two product teams both emit welcome_user for a new signup and the user gets two welcomes, because nothing anywhere asks “have we already sent this?”
  • The frequency cap is worse than absent, because it looks present. SELECT count(*) ... WHERE user_id = ? AND category = 'MARKETING' runs per recipient, against the table we are bulk-inserting into, and it is read-then-write: two Routers handling the same user concurrently both read 4, both proceed, and the cap of 5 delivers 6. At campaign scale the race is not theoretical, it is the common case.

Good: dedupKey on the notifications table with a unique constraint. Second insert fails → second team’s send is dropped. Works for exact dups.

Great - Air Traffic Control layer (from LinkedIn’s playbook):

  • A “policy check” step between Router and channel workers.
  • Input: user ID, category, timestamp, content hash.
  • Policies:
    • Dedup - exact dedupKey match within last 24h → drop.
    • Frequency cap - ≤5 marketing per day per user. Counter in Redis (INCR notif:mkt:{userId}:2026-05-04 + EXPIRE).
    • Category quota - no more than 3 “new review” notifications per hour.
    • Global mute - user churned to quiet mode for N days → all marketing dropped.
  • Tokens live in Redis, sharded by user_id. Per-user consistency holds; cross-user global quotas use a separate counter.

This is the layer Uber calls the CCG. It’s where the ML logic for send-time optimization would eventually slot in.


Deep Dive 5 - It is 2:30am where the user is. Where does the notification wait?

Bad: FR2’s quiet-hours check, which drops the notification.

  • “Do not disturb me at 2:30am” means send it later. FR2 reads it as do not send, so the user never learns their order shipped and the campaign silently loses whatever fraction of its audience was asleep – which, across global timezones, is most of them.
  • The other naive option is to hold the thread: check quiet hours, and if we are inside them, Thread.sleep until 7am. That converts a lost notification into an occupied worker, and with hundreds of thousands of deferred sends the channel workers are all asleep instead of delivering the OTPs that bypass quiet hours entirely.
  • Both failures come from the same mistake: treating “later” as something the send path has to wait for, rather than as state to be stored.

Good: If in quiet hours, compute readyAt = end_of_quiet_hours_in_user_tz and insert into a delayed queue. A scheduler wakes up and re-injects when ready.

Great - Redis ZSET with a dequeue poller:

ZADD delayed:notifications <readyAtEpoch> <notificationId>

A scheduler service polls every second:

ZRANGEBYSCORE delayed:notifications 0 <now> LIMIT 0 1000

For each returned ID, re-publish to the channel topic and ZREM. O(log N) inserts, O(log N + k) poll where k = batch size. Scales to hundreds of millions of scheduled notifications.

Alternatives: Kafka timer-topic tumbling wheel, DynamoDB TTL streams, SQS visibility timeout tricks. Pick Redis for simplicity and latency, others if volumes push past a single Redis cluster.

Edge case: user changes time zone mid-wait. Two reasonable answers:

  • Let the scheduled time fire as originally computed (simplicity wins).
  • Re-enqueue on preference change with the new tz (more accurate, more complex).

Most teams pick option 1 and accept occasional mis-timing.


Deep Dive 6 - The provider said SENT. How do we know a phone ever showed it?

Bad: FR3’s delivery_attempts table, which records what we did and not what happened.

  • It is real progress over grepping logs across 50 hosts, and it answers the wrong question. A row saying SENT with a 200 from APNs means APNs accepted the payload. It does not mean the device was reachable, that the user had notifications enabled, or that anything appeared on a screen.
  • So the support ticket “I never got my OTP” is unanswerable in the one case that matters: our records say success, the user says nothing arrived, and both are telling the truth. The provider knows what happened next and we never asked.

Good: Structured logs in ELK (the Elasticsearch, Logstash and Kibana stack — a common way to ship logs into a searchable index with a dashboard on top). Search by notification_id.
💡 Searchable logs are a real step up from grep and still the wrong shape for this question: a log line records what we tried, and the thing we need is a per-notification record of what the provider later said happened. Learn more →

Great - first-class attempt history + delivery webhooks + dashboards:

  • delivery_attempts table holds per-try status. Indexed by notification_id for O(1) support lookups.
  • Provider delivery callbacks (APNs feedback, SES SNS, Twilio webhook) write to an inbound_receipts table; a reconciler joins attempts ↔ receipts to compute true delivery rate.
  • Real-time dashboard: delivery rate per channel, per provider, per category, per locale. Alert on sudden drops.
  • Backstop for lost webhooks: periodic /status poll for providers that support it (APNs Feedback Service); if we have a SENT attempt with no receipt after 30 min, we poll.


Deep Dive 7 - The bell icon needs to update now, not in 30 seconds. Push or poll?

Bad: polling, which is all FR1 through FR3 give an in-app client – the app hits GET /notifications?since=... every 30 seconds. At 500M DAU that is ~17M requests/sec if everyone has the app open, and the overwhelming majority return an empty list. Users see a 30-second lag; 1M DAUs = 33k req/sec of wasted polling.

Good: Server-sent events (SSE) over HTTP/2. The server keeps a unidirectional stream open; when a notification arrives for this user, the server writes a frame. SSE is one-way, text-only, and works through most proxies without configuration.

Great - WebSocket gateway with a presence layer + a fallback poll:

flowchart LR
    APP["Mobile or Web"]
    LB["L4 Load Balancer"]
    WS["WebSocket Gateway<br/>(sticky sessions)"]
    PRESENCE[("Redis<br/>presence: userId -> nodeId")]
    KAFKA["Kafka<br/>in-app topic"]
    FANOUT["In-App Fan-out"]

    APP -->|"1. Connect WebSocket"| LB
    LB -->|"2. Route"| WS
    WS -->|"3. Register presence"| PRESENCE
    FANOUT -->|"4. Read from Kafka"| KAFKA
    KAFKA -->|"5. Push to WS gateway"| WS
    WS -->|"6. Push to client"| APP

How it works:

  1. Client opens a WebSocket to /v1/users/:id/stream. The L4 load balancer — one that routes on TCP connection rather than inspecting HTTP — uses consistent hashing on userId to pin the connection to a specific WS gateway node (sticky sessions). This means a given user is always on the same node, simplifying routing.
    💡 Sticky sessions mean the balancer keeps sending one user to the same server. That is normally something to avoid, and here it is required, because the open socket is state living on exactly one machine. Learn more →
  2. On connect, the WS gateway writes userId -> nodeId to Redis (TTL 30s, refreshed by heartbeat every 10s).
  3. When the In-App Fan-out worker consumes a notification, it looks up the target user’s nodeId in Redis. If present, it publishes to a Kafka topic keyed by node; each WS gateway node consumes its own keyed partition and delivers to the live socket.
  4. If nodeId is missing (user offline), the worker writes the notification to an “inbox” - a Redis list inbox:{userId} capped at 100 items + a Postgres backup. Next time the app connects, it drains the inbox as the first thing.
  5. Fallback poll: even with WS, the app periodically (every 60s) calls GET /notifications?since=<lastSeenId> as a safety net. This catches any notification lost to a transient WS hiccup. It’s rare, but belt-and-suspenders.

Why WS over SSE: bidirectional frames give us acknowledgments (client says “got it, showed badge”), and modern load balancers + browsers handle WebSocket fine. Also: we can multiplex multiple event types over one WS (notifications, typing indicators, presence).

Scale numbers: a single modern WS gateway node handles 50k-100k open sockets. For 10M concurrent users, 100-200 gateway nodes behind a consistent-hash LB.

Trade-off: sticky sessions complicate rolling deploys. Mitigation: graceful drain - new deploy tells existing sockets to reconnect, they get routed to the new node via the LB.


Deep Dive 8 - Marketing wants to change one word. Does that need a deploy?

Bad: templates as hardcoded strings in worker code – which is what FR1 defaults to, since it says the workers render templates and never says where templates come from.

  • Every copy change is a code change, a review, and a deploy across three separate worker fleets. Marketing cannot fix a typo without an engineer, and translators need one too.
  • The subtler cost is that the three workers drift. Push, email and SMS each hold their own copy of the same message, so a wording change lands in two of them and the third keeps sending last quarter’s text until someone notices.

Good: Templates in a database, fetched by ID at render time. Versioned. Marketing uses a console.

Great - immutable template versions + pre-compiled renderer + per-locale cache:

flowchart LR
    CONSOLE["Marketing Console"]
    TMPL["Template Service"]
    S3[("Object Storage<br/>template artifacts")]
    DB[("Postgres<br/>template metadata")]
    CACHE[("Redis<br/>compiled templates")]
    WORKER["Channel Worker"]

    CONSOLE -->|"1. Create campaign"| TMPL
    TMPL -->|"2. Load template from DB"| DB
    TMPL -->|"3. Store rendered template"| S3
    WORKER -->|"4. Render notification"| TMPL
    TMPL -->|"5. Lookup cached template"| CACHE
    CACHE -. miss .-> S3

Model:

  • A template has an ID, a version, a channel (PUSH / EMAIL / SMS / IN_APP), and a locale (en, hi-IN, ja-JP, etc.).
  • Each version is immutable. You don’t edit v3; you publish v4.
  • The templateId on a send request resolves to the current active version per locale.
  • Old versions remain queryable - needed to render historical notifications in the support UI correctly.

Publishing flow:

  1. Marketer drafts a template in the console.
  2. Console uploads the template file (Mustache/Handlebars/MJML for email) to object storage at templates/order_shipped_v4/en.mustache.
  3. Pre-flight validation: variables referenced in the template must all exist in a registered variableSchema. Catches typos before a real send fails.
  4. Compliance reviewer approves (required for MARKETING category).
  5. Activate atomically: Postgres row updates the active_version pointer for (templateId, locale).

Render flow (from a channel worker):

  1. Look up (templateId, userLocale) via Template Service.
  2. Fetch compiled template from Redis. Miss → pull from S3 → compile (parse the Mustache template into an abstract syntax tree, or AST) → cache.
    💡 An abstract syntax tree is the parsed, in-memory form of the template: “literal text, then insert firstName, then more literal text”. Parsing once and reusing the tree is what turns a render into microseconds rather than a fresh parse per send.
  3. Render with the user’s variables. Run output sanitization (HTML escape for email, length-cap for SMS, JSON-safe for push payload).
  4. Return the rendered content to the worker.

Caching: compiled template objects stay in Redis with a long TTL (24h) because versions are immutable - there’s no staleness risk. On activation, the service bumps a global version number which workers check cheaply to detect new active versions.

Locale fallback: hi-IN not found → try hi → try template’s declared default locale → fail send. All falls through Template Service so workers don’t reinvent fallback logic.

Why pre-compile: a template is parsed once per node per version; subsequent renders are ~10-20 μs instead of parsing the template string each time. At 500k/sec we can’t afford the parser on every send.

Integration with channels:

  • Push: renders to title + body + data payload. Max 4KB (APNs) / 4KB (FCM).
  • Email: renders MJML → responsive HTML. Separate plain-text fallback.
  • SMS: renders to plain text, segmented if > 160 GSM characters (the restricted alphabet SMS uses; one emoji or accented letter switches the whole message to a 70-character encoding, and each extra segment is billed separately).
  • In-app: renders to a structured JSON the client knows how to display.

Deep Dive 9 - Everyone gets the campaign at 9am. Why is that the worst time to send it?

Bad: send on submit, which is what the pipeline does – the only timing logic anywhere is Deep Dive 5’s quiet hours, and that is a veto rather than a choice.

  • A campaign scheduled for 9am sends to everyone at 9am. Half ignore it, because 9am is when they are commuting, or in standup, or it is 9am in the timezone of whoever scheduled it and 4am for them.
  • Quiet hours actively make this worse at the margin: everyone deferred overnight is released the instant their window opens, so the 7am boundary becomes its own synchronized blast.
  • The cost is not just open rate. Notifications a user reliably ignores train them to swipe the whole channel away, and an opt-out is permanent in a way that a bad send is not.

Good: Default quiet hours + frequency cap. Better, but still one-size-fits-all. Your “marketing hits at 9am local” misses the user who opens the app at 7pm every day.

Great - per-user send-time prediction + constrained ranking:

flowchart TD
    EVENTS["Engagement events<br/>Kafka"]
    FEATURE["Feature Store"]
    MODEL["Send-Time Model<br/>offline"]
    SERVING["Model Serving"]
    ATC["Policy ATC"]
    RANKER["Ranker"]
    DELAYQ[("Redis ZSET<br/>delayed queue")]

    EVENTS -->|"1. user events"| FEATURE
    FEATURE -->|"2. training features"| MODEL
    MODEL -->|"3. publish model"| SERVING
    ATC -->|"4. ask best hour"| SERVING
    SERVING -->|"5. predicted hour"| RANKER
    RANKER -->|"6. hold until then"| DELAYQ

New components:

  • Model Serving: A small always-on service that holds the trained model in memory and answers “what is the best hour to reach user U with a MARKETING message?” in under a millisecond. It is separate from the offline training job because training runs weekly on a cluster and serving has to answer on the send path.
  • Policy ATC: The Air Traffic Control layer from Deep Dive 4, doing dedup and frequency caps. It appears here because it is the component that asks the model for a time — the policy decision (“may we send this at all”) and the timing decision (“when”) belong together, since both can end in “not now”.

Three layers:

  1. Feature store - per-user features: open-rate-by-hour histogram, click-rate-by-hour, last-active-hour, timezone, days since last notification. Updated in near real time from the engagement Kafka topic.
    💡 A feature store is just a serving layer for the pre-computed inputs a model needs, kept fresh enough to read at request time. It exists so the send path never has to compute “what hours does this user usually open things” on the fly.

  2. Send-time model - offline-trained (weekly) gradient-boosted model that predicts P(open user, hour-of-day, category). Lightweight: ~KBs per user, serves in <1ms. For each incoming notification with useSendTimeOptimization=true, inference returns the best hour in the next 24h.
  3. Ranker - multiple notifications compete for attention. Per-user ranker runs a linear program (Uber’s actual approach - linear programming) that picks at most N notifications per day subject to:
    • category priority (transactional > security > social > marketing),
    • frequency caps,
    • minimum spacing between notifications (15 min),
    • predicted open probability.

    The output is a scheduled list: (notificationId, sendAt) pairs. Each is enqueued in the delayed Redis ZSET from Deep Dive 5.

Why linear programming rather than greedy: the “max 5 marketing per day + min 15 min spacing + top-N by predicted open” problem has conflicting constraints. Greedy picks the highest-scoring notification first and loses optimal coverage. LP gets the globally best schedule in milliseconds for per-user problems of this size (~dozens of candidates per user per day).

Only marketing and social categories go through this layer. Transactional and security bypass - they fire immediately.

Cost control: inference serving is the hot spot. At 100M users × 10 marketing candidates per day = 1B inferences/day. A small Redis-cached “best hour per user per category” result valid for 24h absorbs 95% of those.

Trade-off: adds latency to marketing sends. That’s fine - they’re not time-sensitive. For “this product just restocked” you’d still fire with a shorter urgency window.


Deep Dive 10 - Delivered is not read. How do we find out if anyone cared?

Bad: nothing on the client reports back, so the pipeline’s last data point is the provider’s accept.

  • Deep Dive 6 got us as far as delivered. This is the next question and the pipeline has no mechanism for it at all: delivered is not opened, and opened is not acted on. Every number in the campaign report stops at the point the message left our control.
  • Which means the one feedback loop that would improve the system is missing. Deep Dive 9 wants to learn when a user actually engages, and there is no engagement signal to learn from.

Good: Client-side reporting. App SDK pings POST /v1/notifications/:id/opened when user taps. Email has a tracking pixel. But: no reliable way to know for push without client SDK, and clients can lie or double-report.

Great - multi-source engagement ingestion + deduped event store:

flowchart LR
    APP["Mobile SDK"]
    EMAIL["Email Pixel<br/>& tracking links"]
    PROVIDER["Provider Webhooks<br/>APNs Feedback / SES SNS"]
    COLLECT["Engagement Collector"]
    KAFKA["Kafka<br/>engagement topic"]
    DEDUP["Deduper"]
    DWH[("Analytics Store<br/>events - 90d hot")]
    COLD[("Parquet on S3<br/>cold - 2y")]

    APP -->|"1"| COLLECT
    EMAIL -->|"2"| COLLECT
    PROVIDER -->|"3"| COLLECT
    COLLECT -->|"4"| KAFKA
    KAFKA -->|"5"| DEDUP
    DEDUP -->|"6"| DWH
    DWH -->|"7"| COLD

Event types tracked:

  • SENT - worker handed off to provider.
  • DELIVERED - provider confirmed or SDK ack’d receipt.
  • OPENED - user tapped push / opened email.
  • CLICKED - user tapped a tracked link.
  • DISMISSED - user swiped away without opening.
  • UNSUBSCRIBED - user hit unsubscribe link.
  • BOUNCED - email bounce (hard / soft).
  • COMPLAINED - spam report.

Pipeline:

  1. Sources normalize to a common envelope: {notificationId, userId, event, at, source}.
  2. Collector publishes to the engagement Kafka topic, partitioned by notificationId.
  3. Deduper drops duplicates per (notificationId, event) within a 7-day window using a Bloom filter in Redis. Fixes double-reports from SDK + provider webhook for the same open.
  4. Events land in ClickHouse for real-time dashboards (campaign open rate, per-locale performance). Daily roll-up to S3 Parquet for long-term analysis and ML training.
  5. Events also feed back into the feature store (Deep Dive 9) within minutes.

Why ClickHouse: column-store gives fast aggregation for SELECT category, hour, COUNT(*) FROM events WHERE date=today GROUP BY ... dashboards. Postgres would be too slow at the event volume (10B events/day).

Why a Bloom filter for dedup: exact dedup would require storing 10B IDs per week. Bloom filter accepts ~0.1% false positives (we occasionally drop a real second open) but uses ~100x less memory.

Engagement data flows back into:

  • The send-time optimization model (better predictions).
  • The ATC layer (noisy unsubscribe → suppress future marketing).
  • Product dashboards (which templates work, which don’t).

Deep Dive 11 - 500M recipients, one campaign. What does the Router do with that list?

Bad: FR1’s Router, handed 500M recipients – it iterates the list one at a time, doing per-user preference lookups and per-user inserts.

  • At the 50K/sec sustained intake rate, 500M recipients is about 2.8 hours just to enqueue, before a single push is sent. The campaign’s “send at 9am” means the last recipient hears from us around noon.
  • And it is a single consumer walking a list, so it cannot be sped up by adding Routers: whoever holds the campaign owns the whole iteration. A crash at recipient 300M has no checkpoint to resume from.

Good: Parallelize the iteration. Shard the user list into batches of 10k, each processed by a worker pool. Still bounded by provider rate limits.

Great - pre-computed segment materialized view + push-time content personalization:

  1. For any large segment (country = IN, engaged_users, power_users_top_10pct), Segment Service materializes the user list nightly into an S3 object or a dedicated table.
  2. Broadcast Worker reads the segment in parallel partitions (e.g., 1000 partitions for 500M users) - each partition processed by a separate consumer group.
  3. Content is static across the segment (same template ID, same variables) but rendered per-user-locale at worker time.
  4. Provider rate limit is the ceiling: even fully parallelized, APNs caps total throughput at ~1M/sec. 500M users → ~8 minutes wall-clock minimum.

For truly instant large-audience cases (emergency civic alerts, security advisories), broadcast via channels that support topic-based fan-out natively:

  • APNs Topic, FCM Topics - subscribers receive by topic subscription. Kicks fan-out to the provider.
  • SMS carrier broadcast features for regional alerts (governmental use only).

For normal business broadcast, the segmented-queue approach is what you want.


13. Design Self-Audit

Weak spots checked:

  • Text search - yes, if support team needs to search notifications by content. Push content through a search index (Elasticsearch) with a 14-day retention. Not core but worth mentioning.
  • Stale prefs after write - user opts out, gets one more marketing send because the cache hasn’t invalidated. Fix: 1-second TTL on the cache entry plus event-driven invalidation; acceptable window.
  • Single-region failure - primary Postgres region goes down. Active-passive: async replica in DR region; on failover, promote and re-route traffic. In-flight notifications in Kafka → consumer group repositions to the DR cluster that’s mirrored via MirrorMaker.
  • DLQ reconciliation - ops dashboard lists DLQ entries by reason. Auto-retry once after 1h, then require human decision.
  • Cost at scale - egress to providers is free-ish for APNs/FCM, paid per send for SES/Twilio. Cost dashboard per category so Marketing knows their send cost.
  • Hot user / broadcast - celebrity’s account triggers 100k notifications to followers. Covered in Deep Dive 11.
  • In-app real-time delivery - user opens the app and expects to see the unread badge instantly. Covered in Deep Dive 7 via WebSocket gateway + presence + inbox.
  • Template staleness and localization - marketing can’t edit strings without a deploy. Covered in Deep Dive 8.
  • Over-notification and smart scheduling - users ignore poorly-timed marketing. Covered in Deep Dive 9 with Uber CCG-style send-time optimization.
  • Engagement blindness - we send and hope. Covered in Deep Dive 10 with a unified engagement pipeline.

14. Core Flows

Flow 1 - Transactional send (OTP)

sequenceDiagram
    actor User
    participant AuthSvc as Auth Service
    participant NotifAPI as Notification API
    participant DB as Postgres
    participant Kafka
    participant Router
    participant Prefs as Preference Svc
    participant Worker as SMS Worker
    participant Twilio
    participant Attempts as attempts table

    AuthSvc->>NotifAPI: POST /notifications (OTP, category=SECURITY)
    NotifAPI->>DB: INSERT notification + outbox
    DB-->>NotifAPI: id
    NotifAPI-->>AuthSvc: 202 accepted (id)
    DB-->>Kafka: CDC → notification.requested
    Kafka->>Router: consume
    Router->>Prefs: get prefs(userId)
    Prefs-->>Router: prefs (security always-on, ignore quiet hours)
    Router->>Kafka: publish sms.transactional (renderedPayload)
    Kafka->>Worker: consume
    Worker->>Twilio: POST /Messages
    alt success
        Twilio-->>Worker: 201
        Worker->>Attempts: INSERT status=SENT
    else transient 5xx
        Twilio-->>Worker: 503
        Worker->>Attempts: INSERT status=FAILED
        Worker->>Kafka: publish retry with backoff
    end

Walkthrough:

  1. Auth service calls the Notification API with the OTP template and category=SECURITY.
  2. API writes the notification and its outbox entry in one transaction.
  3. It returns 202 in under 20ms - the user sees “code sent” immediately.
  4. CDC picks up the commit and publishes to Kafka.
  5. Router consults Preference Service. Security overrides quiet hours and marketing opt-out.
  6. Router fans out to sms.transactional (high-priority topic).
  7. SMS worker renders and hits Twilio with a 5s timeout.
  8. On success, we record the attempt; on 5xx, we retry with exponential backoff; on 4xx we mark permanent failure and alert.

Failure case: Twilio webhooks tell us 15s later the SMS was actually undelivered (number disconnected). The reconciler joins the webhook to our delivery_attempts, flips the status to UNDELIVERED, and notifies Auth Service via its own outbound webhook so it can offer the user an alternate channel.

Flow 2 - Marketing campaign send (10M users)

sequenceDiagram
    participant Marketer
    participant CampaignAPI
    participant SegBuilder as Segment Builder
    participant DB as Postgres
    participant Kafka
    participant Router
    participant ATC as Policy (ATC)
    participant Prefs
    participant DelayQ as Redis ZSET
    participant Worker as Push Worker
    participant APNs

    Marketer->>CampaignAPI: POST /campaigns (segment, templateId)
    CampaignAPI->>SegBuilder: resolve segment → user IDs
    SegBuilder-->>CampaignAPI: 10M user IDs (stream)
    CampaignAPI->>DB: bulk COPY notifications + outbox
    DB-->>Kafka: CDC (batched)
    loop per user
        Kafka->>Router: consume
        Router->>Prefs: get prefs
        Prefs-->>Router: marketing=on, quiet=22-07 in Sydney
        alt in quiet hours
            Router->>DelayQ: ZADD readyAt=7am-Sydney
        else not in quiet hours
            Router->>ATC: check dedup + freq cap
            ATC-->>Router: allowed
            Router->>Kafka: push.marketing
            Kafka->>Worker: consume
            Worker->>APNs: POST /push (rate-limited bucket)
            APNs-->>Worker: 200
        end
    end
    Note over DelayQ,Router: scheduler polls every 1s<br/>ZRANGEBYSCORE 0 now

Walkthrough:

  1. Marketer calls CampaignAPI with a segment definition (e.g., “Indian users, 18-34, active in last 7 days”).
  2. Segment Builder streams the user IDs out of the user data warehouse.
  3. CampaignAPI bulk-writes notifications using COPY - seconds, not minutes.
  4. CDC streams events to Kafka in order.
  5. Router consults prefs + ATC for each. Users in quiet hours get deferred via Redis ZSET.
  6. Rate-limited workers drain the topic, respecting APNs throughput caps.
  7. Failures → retry topic with backoff.

Non-obvious failure: campaign writes succeed, CDC is behind by 10 minutes. We don’t block. Marketer sees “campaign queued” because the row is committed; the delay is at most CDC lag, which alerting monitors. Acceptable for marketing.

Flow 3 - User updates preferences

sequenceDiagram
    actor User
    participant App as Mobile App
    participant PrefAPI as Preference API
    participant DB as Postgres
    participant Cache as Redis
    participant Kafka

    User->>App: toggle marketing off
    App->>PrefAPI: PUT /users/:id/preferences
    PrefAPI->>DB: UPDATE preferences
    PrefAPI->>Cache: DEL user:prefs:{id}
    PrefAPI->>Kafka: publish preference.changed
    PrefAPI-->>App: 200
    Note over Kafka: downstream ATC listens<br/>to reset per-user counters
  1. App calls PUT.
  2. Preference API updates Postgres.
  3. Invalidates Redis cache (next read rebuilds).
  4. Publishes a preference.changed event - downstream consumers (ATC, counters) can react.
  5. Returns 200.

Within milliseconds of the update, the next notification fan-out sees the new preference on cache miss → DB hit → re-cache.

State machine - a notification’s lifecycle

stateDiagram-v2
    [*] --> ACCEPTED
    ACCEPTED --> QUEUED: published to Kafka
    QUEUED --> DEFERRED: in quiet hours
    DEFERRED --> QUEUED: wake up
    QUEUED --> SUPPRESSED: policy drop
    QUEUED --> DISPATCHING: worker picks up
    DISPATCHING --> SENT: provider 200
    DISPATCHING --> RETRYING: transient failure
    RETRYING --> DISPATCHING: backoff elapsed
    RETRYING --> FAILED: retries exhausted
    SENT --> DELIVERED: provider receipt
    SENT --> UNDELIVERED: provider receipt (failure)
    FAILED --> [*]
    SUPPRESSED --> [*]
    DELIVERED --> [*]
    UNDELIVERED --> [*]

15. Final Architecture

flowchart TB
    SVC(["Product Services"])
    API["Notification API"]
    KF[["Kafka"]]
    ROUTE["Router<br>policy and ranking"]
    PREFS["Preference Service"]
    TMPL["Template Service"]
    WORK["Channel Workers<br>push email sms"]
    INAPP["In-App Gateway<br>websocket"]
    PG[("Postgres<br>notifications and prefs")]
    RD[("Redis<br>presence and delay queue")]
    DLQ[["Dead Letter Queue"]]
    ANALYTICS[("Analytics Store<br>engagement")]
    VENDORS[/"APNs SES Twilio"/]
    USER(["End Users"])

    SVC -->|"send notification"| API
    API --> PG
    API -->|"enqueue"| KF
    KF --> ROUTE
    ROUTE -->|"is this allowed"| PREFS
    PREFS --> PG
    ROUTE -->|"quiet hours and presence"| RD
    ROUTE -->|"render body"| TMPL
    ROUTE --> WORK
    ROUTE --> INAPP
    WORK --> VENDORS
    WORK -->|"gave up"| DLQ
    VENDORS --> USER
    INAPP --> USER
    USER -->|"opened or clicked"| ANALYTICS

How it works end-to-end:

  1. Product Service sends notification — calls the Notification API with event type, user IDs, and payload
  2. Outbox pattern captures event — written to Postgres; Debezium CDC streams the change to Kafka
  3. Router consumes and evaluates — checks user preferences (Redis pref cache), applies frequency caps (ATC/Policy)
  4. Channel-specific topics populated — Router publishes to per-channel Kafka topics (push, email, SMS, in-app)
  5. Workers render and deliver — Push/Email/SMS Workers call Template Service for localized content, then send via APNs/FCM, SES, or Twilio
  6. In-App fan-out via WebSocket — In-App worker pushes through the WebSocket Gateway to connected users
  7. Failures retry with backoff — exponential backoff on transient errors; permanent failures go to DLQ
  8. Engagement tracked — opens, clicks, and provider webhooks flow to the Engagement Collector, feeding the analytics store and ML feature store for send-time optimization

Key Technologies

Term What it is
Kafka Distributed event log decoupling notification intake from delivery - absorbs burst traffic so product services never block on slow providers.
APNs (Apple Push) Apple Push Notification Service - the only gateway for delivering push notifications to iOS devices.
FCM (Firebase Cloud Messaging) Google’s push notification gateway for Android (and web) - your server can’t push directly to phones without going through FCM.
SES / Twilio Amazon SES for email delivery, Twilio for SMS - external provider adapters wrapped behind channel workers.
Template Engine Renders per-channel, per-locale message content from pre-approved templates with variable interpolation (e.g., {{firstName}}).
Dead Letter Queue Parking spot for permanently-failed messages after max retries - reviewed by ops or an automated reconciler.
Exponential Backoff Retry strategy that waits progressively longer between attempts (2s → 10s → 60s → 5min) to avoid hammering a struggling provider.
Rate Limiting Token bucket per provider and per tenant preventing any single sender from exhausting push/email/SMS quotas for everyone.

What’s Expected at Each Level

This section helps you calibrate your depth. You don’t need to cover everything - just know what’s expected for your level.

Mid-level

Design a basic system that receives events and sends notifications via push/email. Propose a queue between event generation and delivery. Understand why async processing matters - synchronous dispatch blocks the product service and can’t handle provider slowdowns gracefully.

Senior

Propose Kafka for event ingestion with consumer groups per channel. Discuss template service for message rendering, user preference management (opt-in/out per channel), and rate limiting per user. Explain retry strategies with exponential backoff and DLQ for permanently failed deliveries. Articulate the outbox pattern for guaranteed event capture.

Staff+

Address notification deduplication across channels (Air Traffic Control pattern from LinkedIn), priority queuing (critical alerts skip the queue), and A/B testing delivery times for engagement optimization. Discuss cost analysis across channels (SMS costs $0.01/msg vs push at $0) and provider routing for cost optimization. Cover regulatory compliance (CAN-SPAM, GDPR consent) and the operational cost of maintaining per-user frequency caps at scale.


🎯 Key Takeaways

  • Multi-channel (push + email + SMS) with per-user preference routing
  • Kafka decouples event producers from notification delivery
  • Template engine separates content from channel logic
  • At-least-once delivery with dedup on the client side


Understand the building blocks used in this design: