SteelReed

Search

Search posts, questions…

7. System Design

Designing a notification system: push, SMS, email, per-channel queues, deduplication and frequency caps

A system design case study for sending 16 million notifications a day through APNs, FCM, SMS and email: estimation, the intake API, separate queues per channel and priority, workers, templates and user preferences, idempotency keys, retries with backoff and dead letters, rate limits per provider and per user, device token management, status tracking and bulk campaigns.

19 Nov 20267 min readSenior

–

Almost every system has to send notifications: OTPs, order confirmations, reminders, promotions. The design below is a shared notification service, following the 4-step system design interview process; the deep dive focuses on deduplication, retries and frequency caps.

1. The problem

At 20:00 marketing fires 5 million pushes through one shared 12-partition topic. Meanwhile users logging in wait for OTPs: they queue behind millions of promos, arrive 4 minutes late, already expired.

2. Key idea

Think of a post office: the counter only stamps and bags the mail, and each route's carrier delivers at its own pace. The API returns 202 Accepted once the message is queued.

The average is only ~185 messages/s (16 million a day). What drives the design is the campaign peak (~2,800/s) and the providers' quotas. SMS costs hundreds of times more than push: prevent duplicate SMS at all costs.

Component Job
Notification API validate, deduplicate, preferences, render, write PENDING, enqueue
Queues one per channel × priority
Workers rate limiting, calling providers, retries, recording status

2.1 Where to deduplicate?

  • API: store the Idempotency-Key (order-98765-confirmed) under a UNIQUE constraint; on repeat, return the earlier result.
  • Worker: UPDATE … SET status = 'SENDING' WHERE status = 'PENDING'; 0 rows means another worker has it. SENDING carries a lease of a few minutes so a dead worker's job gets picked up.
  • Remaining gap: sent, then crashed before writing SENT; pass an id to the provider for dedup (apns-collapse-id, FCM collapse keys).

2.2 Retries and rate limits

Situation Do Don't
timeout, 5xx retry with backoff + jitter through a delay queue Thread.sleep in the worker
429 + Retry-After slow down the whole channel retry each message immediately
4xx (bad token, 410) dead letter, delete the token retry
Provider quota one cluster-wide token bucket, ~80% of quota a separate limit per worker
Per-user limits count marketing messages per day, quiet hours apply them to OTPs or security alerts

3. In Java

JAVA
SendResult handle(Notification n) {
    if (repo.claim(n.id()) == 0) return DUPLICATE;               // PENDING -> SENDING, 5-minute lease
    if (n.isMarketing() && userCap.incrementToday(n.userId()) > 2) return CAPPED;
    for (int attempt = 1; ; attempt++) {
        providerLimiter.acquire(n.channel());                     // cluster-wide token bucket
        ProviderResponse r = provider.send(n);
        if (r.ok()) { repo.markSent(n.id(), r.providerMessageId()); return SENT; }
        if (!r.retryable() || attempt == 4) {                     // 4xx or out of attempts
            if (r.status() == 410) devices.delete(n.token());
            return deadLetter(n, r);
        }
        long cap = Math.min(30_000, 500L << attempt);
        scheduleRetry(n, ThreadLocalRandom.current().nextLong(cap)); // full jitter, via a delay queue
        return RETRY_SCHEDULED;
    }
}
// always OK: SENT; fails twice then OK: SENT; always 503: DEAD_LETTER; 410: DEAD_LETTER + token deleted

Writing the log and enqueueing are two systems: use a transactional outbox if messages must not be lost.

Kafka or a queue with built-in delays?
Kafka SQS/RabbitMQ
Strengths high throughput, replayable, many consumer groups per-message ack, visibility timeout, delay queues, DLQ built in
Weaknesses you build tiered retry topics (retry-1m, retry-10m) and a DLQ; a slow message blocks its partition no history replay

A common setup: Kafka carries business events, and the notification service turns them into tasks on a retrying queue. Push through APNs/FCM isn't guaranteed to arrive or arrive on time: an in-app inbox lets users still see transactional messages when a push gets lost.

4. Working with AI

Give the AI: the estimation table, schemas for notification and device, a worker with tests for the four kinds of provider response.

Check in the AI's design:

  • The API never calls providers directly.
  • OTPs have their own queue and workers, not shared with marketing.
  • Nothing is marked "sent" before sending; SENDING has a lease.
  • 4xx isn't retried; 410 deletes the device token.

5. Exercises

Exercise 1: An AI-written worker

The AI writes a worker with "guaranteed dedup": SETNX sent:{key} in Redis, and on success calls the provider; on any error it does Thread.sleep(2^n seconds) and retries up to 5 times. Find three problems.

Solution to Exercise 1
  • Marking before sending: if the worker dies after SETNX, the message is never sent (at-most-once in disguise). Use SENDING with a lease that another worker can take over.
  • Thread.sleep in the worker: holds the thread and blocks later messages on the same partition. Re-enqueue with a delay instead.
  • Retrying every error: retrying 410 Unregistered or a bad phone number 5 times wastes SMS money. Retry only timeouts, 5xx and 429, with jitter so workers don't stampede.

Exercise 2: Splitting the queues

Back to section 1: one notifications topic, 12 partitions, 12 workers. Fix the design so a 5-million-push campaign doesn't delay OTPs.

Solution to Exercise 2
  • Split by channel × priority: otp-sms, otp-push, transactional-email, marketing-push, each with its own worker group. OTP workers are always running.
  • Campaigns enqueue at a controlled rate (2,000/s), below quota; the push rate limiter reserves part of the quota for transactional messages.

Summary

  • The API only enqueues and returns 202.
  • One queue per channel and priority.
  • Dedup at the API (idempotency key) and the worker (SENDING with a lease).
  • Retry 5xx/429 with backoff and jitter; 4xx goes to the dead letter queue.
  • Provider rate limits differ from per-user limits.

Read more: Idempotency in distributed systems.


Self-compiled notes from official documentation and hands-on practice.

Practice interview questions on this topic

All System Design questions →

Loading comments…
Next on the roadmapCalling an LLM from the backend: timeouts, retries, streaming and fallbacks