Design a notification system
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite must send OTPs, order updates and sale offers by email, SMS and push. Sending one message is easy; the hard parts are retries, duplicates and respecting what each user wants.
Your turn: one OTP, five million offers
On sale day ShopLite queues 5 million offers, and at the same moment a customer asks for a login OTP. Think first:
- Should the order service call the SMS provider directly? What if the provider is slow or down?
- How do you make sure the OTP is not stuck behind the offers?
- If a worker crashes and retries, how do you avoid sending the same SMS twice?
Write down your answers, then compare them with the design below.
Requirements: channels, preferences and retries
Push notification is a message shown by the phone's operating system, delivered through Firebase Cloud Messaging on Android or Apple Push Notification service on iPhone, even when the app is closed.
The requirements, then a program that picks the channels for a message from the user's preferences and the message category.
Example 1 · Preferences decide the channels
import java.util.ArrayList;import java.util.EnumSet;import java.util.List;import java.util.Map;import java.util.Set;
enum Channel { EMAIL, SMS, PUSH }
enum Category { SECURITY, ORDER, PROMO }
record Preferences(String userId, Map<Category, Set<Channel>> optedIn) {}
public class PreferenceFilterDemo { static List<Channel> channelsFor(Preferences p, Category category, Set<Channel> requested) { List<Channel> result = new ArrayList<>(); for (Channel c : requested) { boolean mandatory = category == Category.SECURITY; // OTPs and password alerts always go if (mandatory || p.optedIn().getOrDefault(category, Set.of()).contains(c)) { result.add(c); } } return result; }
public static void main(String[] args) { Preferences priya = new Preferences("priya", Map.of( Category.ORDER, EnumSet.of(Channel.PUSH, Channel.EMAIL), Category.PROMO, EnumSet.noneOf(Channel.class))); Set<Channel> all = EnumSet.allOf(Channel.class);
System.out.println("Order shipped -> " + channelsFor(priya, Category.ORDER, all)); System.out.println("Diwali sale -> " + channelsFor(priya, Category.PROMO, all)); System.out.println("Login OTP -> " + channelsFor(priya, Category.SECURITY, EnumSet.of(Channel.SMS))); }}Order shipped -> [EMAIL, PUSH] Diwali sale -> [] Login OTP -> [SMS]
What this code does
channelsForkeeps only the channels the user opted into for that category.- Priya turned off promotions, so the Diwali sale goes nowhere; the OTP is a security message and is sent anyway.
Functional requirements: other services ask for a notification (user, type, data) and the system sends it by email, SMS and/or push. Users choose channels for each category: security, order updates, promotions.
Security messages such as OTPs ignore preferences, because users cannot switch them off. Promotions must respect them, and Indian rules on commercial SMS make that a legal need too. Non-functional requirements: no message lost, none sent twice, OTPs in a few seconds, and a sale-day peak of millions of promotions that must not delay OTPs.
Architecture: API, a queue per channel, workers, providers
Provider is the outside company that actually delivers a message: an email service, an SMS gateway, or Firebase Cloud Messaging and Apple Push Notification service for push.
The architecture as a diagram: the API checks preferences, then one queue per channel feeds workers that call the providers.
[Order service] --(1) POST /api/v1/notifications--> [Notification API][Notification API] --(2) check prefs--> [(Preferences DB)][Notification API] ..(3) one job per channel..> [[email queue]] [[sms queue]] [[push queue]][[email queue]] ..> [Email workers] --(4)--> [Email provider][[sms queue]] ..> [SMS workers] --(4)--> [SMS gateway][[push queue]] ..> [Push workers] --(4)--> [FCM / APNs][Workers] --(5) status--> [(Delivery log)] failed 3 times --> [[dead-letter queue]]The Notification API checks the request and the user's preferences, then puts one job per channel on that channel's queue and answers 202 Accepted. It never calls an email or SMS provider itself, because providers are slow and sometimes down.
Workers are background processes that read one queue and call one provider: the outside company that actually delivers (an email service, an SMS gateway, FCM or APNs). A queue per channel means a slow SMS gateway cannot block emails or pushes. Urgent and bulk traffic should also be separated: an OTP queue with its own workers, so a sale campaign of 5 million promotions never delays a login.
Order of execution
The journey of one OTP
Put the steps in order.
Templates, deduplication and idempotent sends
Deduplication key is built from the event id, the channel and the user, and stored when a job is sent. Any later job with the same key is skipped, so a repeated delivery sends nothing twice.
A template filled with data, and a duplicate check that skips a job whose key was already handled.
Example 2 · Templates and duplicate protection
import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;
record Event(String eventId, String userId, String template, Map<String, String> data) {}
public class TemplateDedupDemo { static final Map<String, String> TEMPLATES = Map.of( "order_shipped", "Hi {name}, order {orderId} is on the way. Track: {link}", "payment_failed", "Hi {name}, payment for order {orderId} failed. Please retry.");
static final Set<String> sentKeys = new HashSet<>(); // a real system keeps these for a few days
static String render(String templateId, Map<String, String> data) { String text = TEMPLATES.get(templateId); for (Map.Entry<String, String> e : data.entrySet()) { text = text.replace("{" + e.getKey() + "}", e.getValue()); } return text; }
static void send(Event e, String channel) { String dedupKey = e.eventId() + ":" + channel + ":" + e.userId(); if (!sentKeys.add(dedupKey)) { System.out.println("skip duplicate " + dedupKey); return; } // The same key goes to the provider as an idempotency key, so its own retries are safe too. System.out.println("send " + channel + " [" + dedupKey + "] " + render(e.template(), e.data())); }
public static void main(String[] args) { Event shipped = new Event("evt-9001", "u42", "order_shipped", Map.of("name", "Priya", "orderId", "SL-1042", "link", "sl.in/t/1042")); List<Event> fromQueue = List.of(shipped, shipped); // the queue delivered the event twice for (Event e : fromQueue) { send(e, "SMS"); } send(shipped, "EMAIL"); }}send SMS [evt-9001:SMS:u42] Hi Priya, order SL-1042 is on the way. Track: sl.in/t/1042 skip duplicate evt-9001:SMS:u42 send EMAIL [evt-9001:EMAIL:u42] Hi Priya, order SL-1042 is on the way. Track: sl.in/t/1042
What this code does
renderreplaces each{placeholder}with its value, so the order service sends onlyorder_shippedplus data.- The queue delivered
evt-9001twice. The keyevt-9001:SMS:u42is already in the set, so the second SMS is skipped. - The email has a different key because the channel is part of it, so the user still gets one email and one SMS.
A template is the message text with placeholders, such as Hi {name}, order {orderId} is on the way. Services send only the template id and data, so wording can change without changing every service.
Queues usually deliver at least once, so a worker can receive the same job twice, for example after a crash. Send the same key to the provider as an idempotency key when it supports one: doing it twice then has the same effect as doing it once, so even the worker's own retries cannot send two SMS.
Per-user rate limits and quiet hours
Quiet hours are a time range in the user's time zone, such as 22:00 to 08:00, when non-urgent messages wait. Urgent messages such as OTPs and payment failures skip them.
A daily promotion limit and a quiet-hours check that works across midnight.
Example 3 · Daily promo limit and quiet hours
import java.time.LocalTime;import java.util.HashMap;import java.util.Map;
public class QuietHoursDemo { static final LocalTime QUIET_START = LocalTime.of(22, 0); static final LocalTime QUIET_END = LocalTime.of(8, 0); static final int PROMO_PER_DAY = 2; static final Map<String, Integer> promosToday = new HashMap<>();
static boolean isQuiet(LocalTime t) { // the quiet period crosses midnight, so it is "after 22:00 OR before 08:00" return !t.isBefore(QUIET_START) || t.isBefore(QUIET_END); }
static String decide(String user, boolean urgent, LocalTime localTime) { if (urgent) { return "send now (urgent)"; } int sent = promosToday.getOrDefault(user, 0); if (sent >= PROMO_PER_DAY) { return "drop (daily limit " + PROMO_PER_DAY + " reached)"; } promosToday.put(user, sent + 1); if (isQuiet(localTime)) { return "delay to " + QUIET_END; } return "send now"; }
public static void main(String[] args) { System.out.println("11:00 promo -> " + decide("u42", false, LocalTime.of(11, 0))); System.out.println("23:30 OTP -> " + decide("u42", true, LocalTime.of(23, 30))); System.out.println("23:30 promo -> " + decide("u42", false, LocalTime.of(23, 30))); System.out.println("23:45 promo -> " + decide("u42", false, LocalTime.of(23, 45))); }}11:00 promo -> send now 23:30 OTP -> send now (urgent) 23:30 promo -> delay to 08:00 23:45 promo -> drop (daily limit 2 reached)
What this code does
isQuietuses OR because 22:00–08:00 crosses midnight: 23:30 is after the start, 03:00 is before the end.- The OTP at 23:30 is urgent and goes now; the promo at 23:30 waits until 08:00.
- The third promo of the day is dropped by the per-user limit of 2.
Too many messages make users uninstall the app. A per-user limit caps non-urgent messages, for example at most 2 promotions per user per day; extra ones are dropped or merged into a summary.
The quiet-hours range crosses midnight, so the check is "time is 22:00 or later, or earlier than 08:00". Mark urgency on the template, not in the calling code, so no service can turn a promotion into an urgent message by mistake.
Single-file simulation: channel queues, retries and a dead-letter list
Dead-letter queue is a holding place for jobs that keep failing after all their retries. A person or a later job inspects them, so a bad job never blocks the queue or disappears silently.
Three queues, a fake provider that fails on purpose, retries with doubling waits, and a dead-letter list for jobs that never succeed.
Example 4 · Channel queues, retries with backoff, dead letters
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Queue;
record Job(String id, String channel, String to, int attempt, long notBefore) { Job retry(long now) { long backoff = 1L << attempt; // 2, 4, 8 ... seconds return new Job(id, channel, to, attempt + 1, now + backoff); }}
/** A fake provider: fails the first N calls for some recipients, always fails for others. */class FakeProvider { private final Map<String, Integer> failuresLeft = new HashMap<>();
FakeProvider failFirst(String to, int times) { failuresLeft.put(to, times); return this; }
boolean deliver(Job job) { int left = failuresLeft.getOrDefault(job.to(), 0); if (left > 0) { failuresLeft.put(job.to(), left - 1); return false; } return true; }}
public class NotificationPipelineDemo { static final int MAX_ATTEMPTS = 3;
public static void main(String[] args) { Map<String, Queue<Job>> queues = new LinkedHashMap<>(); Map<String, FakeProvider> providers = new HashMap<>(); for (String channel : List.of("EMAIL", "SMS", "PUSH")) { queues.put(channel, new ArrayDeque<>()); } providers.put("EMAIL", new FakeProvider().failFirst("priya@mail.in", 1)); providers.put("SMS", new FakeProvider().failFirst("+91-90000-00001", 99)); // a dead number providers.put("PUSH", new FakeProvider());
// The API only validates and enqueues; it answers 202 Accepted right away. queues.get("EMAIL").add(new Job("n1", "EMAIL", "priya@mail.in", 1, 0)); queues.get("SMS").add(new Job("n2", "SMS", "+91-90000-00001", 1, 0)); queues.get("PUSH").add(new Job("n3", "PUSH", "device-7f3a", 1, 0)); queues.get("SMS").add(new Job("n4", "SMS", "+91-90000-00002", 1, 0));
List<Job> deadLetters = new ArrayList<>(); int delivered = 0; for (long now = 0; now <= 10; now++) { for (Map.Entry<String, Queue<Job>> entry : queues.entrySet()) { Queue<Job> queue = entry.getValue(); int ready = queue.size(); for (int i = 0; i < ready; i++) { Job job = queue.poll(); if (job.notBefore() > now) { queue.add(job); continue; } if (providers.get(job.channel()).deliver(job)) { delivered++; System.out.println("t=" + now + " " + job.channel() + " " + job.id() + " delivered (attempt " + job.attempt() + ")"); } else if (job.attempt() < MAX_ATTEMPTS) { Job next = job.retry(now); System.out.println("t=" + now + " " + job.channel() + " " + job.id() + " failed, retry at t=" + next.notBefore()); queue.add(next); } else { System.out.println("t=" + now + " " + job.channel() + " " + job.id() + " failed " + MAX_ATTEMPTS + " times -> dead-letter list"); deadLetters.add(job); } } } } System.out.println("Delivered: " + delivered + ", dead letters: " + deadLetters.size() + " " + deadLetters.stream().map(Job::id).toList()); }}t=0 EMAIL n1 failed, retry at t=2 t=0 SMS n2 failed, retry at t=2 t=0 SMS n4 delivered (attempt 1) t=0 PUSH n3 delivered (attempt 1) t=2 EMAIL n1 delivered (attempt 2) t=2 SMS n2 failed, retry at t=6 t=6 SMS n2 failed 3 times -> dead-letter list Delivered: 3, dead letters: 1 [n2]
What this code does
- Each channel has its own
Queue<Job>; a job that is not due yet (notBefore) is put back, which is how the backoff wait works. retrydoubles the wait with1L << attempt: n1 succeeds on attempt 2 at t=2; n2 fails at t=0, t=2 and t=6.- After 3 attempts n2 goes to the dead-letter list instead of being retried forever; the SMS n4 to a good number was not held up.
The simulation puts jobs on three queues and gives each channel worker a turn every second of a fake clock. The email fails once, and one SMS number never works.
A failed job goes back on its queue with exponential backoff: wait 2 seconds, then 4, doubling each time, so a struggling provider gets room to recover. After 3 attempts the job moves to the dead-letter list. Real workers run in parallel; the turn-by-turn loop just keeps the output the same on every run.
Predict the output
Predict the retries and the duplicates
Read each snippet and choose what it prints.
Round 1 of 2
A job fails every time. When are its attempts made?
Next step
Check your understanding
12 quick questions