TExcelTAD
Home › System Design › Design a Notification System

Design a Notification System

Almost every product sends notifications: a push alert for a new message, an SMS with a login code, an email receipt, an in-app badge. A notification service gives all teams one API for this, and takes care of channels, user preferences, priorities, retries, rate limits and deduplication.

1. Requirements

Functional

  • Send notifications via push (APNs for iOS, FCM for Android), SMS, email and in-app.
  • Triggered by other services (an event or an API call) and by scheduled campaigns.
  • Respect user preferences (opt-outs per channel and category, quiet hours) and templates per language.

Non-functional

  • Transactional messages (login codes, security alerts) arrive within seconds; marketing can wait.
  • At-least-once delivery to the provider, but a user must not receive the same notification twice.
  • 10 million notifications per day normally, 100 million when a campaign runs.
  • One slow provider must not delay the others.

2. Estimates

python · try it yourself
daily = {"push": 7_000_000, "email": 2_500_000, "sms": 400_000, "in_app": 100_000}
campaign_multiplier = 10
peak_hour_share = 0.2                    # campaigns are often sent within a few hours

total = sum(daily.values())
print(f"normal day: {total:,} notifications, avg {total / 86_400:,.0f}/s")
campaign = total * campaign_multiplier
print(f"campaign day: {campaign:,} -> peak hour {campaign * peak_hour_share / 3600:,.0f}/s")

sms_cost_usd = 0.0075
print(f"SMS cost per normal day: ${daily['sms'] * sms_cost_usd:,.0f}")
normal day: 10,000,000 notifications, avg 116/s
campaign day: 100,000,000 -> peak hour 5,556/s
SMS cost per normal day: $3,000

SMS is the expensive channel, which is one reason preferences and dedup are business-critical, not just nice to have.

3. High-level design

text
 services --(API / events)--> [ notification service ]
                                 | validate, dedup, look up preferences & templates
                                 v
          [ priority queues per channel ]   high: login codes, alerts     low: marketing
            |            |           |
      [push workers] [email workers] [sms workers]   rate-limited per provider, retries with backoff
            |            |           |
          APNs/FCM     SES/SendGrid   Twilio            --> delivery status events --> analytics
                                                         --> dead-letter queue after N failures

Separate queues per channel and priority isolate failures: if the SMS provider is slow, push notifications keep flowing, and a marketing burst never delays a login code.

4. Preferences, dedup and fan-out to channels

python · try it yourself
import hashlib

preferences = {
    "ana": {"channels": {"push", "email"}, "opt_out": {"marketing"}, "quiet_hours": (22, 7)},
    "ben": {"channels": {"sms", "email"}, "opt_out": set(), "quiet_hours": None},
}
sent_keys = set()                   # in production: a store with a TTL (e.g. Redis SET NX EX)

def in_quiet_hours(hour, quiet):
    if not quiet:
        return False
    start, end = quiet
    return hour >= start or hour < end

def notify(user, category, event_id, priority, hour):
    prefs = preferences[user]
    if category in prefs["opt_out"]:
        return [f"{user}: skipped ({category} opted out)"]
    if priority == "low" and in_quiet_hours(hour, prefs["quiet_hours"]):
        return [f"{user}: delayed until morning (quiet hours)"]
    results = []
    for channel in sorted(prefs["channels"]):
        key = hashlib.sha1(f"{user}:{event_id}:{channel}".encode()).hexdigest()[:10]
        if key in sent_keys:
            results.append(f"{user}: {channel} duplicate suppressed")
            continue
        sent_keys.add(key)
        results.append(f"{user}: enqueue {channel} [{priority}] key={key}")
    return results

calls = [
    ("ana", "security", "login-123", "high", 23),
    ("ana", "security", "login-123", "high", 23),     # upstream retried the same event
    ("ana", "marketing", "spring-sale", "low", 10),
    ("ben", "marketing", "spring-sale", "low", 10),
    ("ben", "social", "new-follower-9", "low", 23),
]
for call in calls:
    for line in notify(*call):
        print(line)
ana: enqueue email [high] key=bc601bdfbe
ana: enqueue push [high] key=8b3ac39e3a
ana: email duplicate suppressed
ana: push duplicate suppressed
ana: skipped (marketing opted out)
ben: enqueue email [low] key=b3b9d1869e
ben: enqueue sms [low] key=f0ee883043
ben: enqueue email [low] key=211faaab41
ben: enqueue sms [low] key=02b8c1d182

The deduplication key is derived from the event id, so an upstream retry of the same event can't double-notify. Security alerts ignore quiet hours; low-priority messages wait.

5. Priority queues and workers

Workers always drain the high-priority queue first. A simulation with one worker that can send 3 messages per tick, during a marketing burst:

python · try it yourself
from collections import deque

high, low = deque(), deque()
arrivals = {0: [("low", f"promo-{i}") for i in range(8)],
            1: [("high", "login-code-ana")],
            2: [("high", "fraud-alert-ben")]}
SENDS_PER_TICK = 3

for tick in range(6):
    for priority, msg in arrivals.get(tick, []):
        (high if priority == "high" else low).append(msg)
    sent = []
    for _ in range(SENDS_PER_TICK):
        queue = high if high else low
        if queue:
            sent.append(queue.popleft())
    print(f"tick {tick}: sent {sent}  (waiting: high {len(high)}, low {len(low)})")
tick 0: sent ['promo-0', 'promo-1', 'promo-2']  (waiting: high 0, low 5)
tick 1: sent ['login-code-ana', 'promo-3', 'promo-4']  (waiting: high 0, low 3)
tick 2: sent ['fraud-alert-ben', 'promo-5', 'promo-6']  (waiting: high 0, low 1)
tick 3: sent ['promo-7']  (waiting: high 0, low 0)
tick 4: sent []  (waiting: high 0, low 0)
tick 5: sent []  (waiting: high 0, low 0)

The login code arriving at tick 1 goes out in that same tick, ahead of the promotions queued earlier. Strict priority can starve low-priority work forever, so real systems use weighted draining (for example 8 high : 1 low) or separate worker pools.

6. Retries and dead letters

Providers fail: timeouts, 429 rate limits, 5xx errors. Workers retry transient failures with exponential backoff and jitter, give up on permanent ones (invalid phone number, unregistered device token, which should also be cleaned from the user's profile), and move messages that exhausted their retries to a dead-letter queue.

python · try it yourself
import random

rng = random.Random(42)

def provider_send(attempt):
    # 60% transient failure rate on a bad day
    return "ok" if rng.random() < 0.4 else "503"

MAX_ATTEMPTS = 3
delivered, dead_letter, total_attempts = 0, [], 0
for msg_id in range(1, 11):
    for attempt in range(1, MAX_ATTEMPTS + 1):
        total_attempts += 1
        if provider_send(attempt) == "ok":
            delivered += 1
            break
        backoff = rng.uniform(0, 0.5 * 2 ** attempt)        # full jitter; a real worker sleeps this long
    else:
        dead_letter.append(msg_id)
print(f"delivered {delivered}/10 with {total_attempts} attempts; dead-lettered: {dead_letter}")
delivered 9/10 with 18 attempts; dead-lettered: [3]

Trade-offs

Decision Choice Why
Queues Per channel and priority Isolation; urgent messages never wait behind campaigns
Delivery At-least-once + dedup keys Retries are needed; duplicates annoy users and cost money
Preferences Checked before enqueueing Don't waste work on messages that won't be sent
Provider limits Token buckets per provider/account Avoid 429s and suspensions
Tracking Delivery/open events to analytics Measure, debug, and stop sending to dead tokens

Tip: Make notifications idempotent end to end: event id → dedup key → provider idempotency key where supported. A user who receives the same 2FA code three times quickly stops trusting the product.

Test yourself

Why use separate queues per channel and priority?

  1. To save memory
  2. So a slow provider or a marketing burst can't delay urgent notifications on other channels
  3. Because providers require it
  4. To sort messages alphabetically

What should the deduplication key be based on?

  1. The time the message was sent
  2. The source event id (plus user and channel)
  3. A random number per attempt
  4. The message text

What should a worker do when the provider says a device token is no longer registered?

  1. Retry forever
  2. Treat it as a permanent failure: stop retrying and remove the token
  3. Send an SMS instead without asking
  4. Put it back at the front of the queue