System Design Part 9 Design problems

Design Problem: A Notification System Where Verification Codes Cannot Wait Behind 10 Million Newsletters

Bill.Lin 18 min read

System Design series Part 9-5 | Previous: Flash Sale Ticketing | Next: Leaderboard | Series map

Scenario and problem

Every service on the talk platform needs to notify members:

Notification Channel Nature
Login verification code SMS, email Transactional; must arrive within seconds
Sign-up confirmed, payment completed, payment deadline reminder Email, in-app Transactional
Talk starts in 15 minutes Push, falling back to email when there is no push Transactional; concentrated at one point in time
Offline chat messages (Chat System) Push Transactional
Weekly newsletter of featured talks Email Marketing; the largest volume

If each service integrates with the email and push providers on its own, the handling of unsubscribes, quiet hours, and invalid tokens ends up scattered across a dozen or more places, and nobody knows how many notifications a member has actually received today. So you centralize it into one notification service.

Scale estimate

Item Estimate
Transactional notifications About 5 million a day, about 60 a second on average
Talk start reminders At 8:00 p.m. sharp several talks start at once: 100,000 within 1 minute → about 1,700 a second
Weekly newsletter 10 million emails; at a sending rate of 2,000 a second, about 1.4 hours to send them all
Notification log About 500 bytes each, about 2.5 GB a day; about 225 GB for 90 days of retention
Centralizing into one notification service1 / 5
Centralizing into one notification serviceServicesNotificationsSMSEmailPushServicesNotificationsSMSEmailPushnotify requestlogin codesign-upstarting soonServicesNotifications~60 per secondNotificationsPush100k in 1 minAbout 1,700 a secondNotificationsEmail10M newslettersTakes 1.4 hoursNotificationsEmailSMSnewsletter going outlogin codeMust arrive in seconds
  1. One central serviceIf each service integrates with the email and push providers on its own, the handling of unsubscribes, quiet hours, and invalid tokens gets scattered across a dozen or more places. So you centralize it into one notification service.
  2. A normal dayAbout 5 million transactional notifications a day, about 60 a second on average.
  3. 8:00 p.m. sharpAt 8:00 p.m. sharp several talks start at once, and 100,000 reminders have to go out within 1 minute, about 1,700 a second.
  4. Weekly newsletterThe weekly newsletter is 10 million emails; at 2,000 a second, it takes 1.4 hours to send them all.
  5. Codes cannot waitDuring the 1.4 hours the newsletter is being sent, login verification codes still have to arrive within seconds; they cannot wait behind 10 million newsletter emails.

During the 1.4 hours the newsletter is being sent, verification codes still have to arrive within seconds. This is the core constraint of the design.

The simplest approach and its limits

All notifications go into one queue and are sent in order:

  • Queuing: the newsletter’s 10 million emails sit in the queue, and a verification code that comes in after them has to wait until they are all sent
  • Duplicates: a consumer crashes after sending but before acknowledging, the message is redelivered, and the member gets two identical emails
  • Sender reputation: complaints about marketing emails drag down the sending domain’s reputation, and even transactional emails start landing in spam
  • Not respecting users: marketing pushes arrive at 3 a.m.; they keep coming after the member unsubscribes; after a member switches phones, sends to the old phone’s push token keep failing

Core mechanism

Architecture

flowchart LR
    S[Services] -->|Notification request<br/>with dedup key| API[Notification service API]
    API --> DB[(Notification log)]
    API -->|outbox| T1[[Transactional queue]]
    API -->|outbox| T2[[Marketing queue]]
    T1 --> D1[Transactional dispatch<br/>more consumers]
    T2 --> D2[Marketing dispatch<br/>fewer consumers, rate-limited]
    D1 & D2 --> P{Preferences, quiet hours<br/>frequency cap, suppression list}
    P --> E[Email provider]
    P --> PU[APNs / FCM]
    P --> SMS[SMS provider]
    P --> IN[(In-app notifications)]
    E -.->|bounce, complaint webhook| W[Feedback handling]
    W --> SUP[(Suppression list)]

Isolating by priority

Transactional and marketing notifications are kept apart starting at the queue:

  • Different topics and consumer groups: the transactional side has more consumers, while the marketing side has fewer and is rate-limited. However large the newsletter, it only makes the marketing queue longer
  • Provider quotas are split too: the email provider’s per-second sending limit is shared, and marketing dispatch may use only part of it, leaving headroom for transactional mail
  • Separate sending domains: transactional mail uses mail.lectures.example.com, marketing uses news.lectures.example.com. Receiving servers build up reputation scores per domain and IP, so complaints about marketing mail do not drag down the verification code emails

This is the bulkhead isolation from the Circuit Breakers and Bulkheads post, applied to queues and external quotas.

Deduplication and the state machine

Notification requests come from the services’ events, and events are delivered at-least-once (Message Queues post). Deduplication happens in two stages:

  1. Deduplicating requests: the caller provides a dedup key, such as registration-confirmed:{registration ID}:{member ID}:EMAIL. The notification log puts a unique key on it, so processing the same event twice produces only one notification
  2. Deduplicating sends: when dispatching, first change the status from PENDING to SENDING with a conditional update, and only the one whose update succeeds sends. A redelivered message sees that the status is no longer PENDING and skips it
text
PENDING ──claim──▶ SENDING ──success──▶ SENT
   │                 │
   │                 ├──temporary failure──▶ retry (backoff), finally dead-letter
   │                 └──invalid recipient──▶ FAILED
   └──preference or suppression list──▶ SUPPRESSED

There is still a window this cannot eliminate: the provider has already accepted the email, but the process crashes before updating the status to SENT. Notifications stuck in SENDING for too long get requeued, and the member may then receive two copies. If you can accept an occasional duplicate, you need no more complex mechanism; when the provider’s API supports idempotency keys, passing the notification ID along closes this window (Idempotency post).

User preferences, quiet hours, and frequency caps

These checks happen at dispatch time, not when the notification is created: a member may unsubscribe while the notification is waiting in the queue, and quiet hours have to be judged by the actual sending time.

  • Preferences: each category and each channel can be turned off separately. Transactional notifications (verification codes, payments) cannot be turned off, but the member can choose the channel
  • Quiet hours: marketing pushes are not sent between 22:00 and 08:00 in the member’s local time; they are deferred until the quiet hours end. Use the time zone the member has set, not the server’s time zone
  • Frequency cap: at most 1 marketing push per person per day. Anything over the cap is marked SUPPRESSED right away, not deferred; otherwise the member gets several at once the next day
  • Suppression list: addresses that hard-bounced (the address does not exist) or filed a complaint are never sent to again

Push tokens and bounces

The provider’s response decides the next step:

Response Meaning Handling
APNs 410 Unregistered; FCM UNREGISTERED The app was removed or the token is no longer valid Delete this device token; do not retry
Timeout, 5xx, rate limit A temporary problem Retry with backoff and jitter (Timeouts, Retries, Backoff, and Jitter post)
Email hard bounce The address does not exist Add it to the suppression list
Email complaint The recipient clicked “This is spam” Add it to the suppression list and stop all marketing mail

Email bounces and complaints come back asynchronously: at send time the provider only says “accepted”, and a bounce arrives through a webhook minutes to days later. Keep sending to addresses that do not exist, or ignore complaints, and your sender reputation drops.

When a member logs out or switches accounts, unbind the device token from the account; otherwise the next user of a shared device receives the previous user’s notifications.

Pacing large sends

  • Talk start reminders: 100,000 of them fall in the same minute. Start early at 7:50 and enqueue them in batches by talk; each one carries a “deliver by” time, and anything past it is not sent (a reminder that a talk starts in 15 minutes, arriving when the talk has already been running for 30 minutes, only causes confusion). For the scheduling part, see Distributed Scheduler
  • Newsletter: spread the sends across recipient domains, so you do not send a large volume to the same mailbox provider in a short time and get throttled; adjust the sending rate by the bounce and complaint rates, slowing down automatically when they rise

What large mailbox providers require of senders

Since 2024, Google and Yahoo have required bulk senders (for Gmail, those sending more than 5,000 messages a day to Gmail users) to:

  • Set up SPF and DKIM and publish a DMARC policy; the From domain must align with the SPF or DKIM domain
  • Offer one-click unsubscribe (RFC 8058) in marketing mail, and honor it within two days
  • Keep the spam complaint rate below 0.3%

These are no longer “best practices”; they are the bar for whether your mail reaches the inbox at all. For the exact conditions, go by the two companies’ latest documentation.

Comparing options

Decision Choice Alternatives rejected, and why
Queues Separate topics, consumers, and quotas for transactional and marketing A single queue with a priority field: consumers still have to read through the messages ahead, so the isolation is incomplete
Deduplication A dedup key on the request plus a conditional status transition before sending Relying only on consumer offsets: redelivery sends duplicates
Preference checks Check at dispatch Check at creation: unsubscribes during queuing do not take effect
Sending domain Separate for transactional and marketing Shared: complaints about marketing mail drag down the verification codes
Build or buy Build dispatch and preference management; hand sending to email, push, and SMS providers Running your own mail servers: building and maintaining IP reputation is extremely costly

In Java

1. The notification log

sql
CREATE TABLE notification (
    id          BIGINT       PRIMARY KEY,
    dedup_key   VARCHAR(200) NOT NULL,
    member_id   BIGINT       NOT NULL,
    channel     VARCHAR(16)  NOT NULL,      -- EMAIL, PUSH, SMS, IN_APP
    priority    VARCHAR(16)  NOT NULL,      -- TRANSACTIONAL, MARKETING
    category    VARCHAR(32)  NOT NULL,      -- unit of preference settings, e.g. LECTURE_REMINDER, NEWSLETTER
    template    VARCHAR(64)  NOT NULL,
    params      JSON         NOT NULL,
    status      VARCHAR(16)  NOT NULL,      -- PENDING, SENDING, SENT, FAILED, SUPPRESSED
    deliver_by  TIMESTAMP(3) NULL,          -- not sent after this time
    updated_at  TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
    created_at  TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    UNIQUE KEY uk_dedup (dedup_key),
    KEY idx_member_created (member_id, created_at),
    KEY idx_status_updated (status, updated_at)
);

idx_status_updated lets the cleanup job find notifications stuck in SENDING for too long.

2. Dispatch: claim, check, send

java
public sealed interface SendResult {
    record Sent() implements SendResult {}
    record InvalidRecipient(String reason) implements SendResult {}
    record Retryable(String reason) implements SendResult {}
}

@Component
public class NotificationDispatcher {

    private final JdbcClient jdbc;
    private final NotificationStore store;
    private final MemberPreferences preferences;
    private final FrequencyCap frequencyCap;
    private final DelayedQueue delayed;
    private final Map<Channel, ChannelSender> senders;

    public NotificationDispatcher(JdbcClient jdbc, NotificationStore store, MemberPreferences preferences,
                                  FrequencyCap frequencyCap, DelayedQueue delayed, List<ChannelSender> senders) {
        this.jdbc = jdbc;
        this.store = store;
        this.preferences = preferences;
        this.frequencyCap = frequencyCap;
        this.delayed = delayed;
        this.senders = senders.stream().collect(Collectors.toUnmodifiableMap(ChannelSender::channel, s -> s));
    }

    @KafkaListener(topics = "notify.transactional", groupId = "notify-transactional", concurrency = "8")
    public void transactional(NotificationQueued event) {
        dispatch(event.notificationId());
    }

    @KafkaListener(topics = "notify.marketing", groupId = "notify-marketing", concurrency = "2")
    public void marketing(NotificationQueued event) {
        dispatch(event.notificationId());
    }

    private void dispatch(long id) {
        Notification n = store.find(id);
        if (n.status() != Status.PENDING) {
            return;                                                  // a redelivery of one already handled
        }
        Instant now = Instant.now();
        if (n.deliverBy() != null && now.isAfter(n.deliverBy())) {
            store.markIfPending(id, Status.SUPPRESSED);              // too late, do not send
            return;
        }
        Preferences p = preferences.of(n.memberId());
        if (!p.allows(n.channel(), n.category()) || p.suppressed(n.channel())) {
            store.markIfPending(id, Status.SUPPRESSED);
            return;
        }
        boolean marketing = n.priority() == Priority.MARKETING;
        if (marketing) {
            Instant allowedAt = p.quietHours().nextAllowed(now);
            if (allowedAt.isAfter(now)) {
                delayed.requeueAt(id, allowedAt);                    // quiet hours: defer, status stays PENDING
                return;
            }
        }
        // Only the consumer that changes PENDING to SENDING may send; redelivered messages are skipped here
        int claimed = jdbc.sql("UPDATE notification SET status = 'SENDING' WHERE id = :id AND status = 'PENDING'")
                .param("id", id).update();
        if (claimed == 0) {
            return;
        }
        if (marketing && !frequencyCap.tryAcquire(n.memberId(), n.channel())) {
            store.mark(id, Status.SUPPRESSED);                       // counted only after the claim, so duplicates use no quota
            return;
        }
        switch (senders.get(n.channel()).send(n)) {
            case SendResult.Sent s -> store.mark(id, Status.SENT);
            case SendResult.InvalidRecipient r -> store.mark(id, Status.FAILED);
            case SendResult.Retryable r -> {
                store.mark(id, Status.PENDING);
                throw new RetryableSendException(id, r.reason());   // Kafka's error handler retries with backoff, then the dead-letter topic
            }
        }
    }
}
  • Preferences and quiet hours are checked before the claim, and a deferred notification stays PENDING, so it can still be claimed when it is requeued later; the frequency cap counts only after the claim
  • A notification whose retries run out and that lands in the dead-letter topic stays PENDING; a person or the cleanup job decides whether to resend it or give up
  • Status updates before the claim use markIfPending (its condition includes status = 'PENDING'), so during a rebalance they do not overwrite a notification that another consumer has already claimed and is sending
  • Spring Kafka’s default error handler retries on the original partition, and during the retries every notification behind it in that partition waits. Transactional notifications can switch to non-blocking retries (retry topics, @RetryableTopic): the failed message moves to a delayed retry topic, and the original partition keeps going
  • ChannelSender is implemented per channel; the push implementation deletes the device token when it receives Unregistered/UNREGISTERED, then returns InvalidRecipient
  • The frequency cap can be a Redis counter that expires at the member’s local midnight (Rate Limiting post)

3. Quiet hours

java
public record QuietHours(ZoneId zone, LocalTime start, LocalTime end) {

    /** Returns now if it can be sent now, otherwise the time quiet hours end. start later than end means the window crosses midnight, e.g. 22:00 to 08:00. */
    public Instant nextAllowed(Instant now) {
        ZonedDateTime local = now.atZone(zone);
        LocalTime t = local.toLocalTime();
        boolean quiet = start.isAfter(end)
                ? !t.isBefore(start) || t.isBefore(end)
                : !t.isBefore(start) && t.isBefore(end);
        if (!quiet) {
            return now;
        }
        ZonedDateTime endToday = local.with(end);
        return (endToday.isAfter(local) ? endToday : endToday.plusDays(1)).toInstant();
    }
}

23:00 at night falls between 22:00 and 08:00, and today’s 08:00 has already passed, so the send is deferred to 08:00 tomorrow; 03:00 in the early morning is deferred to 08:00 today.

4. Email and one-click unsubscribe

java
@Component
public class EmailSender implements ChannelSender {

    private final JavaMailSender mail;
    private final Recipients recipients;
    private final Templates templates;
    private final UnsubscribeTokens unsubscribeTokens;

    public EmailSender(JavaMailSender mail, Recipients recipients, Templates templates, UnsubscribeTokens unsubscribeTokens) {
        this.mail = mail;
        this.recipients = recipients;
        this.templates = templates;
        this.unsubscribeTokens = unsubscribeTokens;
    }

    @Override
    public Channel channel() {
        return Channel.EMAIL;
    }

    @Override
    public SendResult send(Notification n) {
        Recipient to = recipients.of(n.memberId());                              // read the latest address only at send time
        Rendered r = templates.render(n.template(), to.locale(), n.params());    // user-supplied values are always escaped
        boolean marketing = n.priority() == Priority.MARKETING;
        try {
            mail.send(message -> {
                MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
                helper.setFrom(marketing ? "news@news.lectures.example.com" : "no-reply@mail.lectures.example.com");
                helper.setTo(to.email());
                helper.setSubject(r.subject());
                helper.setText(r.plainText(), r.html());
                message.setHeader("X-Notification-Id", Long.toString(n.id()));   // maps bounce reports back to the notification
                if (marketing) {
                    String url = "https://lectures.example.com/u/" + unsubscribeTokens.issue(n.memberId(), n.category());
                    message.setHeader("List-Unsubscribe", "<" + url + ">");
                    message.setHeader("List-Unsubscribe-Post", "List-Unsubscribe=One-Click");
                }
            });
            return new SendResult.Sent();
        } catch (MailException e) {
            return new SendResult.Retryable(e.getMessage());
        }
    }
}

@RestController
public class OneClickUnsubscribeController {

    private final UnsubscribeTokens tokens;
    private final MemberPreferences preferences;

    public OneClickUnsubscribeController(UnsubscribeTokens tokens, MemberPreferences preferences) {
        this.tokens = tokens;
        this.preferences = preferences;
    }

    // The mailbox provider POSTs to this URL directly, with no login session and no CSRF token
    @PostMapping("/u/{token}")
    public ResponseEntity<Void> unsubscribe(@PathVariable String token) {
        UnsubscribeClaim claim = tokens.verify(token);                 // HMAC-signed; can unsubscribe from this one category only
        preferences.optOut(claim.memberId(), claim.category());
        return ResponseEntity.ok().build();
    }
}
  • Errors at send time are always treated as temporary; whether an address is valid is decided by the bounce reports that arrive later, which then add it to the suppression list
  • The one-click unsubscribe endpoint requires no login and has to be excluded from CSRF protection, because the caller is the mailbox provider. It can be this open because the token itself is the authorization, and its only effect is unsubscribing from one category. The token cannot be used for anything else, and it must not contain a member ID that can be enumerated
  • It uses POST rather than GET because mailbox providers and antivirus software open the links in an email ahead of time; with GET, a member would be unsubscribed just by receiving the email
  • Both List-Unsubscribe headers have to be covered by the DKIM signature

The code above is written from the official documentation for Spring Boot 4.1, Spring Framework 7 (JavaMailSender, MimeMessageHelper), Spring for Apache Kafka, and Java 21, and has not been compiled or run. NotificationStore, MemberPreferences, FrequencyCap, DelayedQueue, Recipients, Templates, and UnsubscribeTokens are illustrative components.

Pitfalls and gotchas

  • All notifications share one queue: verification codes wait behind the newsletter
  • Transactional and marketing mail share a sending domain: complaints about marketing mail push the verification codes into the spam folder
  • Checking preferences at creation: unsubscribes made while a notification was queued do not take effect
  • Judging quiet hours by the server’s time zone: members overseas get pushes in the middle of the night
  • Deferring instead of dropping over the frequency cap: the member gets five at once the next morning
  • Ignoring invalid tokens and hard bounces: the failure rate keeps rising, sender reputation drops, and the provider may suspend the account
  • Unsubscribe links that use GET: link previews and security scanners unsubscribe members
  • Sending stale notifications anyway: once a queue backlog clears, members get reminders for talks that ended long ago. Give every notification a deliver-by time

Threat model

STRIDE Threat On the talk platform Defense
Spoofing Phishing mail sent under the platform’s domain; forged bounce webhooks An attacker sends “Payment failed, please re-enter your credit card” from @lectures.example.com; forged bounce notifications add a specific member to the suppression list so they stop receiving verification codes SPF, DKIM, and a DMARC policy raised step by step to p=reject; verify the signature and source of webhooks
Tampering Template injection A member sets their nickname to “Platform notice: for a refund, click https://evil.example”, and it appears in emails sent to speakers; the template engine evaluates an expression supplied by a user User-supplied values are always escaped and never turned into links; templates can be edited only by internal staff and never evaluate user input
Repudiation “I never got the verification code” Support cannot tell whether the platform did not send it, the provider did not deliver it, or it was blocked Keep every notification’s status changes and the provider’s responses, searchable by notification ID
Information disclosure Sensitive content on the lock screen; sending to the wrong person A push shows the full payment amount or the content of a private message; a shared device receives the previous user’s notifications Pushes carry as little content as possible; unbind the device token at logout; verify a new email address before switching to it
Denial of service Notification bombing; SMS pumping An attacker repeatedly triggers “resend verification code” for a victim’s phone number, harassing the victim and running up costs Key rate limits on the recipient too, not only on the requester; a daily SMS budget (8-5)
Elevation of privilege Abuse of the bulk-send feature A compromised internal account uses the marketing back-office tool to send a phishing notification to 10 million members Bulk sends require two-person review and MFA; the recipient count and content of every bulk send are written to the audit log

When to use it, and when not to

  • Centralize into a notification service: when you have several services and several channels, and need unified preferences, unsubscribes, and frequency control
  • Call the providers directly: when there are only one or two kinds of notifications and only one service uses them, start with the provider’s SDK and centralize once the needs grow
  • Hand sending to providers: unless you are an email service company, do not run your own mail servers and build your own IP reputation
  • When to re-evaluate: when marketing sends start affecting the delivery latency of transactional notifications, or when bounce or complaint rates approach the mailbox providers’ thresholds

References

Comments