SyntaxPilot
Courses/Low-Level Design/Lesson 72
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 72 of 90

Design a notification service

notification servicechannels email SMS pushNotificationtemplate engineuser preferencesNotificationSender interfaceFactory for channelsObserver for eventsretries and fallback channelsrate limits per userdelivery status tracking

These are the notes for Low-Level Design (LLD) episode 72: designing a notification service, the part of an app that sends OTPs, order updates and offers by email, SMS and push. We start with order code that sends everything itself, watch it message the wrong people, and fix one problem at a time: a Notification record and a NotificationSender interface, a Factory for channels, a template engine, user preferences, the Observer pattern for events, retries and fallback channels, delivery status tracking and rate limits per user.

How the code was run: every program was saved as Main.java in a fresh folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly. Users, orders and messages are made up for teaching; the "senders" print instead of calling real email or SMS providers.

1. The problem: sending wedding invitations

Wedding invitations Notification service
A printed card, a phone call, a WhatsApp message Channels: email, SMS, push
One printed card: "Dear ____, you're invited" A template with placeholders
Nani only answers calls; cousins only read WhatsApp User preferences
Don't call Nani ten times a day A rate limit per user
A tick list of who got it Delivery status tracking
Call not picked up? Send a WhatsApp A fallback channel

2. The words

  • Notification: one message to one user on one channel.
  • Channel: the way it travels.
  • Email: to an inbox.
  • SMS (short message service): a text message to a phone number.
  • Push: the pop-up an app shows on your phone, sent to your device through the app.
  • Notification service: one module that decides what to send, to whom, and on which channel.

3. Attempt 1: the order code sends everything

import java.util.*;
class OrderService {                                   // attempt: the order code sends everything itself
    Map<String, String> names = Map.of("u1", "Asha");
    void shipped(String userId, int order) {
        String text = "Hi " + names.get(userId) + ", order " + order + " is shipped";
        System.out.println("EMAIL -> " + userId + ": " + text);       // every channel, hard-coded here
        System.out.println("SMS   -> " + userId + ": " + text);       // Asha turned SMS OFF last week...
        System.out.println("PUSH  -> " + userId + ": " + text);
    }
    void delivered(String userId, int order) {         // copy-paste for every new event
        String text = "Hi " + names.get(userId) + ", order " + order + " is delivered";
        System.out.println("EMAIL -> " + userId + ": " + text);
        System.out.println("SMS   -> " + userId + ": " + text);
        System.out.println("PUSH  -> " + userId + ": " + text);
    }
}
public class Main { public static void main(String[] args) {
    OrderService orders = new OrderService();
    orders.shipped("u1", 742);
    orders.delivered("u2", 743);                       // a new user, not in the names map yet
} }

Output:

EMAIL -> u1: Hi Asha, order 742 is shipped
SMS   -> u1: Hi Asha, order 742 is shipped
PUSH  -> u1: Hi Asha, order 742 is shipped
EMAIL -> u2: Hi null, order 743 is delivered
SMS   -> u2: Hi null, order 743 is delivered
PUSH  -> u2: Hi null, order 743 is delivered

Why it failed

  • Channels are hard-coded inside business code: a new channel (WhatsApp) means editing every event method.
  • Text glued by hand: a missing value quietly prints null ("Hi null").
  • No user preferences: Asha switched SMS off and still got one.
  • Copy-paste for every new event.

4. The fix: an interface, a Factory, a template engine, preferences

  1. NotificationSender interface: one method, send(Notification). EmailSender, SmsSender and PushSender each implement it, so the rest of the code only knows the interface (episode 7: programming to an interface).
  2. Factory (episode 23): SenderFactory.of(Channel.SMS) returns the right sender. Here it is a registry-based factory: a map from each channel to a Supplier (a function with no input that makes an object, SmsSender::new). A new channel is one new class plus one line in the map.
  3. Template engine: a template is text with placeholders in double curly braces, "Hi {{name}}, order {{order}} is shipped". The engine replaces each placeholder with its value and fails loudly if one is left.
  4. User preferences: a map from each user to the channels they allow, e.g. u1 → {EMAIL, PUSH}. EnumSet is a fast, compact Set for enum values.
import java.util.*;  import java.util.function.Supplier;
enum Channel { EMAIL, SMS, PUSH }
record Notification(String userId, Channel channel, String text) {}
interface NotificationSender { void send(Notification n); }       // one interface, many channels
class EmailSender implements NotificationSender {
    public void send(Notification n) { System.out.println("  email to " + n.userId() + ": " + n.text()); } }
class SmsSender implements NotificationSender {
    public void send(Notification n) { System.out.println("  sms   to " + n.userId() + ": " + n.text()); } }
class PushSender implements NotificationSender {
    public void send(Notification n) { System.out.println("  push  to " + n.userId() + ": " + n.text()); } }
class SenderFactory {                                             // Factory: a Channel -> the right sender
    private static final Map<Channel, Supplier<NotificationSender>> MAKERS =
        Map.of(Channel.EMAIL, EmailSender::new, Channel.SMS, SmsSender::new, Channel.PUSH, PushSender::new);
    static NotificationSender of(Channel c) { return MAKERS.get(c).get(); } }
class TemplateEngine {                                            // "Hi {{name}}" + values -> the text
    static String render(String t, Map<String, String> values) {
        for (var e : values.entrySet()) t = t.replace("{{" + e.getKey() + "}}", e.getValue());
        if (t.contains("{{")) throw new IllegalArgumentException("missing value in: " + t);
        return t; } }
public class Main { public static void main(String[] args) {
    Map<String, Set<Channel>> prefs = Map.of("u1", EnumSet.of(Channel.EMAIL, Channel.PUSH),   // user preferences
                                             "u2", EnumSet.of(Channel.SMS));
    Map<String, String> names = Map.of("u1", "Asha", "u2", "Ravi");
    String shipped = "Hi {{name}}, order {{order}} is shipped";
    for (String user : List.of("u1", "u2")) {
        String text = TemplateEngine.render(shipped, Map.of("name", names.get(user), "order", "742"));
        for (Channel c : prefs.get(user)) SenderFactory.of(c).send(new Notification(user, c, text)); }
    TemplateEngine.render(shipped, Map.of("order", "743"));      // forgot the name
} }

Output:

  email to u1: Hi Asha, order 742 is shipped
  push  to u1: Hi Asha, order 742 is shipped
  sms   to u2: Hi Ravi, order 742 is shipped
Exception in thread "main" java.lang.IllegalArgumentException: missing value in: Hi {{name}}, order 743 is shipped
    at TemplateEngine.render(Main.java:18)
    at Main.main(Main.java:28)

Asha gets email and push (no SMS); Ravi gets only SMS; the forgotten name is a loud IllegalArgumentException instead of a silent "Hi null".

5. The Observer pattern: services publish events

If every service (orders, payments, delivery, support) calls the notification service directly, they are all coupled to it. The Observer pattern (episode 35) fixes that:

  • An event is a fact that happened, with its data: order.shipped for user u1, order 742.
  • Publishers (the order service) just publish events.
  • An event bus delivers each event to every subscriber (observer) of that event type.
  • The notification service subscribes to the event types it has a template for. Analytics can subscribe too.
import java.util.*;  import java.util.function.Consumer;
record Event(String type, String userId, Map<String, String> data) {}
class EventBus {                                         // Observer: subjects publish, observers listen
    private final Map<String, List<Consumer<Event>>> subs = new HashMap<>();
    void subscribe(String type, Consumer<Event> l) { subs.computeIfAbsent(type, k -> new ArrayList<>()).add(l); }
    void publish(Event e) { subs.getOrDefault(e.type(), List.of()).forEach(l -> l.accept(e)); }
}
class NotificationService {                                      // the ONE place that knows about notifications
    private final Map<String, String> templates = Map.of(
        "order.shipped",   "Hi {{name}}, order {{order}} is shipped",
        "order.delivered", "Hi {{name}}, order {{order}} is delivered. Rate it?");
    private final Map<String, List<String>> prefs = Map.of("u1", List.of("EMAIL", "PUSH"), "u2", List.of("SMS"));
    NotificationService(EventBus bus) { templates.keySet().forEach(type -> bus.subscribe(type, this::onEvent)); }
    void onEvent(Event e) {
        String text = templates.get(e.type());
        for (var v : e.data().entrySet()) text = text.replace("{{" + v.getKey() + "}}", v.getValue());
        for (String ch : prefs.get(e.userId())) System.out.println("  " + ch + " -> " + e.userId() + ": " + text);}
}
class OrderService {                                             // knows NOTHING about email, SMS or push
    private final EventBus bus;  OrderService(EventBus bus) { this.bus = bus; }
    void update(String type, String user, String name, int order) {
        bus.publish(new Event(type, user, Map.of("name", name, "order", "" + order))); }
}
public class Main { public static void main(String[] args) {
    EventBus bus = new EventBus();  new NotificationService(bus);
    bus.subscribe("order.shipped", e -> System.out.println("  analytics: +1 shipped"));   // another observer
    OrderService orders = new OrderService(bus);
    orders.update("order.shipped", "u1", "Asha", 742);
    orders.update("order.delivered", "u2", "Ravi", 743); } }

Output:

  EMAIL -> u1: Hi Asha, order 742 is shipped
  PUSH -> u1: Hi Asha, order 742 is shipped
  analytics: +1 shipped
  SMS -> u2: Hi Ravi, order 743 is delivered. Rate it?

To add a new kind of notification, add a template. OrderService never changes. this::onEvent is a method reference: a short way to pass the method onEvent as a Consumer<Event>.

6. Retries, fallback channels and delivery status tracking

The courier The dispatcher
Rings the bell, waits, rings again Retry: try the same channel N times
Leaves it with the neighbour Fallback channel: try the next channel (push → SMS)
Returns it to the sender GAVE_UP: a final status
The tracking page shows every step Delivery status tracking: a history per notification
import java.util.*;
enum Status { QUEUED, FAILED, SENT, GAVE_UP }
interface Sender { String name();  void send(String user, String text) throws Exception; }
class FlakyPush implements Sender {                            // the phone is offline: push always fails
    public String name() { return "PUSH"; }
    public void send(String u, String t) throws Exception { throw new Exception("offline"); } }
class Sms implements Sender {
    public String name() { return "SMS"; }
    public void send(String u, String t) { System.out.println("  SMS to " + u + ": " + t); } }
class Dispatcher {
    final Map<String, List<String>> history = new LinkedHashMap<>();  // delivery status tracking
    void track(String id, Object status) { history.computeIfAbsent(id, k -> new ArrayList<>()).add("" + status); }
    void deliver(String id, String user, String text, List<Sender> channels, int triesEach) {
        track(id, Status.QUEUED);
        for (Sender ch : channels) {                           // fallback: the next channel in the list
            for (int t = 1; t <= triesEach; t++) {             // retries on the same channel
                try { ch.send(user, text);  track(id, Status.SENT + " via " + ch.name());  return; }
                catch (Exception e) { track(id, "FAILED " + ch.name() + " #" + t + " " + e.getMessage()); }
            } }
        track(id, Status.GAVE_UP); }
}
public class Main { public static void main(String[] args) {
    Dispatcher d = new Dispatcher();
    d.deliver("n1", "u1", "Your OTP is 482913", List.of(new FlakyPush(), new Sms()), 2);  // push, then SMS
    d.deliver("n2", "u2", "Order 743 is delivered", List.of(new FlakyPush()), 2);         // push only
    d.history.forEach((id, h) -> System.out.println(id + ": " + String.join(" -> ", h))); } }

Output:

  SMS to u1: Your OTP is 482913
n1: QUEUED -> FAILED PUSH #1 offline -> FAILED PUSH #2 offline -> SENT via SMS
n2: QUEUED -> FAILED PUSH #1 offline -> FAILED PUSH #2 offline -> GAVE_UP

The OTP fell back to SMS; the push-only order update gave up. When a customer says "I never got my OTP", support can read the exact history. (In a real system each try would also wait longer: exponential backoff from episode 71.)

7. Rate limits per user, with priority

A big sale sends 20 promo pushes an hour; the user mutes the app, and now the important messages are lost too.

  • Rate limit per user: at most N notifications per user per time window (here 3 per hour).
  • Fixed window (episode 68): count each user's messages; reset when the hour is over.
  • Priority: transactional messages (OTP, order updates: the user needs them) vs promotional ones (offers). An OTP must never be blocked; limit the promos.
import java.util.*;
enum Kind { OTP, ORDER_UPDATE, PROMO }                     // how important a notification is
class RateLimiter {                                        // per user: at most 3 per hour (a fixed window)
    final int limit;  final long window;  final Map<String, long[]> users = new HashMap<>();  // [start, count]
    RateLimiter(int limit, long window) { this.limit = limit;  this.window = window; }
    boolean allow(String user, long now) {
        long[] w = users.computeIfAbsent(user, u -> new long[]{now, 0});
        if (now - w[0] >= window) { w[0] = now;  w[1] = 0; }   // a new hour: start counting again
        if (w[1] >= limit) return false;
        w[1]++;  return true; }
}
public class Main { public static void main(String[] args) {
    RateLimiter perUser = new RateLimiter(3, 60 * 60_000);   // 3 per user per hour
    Kind[] burst = {Kind.PROMO, Kind.PROMO, Kind.ORDER_UPDATE, Kind.PROMO, Kind.PROMO, Kind.OTP};
    long now = 0;
    for (Kind k : burst) {
        now += 60_000;                                       // one a minute
        boolean critical = k == Kind.OTP;                    // an OTP must never be blocked
        boolean ok = critical || perUser.allow("u1", now);
        System.out.printf("minute %d  %-12s %s%n", now / 60_000, k, ok ? "sent" : "DROPPED: rate limit");
    }
    System.out.println("an hour later: " + (perUser.allow("u1", now + 60 * 60_000) ? "sent" : "DROPPED")); } }

Output:

minute 1  PROMO        sent
minute 2  PROMO        sent
minute 3  ORDER_UPDATE sent
minute 4  PROMO        DROPPED: rate limit
minute 5  PROMO        DROPPED: rate limit
minute 6  OTP          sent
an hour later: sent

8. The class diagram

OrderService ─publish(Event)─▶ EventBus ─▶ NotificationService      (Observer)
NotificationService: Event ─ TemplateEngine("Hi {{name}}", data) ─▶ text
  UserPreferences: userId ─▶ {EMAIL, PUSH}      RateLimiter: per user, OTP never blocked
  SenderFactory.of(channel) ─▶ NotificationSender (EmailSender · SmsSender · PushSender)
Dispatcher: for each channel in order (fallback) · try N times (retries)
  delivery status: QUEUED ─▶ FAILED ... ─▶ SENT via SMS | GAVE_UP

Patterns used: Factory (channels), Observer (events), Strategy-like senders behind one interface, and an Adapter whenever a real provider's API differs (episode 27).

9. Interview follow-ups

Question Answer
Millions of messages a minute A queue between the event bus and the senders, with many workers (episode 69's pub-sub)
No duplicate OTPs when something retries An idempotency key per event/notification; skip a key already sent
Quiet hours Hold promotional messages from, say, 10 PM to 8 AM
A new SMS provider with a different API An Adapter behind NotificationSender (episode 27)
Many languages One template per (event type, language)
Did the user actually read it? Providers report delivered/opened through callbacks (webhooks); add those statuses

10. Common mistakes

Mistake What you see (real message) Why Fix
Channels hard-coded in order code SMS -> u1 for a user who switched SMS off No preferences Preferences + a Factory
Text glued by hand Hi null, order 743 is delivered A missing value A template engine that fails
Map.of with a missing value java.lang.NullPointerException at java.util.Objects.requireNonNull ... at java.util.Map.of Map.of forbids nulls Check the value first
A channel added to the enum but not the factory java.lang.NullPointerException: Cannot invoke "java.util.function.Supplier.get()" because the return value of "java.util.Map.get(Object)" is null No maker registered Register it; throw a clear error for unknown channels
Implementing an interface method without public error: send(String) in SmsSender cannot implement send(String) in NotificationSender ... attempting to assign weaker access privileges; was public Interface methods are public Write public void send(...)
Calling a throwing method inside a Consumer lambda error: unreported exception Exception; must be caught or declared to be thrown Consumer.accept can't throw checked exceptions try/catch inside the lambda, or your own interface that throws Exception
Giving up after one failure The OTP never arrives Device offline Retry + fallback channel
Rate-limiting everything An OTP DROPPED No priority Never block transactional messages

Mini project: a complete notification service

Events in (Observer), a template per event type with a kind (transactional or promotional), preferences in order (fallback), a sender Factory, retries per channel, a per-user rate limit for promos, quiet hours, idempotency keys and a delivery-status history.

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Supplier;

// Mini project: a notification service. Events in (Observer), templates per event type, user preferences in
// order (fallback), a sender Factory, retries per channel, per-user rate limits that never block transactional
// messages, quiet hours for promos, idempotency keys and a delivery-status history.
enum Channel { PUSH, SMS, EMAIL }
enum Kind { TRANSACTIONAL, PROMOTIONAL }
record Event(String id, String type, String userId, Map<String, String> data) {}
record Notification(String id, String userId, Channel channel, String text) {}

interface NotificationSender { void send(Notification n) throws Exception; }

class EmailSender implements NotificationSender {
    public void send(Notification n) { System.out.println("    email -> " + n.userId() + ": " + n.text()); }
}
class SmsSender implements NotificationSender {
    public void send(Notification n) { System.out.println("    sms   -> " + n.userId() + ": " + n.text()); }
}
class PushSender implements NotificationSender {
    static final Set<String> offline = new HashSet<>(Set.of("u2"));     // u2's phone is offline
    public void send(Notification n) throws Exception {
        if (offline.contains(n.userId())) throw new Exception("device offline");
        System.out.println("    push  -> " + n.userId() + ": " + n.text());
    }
}

class SenderFactory {
    private static final Map<Channel, Supplier<NotificationSender>> MAKERS = Map.of(
        Channel.EMAIL, EmailSender::new, Channel.SMS, SmsSender::new, Channel.PUSH, PushSender::new);
    static NotificationSender of(Channel c) {
        Supplier<NotificationSender> m = MAKERS.get(c);
        if (m == null) throw new IllegalArgumentException("no sender for " + c);
        return m.get();
    }
}

class TemplateEngine {
    static String render(String t, Map<String, String> values) {
        for (var e : values.entrySet()) t = t.replace("{{" + e.getKey() + "}}", e.getValue());
        if (t.contains("{{")) throw new IllegalArgumentException("missing value in: " + t);
        return t;
    }
}

class EventBus {
    private final Map<String, List<Consumer<Event>>> subs = new HashMap<>();
    void subscribe(String type, Consumer<Event> l) { subs.computeIfAbsent(type, k -> new ArrayList<>()).add(l); }
    void publish(Event e) { subs.getOrDefault(e.type(), List.of()).forEach(l -> l.accept(e)); }
}

class NotificationService {
    record Template(Kind kind, String text) {}
    private final Map<String, Template> templates = Map.of(
        "otp.requested", new Template(Kind.TRANSACTIONAL, "Your OTP is {{otp}}. Valid for 30 seconds."),
        "order.shipped", new Template(Kind.TRANSACTIONAL, "Hi {{name}}, order {{order}} is shipped"),
        "sale.started",  new Template(Kind.PROMOTIONAL, "Hi {{name}}, the sale is live: {{offer}}"));
    private final Map<String, List<Channel>> prefs = Map.of(
        "u1", List.of(Channel.PUSH, Channel.EMAIL), "u2", List.of(Channel.PUSH, Channel.SMS));
    private final Map<String, long[]> windows = new HashMap<>();   // user -> [window start, count]
    private final Set<String> seenIds = new HashSet<>();           // idempotency keys
    final Map<String, List<String>> status = new LinkedHashMap<>();
    long now = 0;                                                  // a fake clock, in minutes since midnight
    final int limitPerHour = 2, triesPerChannel = 2;

    NotificationService(EventBus bus) { templates.keySet().forEach(t -> bus.subscribe(t, this::onEvent)); }

    private void track(String id, String s) { status.computeIfAbsent(id, k -> new ArrayList<>()).add(s); }

    private boolean allow(String user) {
        long[] w = windows.computeIfAbsent(user, u -> new long[]{now, 0});
        if (now - w[0] >= 60) { w[0] = now; w[1] = 0; }
        if (w[1] >= limitPerHour) return false;
        w[1]++;
        return true;
    }

    void onEvent(Event e) {
        if (!seenIds.add(e.id())) { System.out.println("  " + e.id() + ": duplicate event, skipped"); return; }
        Template t = templates.get(e.type());
        track(e.id(), "QUEUED");
        boolean quiet = now >= 22 * 60 || now < 8 * 60;               // 10 PM to 8 AM
        if (t.kind() == Kind.PROMOTIONAL && quiet) { track(e.id(), "HELD (quiet hours)"); return; }
        if (t.kind() == Kind.PROMOTIONAL && !allow(e.userId())) { track(e.id(), "DROPPED (rate limit)"); return; }
        String text = TemplateEngine.render(t.text(), e.data());
        System.out.println("  " + e.id() + " (" + e.type() + "):");
        for (Channel c : prefs.get(e.userId())) {                     // fallback: the next preferred channel
            NotificationSender sender = SenderFactory.of(c);
            for (int i = 1; i <= triesPerChannel; i++) {              // retries on this channel
                try {
                    sender.send(new Notification(e.id(), e.userId(), c, text));
                    track(e.id(), "SENT via " + c);
                    return;
                } catch (Exception ex) { track(e.id(), "FAILED " + c + " #" + i + " " + ex.getMessage()); }
            }
        }
        track(e.id(), "GAVE_UP");
    }
}

public class Main {
    public static void main(String[] args) {
        EventBus bus = new EventBus();
        NotificationService ns = new NotificationService(bus);
        ns.now = 9 * 60;                                              // 9:00 AM
        bus.publish(new Event("e1", "otp.requested", "u2", Map.of("otp", "482913")));
        bus.publish(new Event("e1", "otp.requested", "u2", Map.of("otp", "482913")));   // the same event again
        bus.publish(new Event("e2", "order.shipped", "u1", Map.of("name", "Asha", "order", "742")));
        for (int i = 3; i <= 5; i++)
            bus.publish(new Event("e" + i, "sale.started", "u1", Map.of("name", "Asha", "offer", "20% off")));
        ns.now = 23 * 60;                                             // 11:00 PM
        bus.publish(new Event("e6", "sale.started", "u2", Map.of("name", "Ravi", "offer", "20% off")));
        bus.publish(new Event("e7", "order.shipped", "u2", Map.of("name", "Ravi", "order", "743")));
        System.out.println("delivery status:");
        ns.status.forEach((id, h) -> System.out.println("  " + id + ": " + String.join(" -> ", h)));
    }
}

Output:

  e1 (otp.requested):
    sms   -> u2: Your OTP is 482913. Valid for 30 seconds.
  e1: duplicate event, skipped
  e2 (order.shipped):
    push  -> u1: Hi Asha, order 742 is shipped
  e3 (sale.started):
    push  -> u1: Hi Asha, the sale is live: 20% off
  e4 (sale.started):
    push  -> u1: Hi Asha, the sale is live: 20% off
  e7 (order.shipped):
    sms   -> u2: Hi Ravi, order 743 is shipped
delivery status:
  e1: QUEUED -> FAILED PUSH #1 device offline -> FAILED PUSH #2 device offline -> SENT via SMS
  e2: QUEUED -> SENT via PUSH
  e3: QUEUED -> SENT via PUSH
  e4: QUEUED -> SENT via PUSH
  e5: QUEUED -> DROPPED (rate limit)
  e6: QUEUED -> HELD (quiet hours)
  e7: QUEUED -> FAILED PUSH #1 device offline -> FAILED PUSH #2 device offline -> SENT via SMS
  • e1 (the OTP) tried push twice, then fell back to SMS; the same event published twice was skipped by its idempotency key.
  • e3, e4 (promos) were sent; e5 was dropped by the rate limit (2 per hour in this run).
  • e6 (a promo at 11 PM) was held for quiet hours; e7 (an order update at 11 PM) went out anyway: it is transactional.

Practice

1. Add a WhatsApp channel.

Answer

Add WHATSAPP to Channel, write class WhatsAppSender implements NotificationSender, and add Channel.WHATSAPP, WhatsAppSender::new to the factory map. Nothing else changes. Forget the map line and you get the Supplier.get() NullPointerException from the mistakes table.

2. Add quiet hours for promotional notifications.

Answer

Before sending a promo, check the user's local time; between 10 PM and 8 AM, store it as HELD (quiet hours) and send it in the morning. See onEvent in the mini project: e6: QUEUED -> HELD (quiet hours).

3. Add an idempotency key so the same event never sends twice.

Answer

Keep a set of processed event ids (in a database in real life); if (!seenIds.add(e.id())) return;. See the mini project: e1: duplicate event, skipped.

4. Add exponential backoff between retries.

Answer

Instead of retrying immediately, put the notification back on a scheduler (episode 71) with delay = base × 2^(try − 1) plus jitter, and keep the try count in the notification.

5. Why should the notification service own the templates, not the order service?

Answer

So wording, languages and channels can change without touching business code. The order service only publishes the facts (order.shipped, the order number); the notification service decides the words.

Quick quiz

The limit is 3 per user per hour, and OTPs skip the limiter. In one hour u1 gets: PROMO, OTP, PROMO, PROMO, PROMO. How many PROMOs are sent? (a) 1 (b) 2 (c) 3 (d) 4

Answer

(c) 3. The OTP doesn't use up the count, so the first three promos are sent and the fourth is dropped. Real run with the episode's RateLimiter:

minute 1  PROMO        sent
minute 2  OTP          sent
minute 3  PROMO        sent
minute 4  PROMO        sent
minute 5  PROMO        DROPPED: rate limit
an hour later: sent

Interview questions

  1. What are the main components of a notification service? Event intake, templates, preferences, rate limiting, channel senders, retries/fallback, status tracking.
  2. Why an interface for senders? New channels without changing the service; easy to fake in tests.
  3. Where does the Factory pattern fit? Turning a channel value into the right sender object.
  4. Where does the Observer pattern fit? Services publish events; the notification service subscribes.
  5. How do you handle a failed push? Retry a few times (with backoff), then fall back to the next preferred channel, then mark it gave up.
  6. How do you avoid duplicate notifications? Idempotency keys stored with the send result.
  7. How do you rate-limit without blocking OTPs? Limit per user per window, only for promotional messages.
  8. What would you store for each notification? Id, user, channel, template, status history with timestamps, attempts.
  9. How would you scale it? A queue between intake and senders, many workers, sharded by user id.
  10. How do you add a new language? Templates keyed by (event type, language), picked from the user's profile.

Glossary

Term Meaning, with an example
Notification One message to one user on one channel
Notification service The module that decides what to send, to whom, on which channel
Channel How a message travels: EMAIL, SMS, PUSH
Email A message to an inbox
SMS A text message to a phone number
Push notification A pop-up from an app, sent to the user's device
NotificationSender Our interface: void send(Notification n)
Interface / implements A contract of methods / a class that fulfils it
Factory An object or method that creates the right object for you: SenderFactory.of(Channel.SMS)
Registry-based factory A factory that looks up a maker in a map
Supplier A function with no input that returns a value: SmsSender::new
Template Text with placeholders: Hi {{name}}
Placeholder A named gap to fill: {{name}}
Template engine Fills a template's placeholders with values
User preferences The channels each user allows, in order
EnumSet A fast Set of enum values: EnumSet.of(EMAIL, PUSH)
Event A fact that happened: order.shipped + data
Observer pattern Subjects publish; observers subscribe and react
Event bus Delivers each event to its subscribers
Subscriber (observer) Code that reacts to an event type
Method reference this::onEvent: pass a method as a function
Coupling How much one class depends on others
Retry Trying the same channel again
Fallback channel The next channel to try when one keeps failing
Delivery status tracking A history of what happened to each notification
QUEUED / SENT / FAILED / GAVE_UP The statuses in that history
Rate limit per user At most N notifications per user per window
Fixed window Count per time window; reset when it ends
Transactional message One the user needs: OTP, order update
Promotional message An offer or marketing message
Quiet hours Times when promos are held: 10 PM to 8 AM
Idempotency key A unique id so the same notification is never sent twice
Dead-letter list Where notifications that failed everywhere are parked
Adapter Wraps a provider's different API behind our interface
Webhook A provider calling your URL to report delivered/opened

Summary

  • Sending from the order code ignored preferences, printed "Hi null", and needed copy-paste for every event.
  • A NotificationSender interface, a Factory for channels, a template engine that fails loudly and user preferences separated the concerns.
  • The Observer pattern let services just publish events; the notification service subscribes with one template per event type.
  • Retries and fallback channels got the OTP through; delivery status tracking recorded every step.
  • A per-user rate limit dropped promo floods while never blocking OTPs.
  • Next episode: design a library management system.