LLD

Full Designs

Notification Service

A weak answer has a sendEmail, a sendSms and a sendPush, and calls all three. We build a service that holds up when the interviewer pushes: which channel a user gets, why a 2 am order update waits until morning, what happens when a provider keeps failing, and why a retried request never reaches the user twice.

"Design a notification service" sounds like three methods: sendEmail, sendSms and sendPush, one each for email, SMS (text messages) and push notifications on a phone. A weak answer writes them, and a notify method calls all three. The user then gets every order update three times. If the push provider is down, the message is lost and nobody knows. If the orders service times out and asks again, the user gets the message twice. And an order update can arrive at 2 am.

The interviewer is checking a few specific things. A user's settings must decide the channel, so channels must be values the code can choose between. A send that fails must be tried again, then on another channel, and in the end recorded as a failure, not lost. The same event asked for twice must reach the user once. And many callers and workers touch the same state, so the design must say what the lock guards and what it never covers.

This article follows a 45 minute interview. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.

Some of this overlaps with the Pub-Sub design, which covers retries, dead letters and at-least-once delivery in depth. We link to it and keep only what is different here.

A notification service at a glance
The orders service calls submit with a key that names the event (1). The service reads asha's settings from the settings service (2): push first, then email, with quiet hours from 22:00 to 07:00. The notification joins a queue ordered by due time. A worker thread calls deliverDue (3), which sends due notifications to the push provider (4). If push keeps failing, the email provider gets it (5). The SMS provider is not one of asha's channels. If every channel fails, the notification is kept as FAILED, with every attempt (6).The orders service calls submit with a key that names the event (1). The service reads asha's settings from the settings service (2): push first, then email, with quiet hours from 22:00 to 07:00. The notification joins a queue ordered by due time. A worker thread calls deliverDue (3), which sends due notifications to the push provider (4). If push keeps failing, the email provider gets it (5). The SMS provider is not one of asha's channels. If every channel fails, the notification is kept as FAILED, with every attempt (6).
The caller only records a request. A worker sends it later. The orders service calls submit with a key that names the event (1). The service reads asha's settings from the settings service (2): push first, then email, with quiet hours from 22:00 to 07:00. The notification joins a queue ordered by due time. A worker thread calls deliverDue (3), which sends due notifications to the push provider (4). If push keeps failing, the email provider gets it (5). The SMS provider is not one of asha's channels. If every channel fails, the notification is kept as FAILED, with every attempt (6).

Ask before you design

The question is vague on purpose. Each question below changes the code, and the right-hand column says how.

QuestionWhat we assumeWhat it changes
Which channels?Email, SMS and pushA Channel enum, and one ChannelSender per channel
Does a notification go to every channel, or one?The user's first choice. The next one only if it failsAn ordered list of channels per user, and a fallback
Who picks the channels?The user, in their settingsA PreferenceStore, read when the request arrives
Can a notification wait?A normal one waits for the user's quiet hours to end. An urgent one, like a login code, does notUrgency, and QuietHours in the user's own time zone
Does the caller wait for the send?No. The service records it, and a worker sends itA queue ordered by due time, and deliverDue
What counts as a failure?The provider says if it is worth trying again. A send that throws counts as worth trying againSendResult with three values
How often do we retry?It depends on the channel: a number of attempts and a wait that doublesA RetryPolicy per channel
What if every channel fails?Keep it, marked as failed, with every attemptStatus.FAILED and failures()
Can a caller ask twice for the same event?Yes, after a timeout. The user must get it onceAn idempotency key on every request
Do many callers and workers run at once?YesOne lock for the bookkeeping, never held during a send

The second question matters most. If a notification goes to every channel, there is no fallback, and the user sees each message up to three times. If it goes to one channel at a time, the design needs an order of channels per user, a rule for when to give up on a channel, and a record of what was tried. We take the second answer and argue for it in "Channels behind one interface" below.

Requirements

Functional:

  1. submit takes a request with an idempotency key, a user, an urgency, a title and a body, and returns a notification id. It sends nothing itself.
  2. A notification goes to the first channel in the user's settings. A user who accepts no channel gets nothing, and the notification is marked OPTED_OUT.
  3. A normal notification never goes out during the user's quiet hours. It waits for them to end. An urgent one goes out at once.
  4. A worker calls deliverDue, which sends everything that is due. After a temporary failure, the same channel is tried again after the channel's wait, up to its maxAttempts.
  5. After a permanent failure, or the last attempt on a channel, the notification moves to the user's next channel at once.
  6. When the last channel fails, the notification is FAILED, with every attempt kept. failures() lists them.
  7. A request whose key was seen before returns the first id and sends nothing new. The same key with a different request is refused.
  8. report returns a notification's status and every attempt.

Out of scope: digests, sending at a set time, rate limits per user, templates in many languages, read receipts, forgetting old keys, and keeping anything on disk. We come back to these at the end, because each is a likely follow-up.

Everything lives in memory, as is normal for a low-level design interview.

What the code itself must handle:

  • Many threads at once. Callers submit while several workers send.
  • Outside calls that fail. A provider can say no, throw, be slow or return nothing. The settings service can throw.
  • Rules that change. Which provider sends a channel, and how often each channel is retried, are set from outside the core class.
  • Testable time. Quiet hours and retry waits depend on the time, so the service takes a Clock.

Finding the classes

Picking the nouns out of the requirements gives a first list. Two of them hold state that changes: the service, with its keys and its queue, and each notification, with its progress through the channels. They become classes. Most of the rest are values that never change, and the two things outside the code become interfaces.

From nouns to classes
The service and the notification become classes. The request, the user's settings, quiet hours, the retry rule, the message for a provider, an attempt and a report become records. Channel, urgency, the provider's answer and the status become enums. The provider and the settings service become interfaces. Seven nouns are dropped. A calling service is any caller of submit, and a worker is any thread that calls deliverDue. EmailNotification and SmsNotification become a Channel value and a sender. Templates are out of scope. The idempotency store is a map, the retry queue is the one queue, and the dead-letter queue is a FAILED status.The service and the notification become classes. The request, the user's settings, quiet hours, the retry rule, the message for a provider, an attempt and a report become records. Channel, urgency, the provider's answer and the status become enums. The provider and the settings service become interfaces. Seven nouns are dropped. A calling service is any caller of submit, and a worker is any thread that calls deliverDue. EmailNotification and SmsNotification become a Channel value and a sender. Templates are out of scope. The idempotency store is a map, the retry queue is the one queue, and the dead-letter queue is a FAILED status.
Most nouns become records, enums or interfaces. Seven are dropped. The service and the notification become classes. The request, the user's settings, quiet hours, the retry rule, the message for a provider, an attempt and a report become records. Channel, urgency, the provider's answer and the status become enums. The provider and the settings service become interfaces. Seven nouns are dropped. A calling service is any caller of submit, and a worker is any thread that calls deliverDue. EmailNotification and SmsNotification become a Channel value and a sender. Templates are out of scope. The idempotency store is a map, the retry queue is the one queue, and the dead-letter queue is a FAILED status.
Decision

Should each channel be a subclass of Notification?

EmailNotification, SmsNotification and PushNotification, each with its own send

It looks object-oriented, and each class knows its own provider. But a notification can start on push and end on email. An object cannot change its class, so a fallback would have to copy one notification into another. The user's settings would also have to pick a class.

One Notification; a Channel value and a ChannelSender per channelOur pick

A channel is data: an enum value in the user's list. The behaviour that differs, talking to a provider, sits behind one interface. A fallback moves an index along the user's list, and the notification stays the same object with one history.

Data or behaviour?

Some classes only carry values that never change: a request, a user's settings, one attempt. In Java these are records. A record's fields are fixed when it is created, and it gets equals, hashCode and toString for free. NotificationService and Notification are ordinary classes, because their state changes and their methods guard those changes.

The class diagram

The classes and how they connect
NotificationService owns every Notification, through its two maps and its queue. It uses a ChannelSender per channel, the PreferenceStore, a Clock and a RetryPolicy per channel. Each Notification keeps a copy of the user's UserPreferences, which holds the user's QuietHours. Methods marked ~ are package-private, so only the service package calls them. The records and enums along the bottom are the values the classes above hold or hand out. Two private records inside NotificationService, Scheduled and Claim, and NoSuchUserException are not drawn.NotificationService owns every Notification, through its two maps and its queue. It uses a ChannelSender per channel, the PreferenceStore, a Clock and a RetryPolicy per channel. Each Notification keeps a copy of the user's UserPreferences, which holds the user's QuietHours. Methods marked ~ are package-private, so only the service package calls them. The records and enums along the bottom are the values the classes above hold or hand out. Two private records inside NotificationService, Scheduled and Claim, and NoSuchUserException are not drawn.
NotificationService coordinates. Two interfaces stand for the outside world. NotificationService owns every Notification, through its two maps and its queue. It uses a ChannelSender per channel, the PreferenceStore, a Clock and a RetryPolicy per channel. Each Notification keeps a copy of the user's UserPreferences, which holds the user's QuietHours. Methods marked ~ are package-private, so only the service package calls them. The records and enums along the bottom are the values the classes above hold or hand out. Two private records inside NotificationService, Scheduled and Claim, and NoSuchUserException are not drawn.

The classes fall into three groups:

  • Data: the records NotificationRequest, UserPreferences, QuietHours, RetryPolicy, Delivery, Attempt and NotificationReport, and the enums Channel, Urgency, SendResult and Status.
  • The core: NotificationService, which owns the keys, the queue and the lock, and Notification, which tracks one notification's channel, attempts and status.
  • Outside code: ChannelSender, one per provider, and PreferenceStore, the settings service. Both are interfaces, so the demo and the tests plug in fakes.

Building it

The request

A calling service sends a NotificationRequest. The key names the event that caused it, such as order-77-shipped, so a caller that asks again sends the same key.

request/NotificationRequest.javalines 9–28 of 29
public record NotificationRequest(String idempotencyKey, String userId, Urgency urgency, String title, String body) {    public static final int MAX_KEY_LENGTH = 128;    public static final int MAX_USER_ID_LENGTH = 64;    public static final int MAX_TITLE_LENGTH = 100;    public static final int MAX_BODY_LENGTH = 1_000;     public NotificationRequest {        requireText(idempotencyKey, "idempotencyKey", MAX_KEY_LENGTH);        requireText(userId, "userId", MAX_USER_ID_LENGTH);        Objects.requireNonNull(urgency, "urgency");        requireText(title, "title", MAX_TITLE_LENGTH);        requireText(body, "body", MAX_BODY_LENGTH);    }     private static void requireText(String value, String name, int maxLength) {        Objects.requireNonNull(value, name);        if (value.isBlank() || value.length() > maxLength) {            throw new IllegalArgumentException(name + " must be 1 to " + maxLength + " characters, not blank");        }    }

Every field is checked when the record is built. A key or user id that is blank or too long, a title over 100 characters or a body over 1,000 is refused with IllegalArgumentException. These limits keep one bad caller from filling memory with a single request. All of these are mistakes in a calling service's code, not in a person's input, so they throw. The same holds for the rest of the design: every refusal is an exception.

Channels behind one interface

Email, SMS and push differ in one thing: how a message reaches the provider. So that one thing gets an interface.

channel/ChannelSender.javalines 3–12 of 12
/** Talks to one provider: an email API, an SMS gateway, a push service. */@FunctionalInterfacepublic interface ChannelSender {    /**     * Sends one message and says how it went. It is called with no lock held,     * so it may be slow, but each sender sets its own timeout on the provider     * call: a call that never returns leaves its notification SENDING.     */    SendResult send(Delivery delivery);}

A sender gets a Delivery: the address for that channel, the title, the body and a deliveryId. The id is the notification id and the channel, such as N-2/PUSH, and it stays the same on every attempt on that channel. A provider that drops repeated ids then sends a retried message once, even when our first attempt timed out after the provider had already sent it. A provider that does not drop repeats may deliver that message twice, and the service cannot tell. The id changes from channel to channel, so a push that timed out after it was delivered, followed by the email fallback, reaches the user twice, and no id can stop that.

Nothing in the service puts a time limit on send. Each sender sets its own timeout on its provider call, because a call that never returns would leave its notification marked SENDING for good.

A sender answers with a SendResult: DELIVERED, TEMPORARY_FAILURE (a timeout, a provider that is down) or PERMANENT_FAILURE (a phone number that does not exist, a push token that was revoked).

Decision

Every channel at once, or one at a time?

Send on every channel the user accepts

The user is most likely to see it. But they see it two or three times, and a failure on one channel has nothing to fall back to. It also costs an SMS for every email.

The user's first channel; the next one only when it failsOur pick

The user gets each notification once, on the channel they prefer, and the other channels become the fallback. The cost is a slower path when the first channel is down: the user hears nothing until its attempts are used up.

Preferences, read once

A user's settings are a UserPreferences record: the channels they accept in the order they prefer, an address for each, their quiet hours and their time zone. Its constructor refuses a channel listed twice or a channel with no address. The settings live in another service, which the design reaches through PreferenceStore.find(userId).

Quiet hours are a window in the user's own time, such as 22:00 to 07:00:

preference/QuietHours.javalines 22–44 of 45
    public boolean contains(LocalTime time) {        if (start.equals(end)) {            return false;        }        if (start.isBefore(end)) {            return !time.isBefore(start) && time.isBefore(end);        }        return !time.isBefore(start) || time.isBefore(end);    }     /** The first instant at or after the given one that is outside quiet hours. */    public Instant nextAllowed(Instant at, ZoneId zone) {        ZonedDateTime local = at.atZone(zone);        if (!contains(local.toLocalTime())) {            return at;        }        // with() keeps the current offset, so the second pass of a repeated hour is handled.        ZonedDateTime quietEnds = local.with(end);        if (!quietEnds.isAfter(local)) {            quietEnds = local.toLocalDate().plusDays(1).atTime(end).atZone(zone);        }        return quietEnds.toInstant();    }

The window includes its start and excludes its end, so 22:00 is quiet and 07:00 is not. If the start is after the end, the window crosses midnight, and a time is quiet if it is after the start or before the end. A window that starts and ends at the same time is empty, and QuietHours.NONE is that window. nextAllowed turns an instant into the user's local time. If that time is quiet, it returns the next time the window ends, today or tomorrow, as an instant again. with(end) keeps the current offset from UTC, so on the night clocks go back, a time in the repeated hour waits for the end of that same pass. If the end falls in the hour skipped when clocks go forward, the answer is late by up to that hour, which we accept.

Decision

When are the preferences read?

On every attempt

A user who turns off SMS at midnight is never sent an SMS after that. But a notification part way through its channels could find its list changed under it, and every retry costs a call to the settings service.

Once, in submit; the notification keeps a copyOur pick

A notification has one fixed list of channels for its whole life, so its history always makes sense. The cost is that a change of settings applies only to new notifications. A notification waiting for quiet hours to end still goes to the channels the user had when it was submitted.

No duplicate notifications

The orders service calls submit, and the call times out. It cannot tell if the notification was recorded, so it calls again with the same key. The second call must not make a second notification.

service/NotificationService.javalines 72–111 of 200
    public String submit(NotificationRequest request) {        Objects.requireNonNull(request, "request");        Notification existing = findByKey(request);        if (existing != null) {            return existing.id();        }        UserPreferences user = preferences.find(request.userId())                .orElseThrow(() -> new NoSuchUserException(request.userId()));        for (Channel channel : user.channels()) {            if (!senders.containsKey(channel)) {                throw new IllegalStateException("no sender for " + channel);            }        }        return insert(request, user);    }     private synchronized Notification findByKey(NotificationRequest request) {        Notification existing = byKey.get(request.idempotencyKey());        if (existing != null && !existing.request().equals(request)) {            throw new IllegalStateException("key " + request.idempotencyKey() + " was used for a different request");        }        return existing;    }     private synchronized String insert(NotificationRequest request, UserPreferences user) {        // Another thread may have inserted this key while we read the preferences.        Notification existing = findByKey(request);        if (existing != null) {            return existing.id();        }        Instant now = clock.instant();        Notification notification = new Notification("N-" + nextId, request, user);        nextId++;        byKey.put(request.idempotencyKey(), notification);        byId.put(notification.id(), notification);        if (notification.status() == Status.PENDING) {            schedule(notification, now);        }        return notification.id();    }

submit works in this order:

  1. Check the key (line 74). findByKey takes the lock and looks the key up. A known key returns its notification's id, and nothing else happens, not even a read of the settings.
  2. Read the settings (lines 78 to 84), with no lock held. An unknown user is refused with NoSuchUserException. A user whose channel has no sender is refused with IllegalStateException.
  3. Insert (line 85). insert takes the lock and checks the key again (line 98), because another caller may have inserted it while we were reading the settings. Only then does it read the clock, make the notification and put it in the maps and the queue.

Everything that can fail happens before anything changes. The settings service can throw, the user can be unknown, the clock can throw. In each case the maps, the queue and the next id are as they were, and the caller can try again with the same key.

A request whose key is known is compared with the first one. Records compare every field, so a different body, user or urgency is a different request. findByKey refuses it with IllegalStateException. Two different events sharing a key is a bug in the caller, and quietly returning the first id would hide that the second message was never sent.

Decision

What happens when a key comes back?

Nothing special: send it again

There is nothing to store. But every timeout and retry in the calling service becomes a second message to the user.

Return the first id, whatever the request says

Retries are safe. But a caller that reuses a key by mistake gets a success back, and its second message is silently lost.

Return the first id for the same request; refuse a different oneOur pick

Retries are safe, and a reused key fails loudly. The cost is memory: every key is kept for as long as the service runs. "Forget old keys" is a follow-up at the end.

The second check inside insert is what makes the key safe under threads. Without it, two callers can both pass the first check before either inserts:

Two calls, one key
On the left, caller A and caller B (a retry of the same event) both run findByKey and find nothing. Both read the settings. A inserts N-7, then B inserts N-8, so the user gets order 77 twice. On the right, insert checks the key again under the lock (amber). A inserts N-7. When B's insert runs, it finds the key and returns N-7, so there is one notification and one id.On the left, caller A and caller B (a retry of the same event) both run findByKey and find nothing. Both read the settings. A inserts N-7, then B inserts N-8, so the user gets order 77 twice. On the right, insert checks the key again under the lock (amber). A inserts N-7. When B's insert runs, it finds the key and returns N-7, so there is one notification and one id.
Checking the key once is not enough when the check and the insert are separate steps. On the left, caller A and caller B (a retry of the same event) both run findByKey and find nothing. Both read the settings. A inserts N-7, then B inserts N-8, so the user gets order 77 twice. On the right, insert checks the key again under the lock (amber). A inserts N-7. When B's insert runs, it finds the key and returns N-7, so there is one notification and one id.

Sending from a worker

submit puts the notification in a queue and returns. The sending happens elsewhere.

Decision

Does submit send, or does a worker?

submit sends, and retries, before it returns

The caller learns the result at once. But the caller waits for the provider, a retry five minutes away holds its thread for five minutes, and a normal notification in quiet hours cannot wait until 07:00 at all.

submit queues; a worker calls deliverDueOur pick

The caller returns as soon as the notification is recorded. Waits for retries and quiet hours become due times in a queue, with no thread asleep. The cost is that the caller does not learn the outcome. It asks report later, and failures are listed by failures().

The queue is a PriorityQueue of entries ordered by due time, then by a sequence number, so two notifications due at once go out in the order they were queued. A worker thread calls deliverDue every few seconds:

service/NotificationService.javalines 118–137 of 200
    public int deliverDue() {        Instant cutoff = clock.instant();        int sends = 0;        Claim claim = claimNext(cutoff);        while (claim != null) {            // A throw, an Error or a null answer counts as a temporary failure.            SendResult result = SendResult.TEMPORARY_FAILURE;            try {                ChannelSender sender = senders.get(claim.delivery().channel());                result = Objects.requireNonNullElse(sender.send(claim.delivery()), SendResult.TEMPORARY_FAILURE);            } catch (RuntimeException e) {                // Treated like a timeout: the result stays TEMPORARY_FAILURE and the loop goes on.            } finally {                record(claim, result, cutoff);            }            sends++;            claim = claimNext(cutoff);        }        return sends;    }

deliverDue reads the clock once at the start, as cutoff (line 119). Only what was due by then goes out in this call, so a retry it schedules waits for a later call. It then takes one due notification at a time with claimNext, sends it with no lock held, and records the result with record. Two things keep a send from being lost:

  • Every answer becomes a SendResult. A sender that throws a RuntimeException, or returns null, counts as a temporary failure, and the loop goes on to the next notification.
  • The result is recorded in a finally. If a sender throws an Error, the attempt is still recorded as a temporary failure, and record moves the notification on before the Error reaches the worker. Once the sender returns, no notification is left marked SENDING.

claimNext is where a notification leaves the queue:

service/NotificationService.javalines 139–158 of 200
    private synchronized Claim claimNext(Instant cutoff) {        // A fresh time for each send, read under the lock, and never earlier than the cutoff.        Instant now = latest(clock.instant(), cutoff);        while (!queue.isEmpty() && !queue.peek().dueAt().isAfter(cutoff)) {            Notification notification = queue.peek().notification();            // Work out every time first, so nothing can throw once the queue has changed.            Instant allowed = notification.allowedAt(now);            int attempt = notification.attemptsOnChannel() + 1;            RetryPolicy policy = retryPolicies.get(notification.channel());            Instant retryAt = attempt < policy.maxAttempts() ? now.plus(policy.waitAfter(attempt)) : null;            queue.poll();            if (allowed.isAfter(now)) {                // Quiet hours: wait for them to end, without using an attempt.                schedule(notification, allowed);            } else {                return new Claim(notification, notification.startAttempt(), attempt, now, retryAt);            }        }        return null;    }

It reads the time again for each send (line 141), under the lock, so attempts are stamped in the order they are claimed, and never earlier than the call's cutoff. A first send that takes two minutes cannot carry the next one past 22:00 with a stale time. Then it works out everything: the time this notification is allowed to go out, the attempt number, and when a retry would be due (lines 145 to 148). All of that can throw, for example on a clock near the end of time. Only after those succeed does it take the entry off the queue (line 149). A throw therefore leaves the queue as it was.

Then it checks quiet hours (line 150). allowedAt returns the time unchanged for an urgent notification, and asks QuietHours.nextAllowed for a normal one. If that time is later than now, the notification goes back in the queue at that time, without using an attempt. Otherwise startAttempt marks it SENDING and builds the Delivery.

Decision

Where are quiet hours checked?

In submit, when the first send time is set

It is one check. But a retry five minutes after 21:58 lands at 22:03, inside quiet hours.

Wherever a send time is set: submit, each retry and each fallback

Every planned time respects quiet hours. But the rule now lives in three places. A worker that runs late can still send at night, because a notification due at 21:59 can be picked up at 22:10.

Once, in claimNext, just before a sendOur pick

The check sits next to the only place a send can start, so first tries, retries, fallbacks and late workers are all covered by one line. The cost is that a queued time is a "not before" time, not the exact time of the send. A notification due at 22:05 is moved to 07:00 only when a worker reaches it.

When a send fails

record decides what happens after each send:

service/NotificationService.javalines 160–173 of 200
    private synchronized void record(Claim claim, SendResult result, Instant cutoff) {        Notification notification = claim.notification();        notification.recordAttempt(new Attempt(claim.delivery().channel(), claim.attempt(), claim.startedAt(), result));        if (result == SendResult.DELIVERED) {            notification.finish(Status.SENT);        } else if (result == SendResult.TEMPORARY_FAILURE && claim.retryAt() != null) {            schedule(notification, claim.retryAt());        } else if (notification.moveToNextChannel()) {            // Due at the cutoff, so this call tries the fallback after a fresh quiet-hours check.            schedule(notification, cutoff);        } else {            notification.finish(Status.FAILED);        }    }

The attempt goes into the notification's history first. Then there are four cases. A delivery ends it as SENT. A temporary failure with attempts left goes back in the queue at retryAt, which claimNext worked out before the send. Anything else, a permanent failure or a channel's last attempt, moves to the user's next channel. It is due at the call's cutoff, so the same call picks it up and checks quiet hours again before sending it. If there is no next channel, the notification is FAILED.

The wait between attempts comes from the channel's RetryPolicy. It is the same doubling wait as ExponentialBackoff on the Pub-Sub page: the first wait, doubled after each failure, never more than the cap. Each channel gets its own policy, because an SMS gateway and an email API fail in different ways. The demo tries push three times with waits of 5 and then 10 minutes, and email three times starting at 1 minute.

Three notifications, one night
Order 78 is a normal notification for asha. Push fails at 21:50 and 21:55, and the solid amber arrows are the waits of 5 and 10 minutes. The retry is due at 22:05, inside asha's quiet hours, so claimNext moves it to 07:00 without using an attempt. At 07:00 push fails a third time, and email delivers it at once. The login code is urgent, so it ignores quiet hours: push fails at 23:00, 23:05 and 23:15, and email delivers it at 23:15. Ravi's refund gets a permanent failure on SMS and then on email at 23:00, so it is FAILED, with both attempts kept.Order 78 is a normal notification for asha. Push fails at 21:50 and 21:55, and the solid amber arrows are the waits of 5 and 10 minutes. The retry is due at 22:05, inside asha's quiet hours, so claimNext moves it to 07:00 without using an attempt. At 07:00 push fails a third time, and email delivers it at once. The login code is urgent, so it ignores quiet hours: push fails at 23:00, 23:05 and 23:15, and email delivers it at 23:15. Ravi's refund gets a permanent failure on SMS and then on email at 23:00, so it is FAILED, with both attempts kept.
Retries wait, quiet hours move them, and a fallback goes out at once. Order 78 is a normal notification for asha. Push fails at 21:50 and 21:55, and the solid amber arrows are the waits of 5 and 10 minutes. The retry is due at 22:05, inside asha's quiet hours, so claimNext moves it to 07:00 without using an attempt. At 07:00 push fails a third time, and email delivers it at once. The login code is urgent, so it ignores quiet hours: push fails at 23:00, 23:05 and 23:15, and email delivers it at 23:15. Ravi's refund gets a permanent failure on SMS and then on email at 23:00, so it is FAILED, with both attempts kept.
Decision

What does a failed send lead to?

Every failure is retried until maxAttempts

It is one rule. But retrying a phone number that does not exist wastes every attempt and delays the fallback by every wait.

The sender says temporary or permanent; only temporary is retriedOur pick

A dead address moves to the next channel at once, and a provider that is down gets its retries. The cost is that each sender must sort its provider's errors into the two kinds. When it cannot tell, it throws or answers temporary, which costs a few retries but never skips a channel that might have worked.

A notification that fails on every channel is not deleted. It stays in the service with its status and every attempt, and failures() lists those notifications, oldest first. This plays the part of a dead-letter queue. Pub-Sub moves such a message to a dead-letter topic, an ordinary topic that a support tool can read. Here a failed notification already sits in the service with its history, so a status and a list are enough.

Many callers, many workers

One lock, the service's own, guards all the shared state: the two maps, the queue, the id and sequence counters, and every Notification. Six methods take it, and each holds it only for a few map and queue operations:

  • findByKey and insert, in submit.
  • claimNext and record, around each send.
  • report and failures, which copy what they return.

The lock is never held while a sender or the settings service runs. A provider that takes 30 seconds to answer holds up only the worker that called it, and that worker reads the time again before its next send. The clock is the one outside object read under the lock, so it must be a plain local read such as Clock.systemUTC(), never a call over the network. Other workers keep claiming and sending, and callers keep submitting. A notification is in the queue at most once, and claimNext takes it off under the lock, so two workers cannot both send the same attempt.

The project includes a check, demo/RaceCheck.java. Eight callers submit the same 2,000 events at the same moment, as if each event were retried seven times, while four workers send:

$ java demo.RaceCheck
submit calls:          16000
notifications created: 2000
messages sent:         2000
events sent twice:     0
notifications SENT:    2000

We also ran it in a scratch copy where insert skips its second key check. Every run we tried sent dozens of events twice. With the lock removed from insert or from claimNext instead, the shared maps and queue broke, and each run we tried crashed. The numbers change from run to run and from machine to machine.

Decision

Where do the locks go?

One lock around all of submit and deliverDue

It is the simplest code to reason about. But every caller waits for the settings service and every provider, so one slow provider stops every caller and every worker.

A ConcurrentHashMap for the keys, and no lock

Each map operation is safe. But a submit is a check, a read of the settings and an insert, and a worker's claim is a peek and a poll. The map cannot make those steps one step, so the races in the figure above come back.

One lock for the bookkeeping, taken twice in submit and twice per send, never held during a send or a settings callOur pick

Each step that reads and changes shared state is atomic, and the slow calls happen between steps. The cost is the second key check in insert, and a rule to keep: no sender and no settings call may run under the lock. The clock is the one outside object read under the lock, so it must be a plain local read such as Clock.systemUTC(), never a call over the network.

The final design

NotificationService is the core. It owns the keys, the queue and every Notification, and one lock guards them. It reaches providers only through ChannelSender, the settings only through PreferenceStore, and the time only through a Clock. Each Notification keeps a copy of the user's settings and moves along their channels. Quiet hours are checked in one place, claimNext, and no lock is held during a send.

The design we built
This figure shows the classes from the class diagram with names only. Amber badges match the rows of the table below. Channel carries 1, Notification carries 2, and UserPreferences carries 3. NotificationRequest carries 4. NotificationService carries 5, 6 and 8, and SendResult carries 7. A purple tag marks ChannelSender as a Strategy.This figure shows the classes from the class diagram with names only. Amber badges match the rows of the table below. Channel carries 1, Notification carries 2, and UserPreferences carries 3. NotificationRequest carries 4. NotificationService carries 5, 6 and 8, and SendResult carries 7. A purple tag marks ChannelSender as a Strategy.
Each decision lands on one class. The channel senders are a Strategy. This figure shows the classes from the class diagram with names only. Amber badges match the rows of the table below. Channel carries 1, Notification carries 2, and UserPreferences carries 3. NotificationRequest carries 4. NotificationService carries 5, 6 and 8, and SendResult carries 7. A purple tag marks ChannelSender as a Strategy.
S.No.The questionWhat we choseWhy
1Should each channel be a subclass of Notification?One Notification; a Channel value and a ChannelSender per channelA fallback changes a value, not a class
2Every channel at once, or one at a time?The user's first channel; the next one only when it failsOne message per notification, and a fallback when a channel is down
3When are the preferences read?Once, in submit; the notification keeps a copyOne fixed list of channels for a notification's whole life
4What happens when a key comes back?Return the first id for the same request; refuse a different oneRetries are safe, and a reused key fails loudly
5Does submit send, or does a worker?submit queues; a worker calls deliverDueWaits become due times, not sleeping threads
6Where are quiet hours checked?Once, in claimNext, just before a sendOne line covers retries, fallbacks and late workers
7What does a failed send lead to?The sender says temporary or permanent; only temporary is retriedA dead address falls back at once
8Where do the locks go?One lock for the bookkeeping, taken twice in submit and twice per send, never held during a send or a settings callSlow providers never block other callers or workers

Here is order 78 from the demo, from the orders service to asha's inbox:

  1. The orders service calls submit. findByKey finds no key, PreferenceStore.find returns push then email, and insert takes the lock, checks the key again and queues N-2 for 21:50.
  2. At 21:50 a worker's deliverDue calls claimNext, which takes the lock, works out a retry time of 21:55, and returns a claim for push attempt 1.
  3. With no lock held, the push ChannelSender answers TEMPORARY_FAILURE. record takes the lock and queues N-2 for 21:55. Attempt 2 fails the same way and queues it for 22:05.
  4. At 22:05 claimNext finds asha in quiet hours and queues N-2 for 07:00, using no attempt.
  5. At 07:00 push attempt 3 fails. It was the last, so record calls moveToNextChannel and queues email at once. The same deliverDue call sends it, and record marks N-2 SENT.

If email had failed too, record would have found no next channel and marked N-2 FAILED, and failures() would list it with every attempt. If the orders service had called submit again at any point, findByKey would have returned N-2 without reading the settings.

The complete code

Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.

serviceNotificationService.java
package service; import java.time.Clock;import java.time.Instant;import java.util.ArrayList;import java.util.Comparator;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;import java.util.PriorityQueue; import channel.Channel;import channel.ChannelSender;import channel.Delivery;import channel.SendResult;import exception.NoSuchUserException;import preference.PreferenceStore;import preference.UserPreferences;import report.Attempt;import report.NotificationReport;import report.Status;import request.NotificationRequest;import retry.RetryPolicy; /** * Sends notification requests through each user's channels and reports every * attempt. One lock guards the bookkeeping: no sender or preference call runs * under it, and the clock read under it must be local, like Clock.systemUTC(). */public class NotificationService {    private record Scheduled(Instant dueAt, long sequence, Notification notification) {    }     /** One attempt taken off the queue. retryAt is null on the channel's last attempt. */    private record Claim(Notification notification, Delivery delivery, int attempt, Instant startedAt,                         Instant retryAt) {    }     private static final Comparator<Scheduled> EARLIEST_FIRST =            Comparator.comparing(Scheduled::dueAt).thenComparingLong(Scheduled::sequence);     private final Map<Channel, ChannelSender> senders;    private final Map<Channel, RetryPolicy> retryPolicies;    private final PreferenceStore preferences;    private final Clock clock;     // Guarded by this object's lock.    private final Map<String, Notification> byKey = new HashMap<>();    private final Map<String, Notification> byId = new LinkedHashMap<>();    private final PriorityQueue<Scheduled> queue = new PriorityQueue<>(EARLIEST_FIRST);    private long nextId = 1;    private long nextSequence = 1;     public NotificationService(Map<Channel, ChannelSender> senders, Map<Channel, RetryPolicy> retryPolicies,                               PreferenceStore preferences, Clock clock) {        this.senders = Map.copyOf(senders);        this.retryPolicies = Map.copyOf(retryPolicies);        if (this.senders.isEmpty() || !this.senders.keySet().equals(this.retryPolicies.keySet())) {            throw new IllegalArgumentException("every channel needs exactly one sender and one retry policy");        }        this.preferences = Objects.requireNonNull(preferences, "preferences");        this.clock = Objects.requireNonNull(clock, "clock");    }     /**     * Records a notification and returns its id. The same request with the     * same key returns the first id and sends nothing new.     */    public String submit(NotificationRequest request) {        Objects.requireNonNull(request, "request");        Notification existing = findByKey(request);        if (existing != null) {            return existing.id();        }        UserPreferences user = preferences.find(request.userId())                .orElseThrow(() -> new NoSuchUserException(request.userId()));        for (Channel channel : user.channels()) {            if (!senders.containsKey(channel)) {                throw new IllegalStateException("no sender for " + channel);            }        }        return insert(request, user);    }     private synchronized Notification findByKey(NotificationRequest request) {        Notification existing = byKey.get(request.idempotencyKey());        if (existing != null && !existing.request().equals(request)) {            throw new IllegalStateException("key " + request.idempotencyKey() + " was used for a different request");        }        return existing;    }     private synchronized String insert(NotificationRequest request, UserPreferences user) {        // Another thread may have inserted this key while we read the preferences.        Notification existing = findByKey(request);        if (existing != null) {            return existing.id();        }        Instant now = clock.instant();        Notification notification = new Notification("N-" + nextId, request, user);        nextId++;        byKey.put(request.idempotencyKey(), notification);        byId.put(notification.id(), notification);        if (notification.status() == Status.PENDING) {            schedule(notification, now);        }        return notification.id();    }     /**     * Sends every attempt that was due when the call started, and returns how     * many attempts it made. Several workers may call it at once. A retry it     * schedules waits for a later call, and a fallback is tried in this one.     */    public int deliverDue() {        Instant cutoff = clock.instant();        int sends = 0;        Claim claim = claimNext(cutoff);        while (claim != null) {            // A throw, an Error or a null answer counts as a temporary failure.            SendResult result = SendResult.TEMPORARY_FAILURE;            try {                ChannelSender sender = senders.get(claim.delivery().channel());                result = Objects.requireNonNullElse(sender.send(claim.delivery()), SendResult.TEMPORARY_FAILURE);            } catch (RuntimeException e) {                // Treated like a timeout: the result stays TEMPORARY_FAILURE and the loop goes on.            } finally {                record(claim, result, cutoff);            }            sends++;            claim = claimNext(cutoff);        }        return sends;    }     private synchronized Claim claimNext(Instant cutoff) {        // A fresh time for each send, read under the lock, and never earlier than the cutoff.        Instant now = latest(clock.instant(), cutoff);        while (!queue.isEmpty() && !queue.peek().dueAt().isAfter(cutoff)) {            Notification notification = queue.peek().notification();            // Work out every time first, so nothing can throw once the queue has changed.            Instant allowed = notification.allowedAt(now);            int attempt = notification.attemptsOnChannel() + 1;            RetryPolicy policy = retryPolicies.get(notification.channel());            Instant retryAt = attempt < policy.maxAttempts() ? now.plus(policy.waitAfter(attempt)) : null;            queue.poll();            if (allowed.isAfter(now)) {                // Quiet hours: wait for them to end, without using an attempt.                schedule(notification, allowed);            } else {                return new Claim(notification, notification.startAttempt(), attempt, now, retryAt);            }        }        return null;    }     private synchronized void record(Claim claim, SendResult result, Instant cutoff) {        Notification notification = claim.notification();        notification.recordAttempt(new Attempt(claim.delivery().channel(), claim.attempt(), claim.startedAt(), result));        if (result == SendResult.DELIVERED) {            notification.finish(Status.SENT);        } else if (result == SendResult.TEMPORARY_FAILURE && claim.retryAt() != null) {            schedule(notification, claim.retryAt());        } else if (notification.moveToNextChannel()) {            // Due at the cutoff, so this call tries the fallback after a fresh quiet-hours check.            schedule(notification, cutoff);        } else {            notification.finish(Status.FAILED);        }    }     private static Instant latest(Instant first, Instant second) {        return first.isAfter(second) ? first : second;    }     private void schedule(Notification notification, Instant dueAt) {        notification.waitForNextAttempt();        queue.add(new Scheduled(dueAt, nextSequence++, notification));    }     public synchronized Optional<NotificationReport> report(String id) {        Objects.requireNonNull(id, "id");        Notification notification = byId.get(id);        return notification == null ? Optional.empty() : Optional.of(notification.report());    }     /** Every notification that could not be delivered on any channel, oldest first. */    public synchronized List<NotificationReport> failures() {        List<NotificationReport> failed = new ArrayList<>();        for (Notification notification : byId.values()) {            if (notification.status() == Status.FAILED) {                failed.add(notification.report());            }        }        return failed;    }}
Click a class name in the code to open its fileJava · 200 lines · 859 in the project

demo/Main.java runs one night for three users, with a clock the demo moves by hand and a worker that runs every minute. Asha accepts push, then email, with quiet hours from 22:00 to 07:00. Ravi accepts SMS, then email, and both his addresses are dead. Meera accepts no channel. The push provider goes down at 21:45:

$ java demo.Main
21:30 The orders service asks for a notification, times out, and asks again:
  first call: N-1, retried call: N-1
  21:30  PUSH  asha-phone             Order 77 shipped     DELIVERED
21:45 The push provider goes down. Order 78 ships at 21:50:
  21:50  PUSH  asha-phone             Order 78 shipped     TEMPORARY_FAILURE
  21:55  PUSH  asha-phone             Order 78 shipped     TEMPORARY_FAILURE
23:00 Asha asks for a login code. Ravi gets a refund. Meera gets an order update:
  23:00  PUSH  asha-phone             Login code 4821      TEMPORARY_FAILURE
  23:00  SMS   +91 00000 00000        Refund issued        PERMANENT_FAILURE
  23:00  EMAIL ravi@old-job.example   Refund issued        PERMANENT_FAILURE
  23:05  PUSH  asha-phone             Login code 4821      TEMPORARY_FAILURE
  23:15  PUSH  asha-phone             Login code 4821      TEMPORARY_FAILURE
  23:15  EMAIL asha@example.com       Login code 4821      DELIVERED
  07:00  PUSH  asha-phone             Order 78 shipped     TEMPORARY_FAILURE
  07:00  EMAIL asha@example.com       Order 78 shipped     DELIVERED
07:05 A bug reuses a key for a different message:
  refused: key order-77-shipped was used for a different request
Meera: OPTED_OUT
Could not deliver:
  N-4 to ravi, "Refund issued"
    SMS attempt 1: PERMANENT_FAILURE
    EMAIL attempt 1: PERMANENT_FAILURE

Notice three things in the output. The retried call for order 77 gets N-1 again, and order 77 is sent once. Order 78's push fails at 21:50 and 21:55, nothing is sent at 22:05, and email delivers it at 07:00, while the urgent login code reaches email at 23:15, inside quiet hours. And ravi's refund is the only failure, with both its attempts kept, while meera's notification is OPTED_OUT and not counted as a failure.

Follow-up questions

After the core design, the interviewer adds a requirement to see how the design bends. For each one, say which class changes and which do not.

The interviewer asksWhat changesWhat does not
"Send one digest a day instead of ten emails."A digest step groups PENDING notifications per user before claimNext hands them out, and one Delivery carries many titles.ChannelSender, retries and the keys.
"Send this at 9 am tomorrow."NotificationRequest gains a sendAt, and insert queues it for that time instead of now. At scale, the queue moves to a store that many workers share.claimNext, quiet hours and fallback.
"No user gets more than five a day."A per-user limiter, as on the Rate Limiter page, checked in claimNext. A limited notification is queued for later, like quiet hours.The senders and record.
"Send it in the user's language."UserPreferences gains a language. A template step turns an event and its data into the title and body, so NotificationRequest carries event data instead of text.Channels, retries, keys and locks.
"Tell us when the user opened it."Providers call back with the deliveryId, and a new status after SENT records it.Everything before the delivery.
"Respect a setting changed while it waits."claimNext reads the settings again, outside the lock, and skips channels the user turned off. Its history must then say why a channel was skipped.Keys and record.
"Forget keys after a day."Each key keeps its first-seen time, and a sweep removes old keys and finished notifications. A caller that retries after a day then sends again.The rest of the design.
"Survive a restart."The maps and the queue move to a database, and a claim becomes a row update with a lease, as in Pub-Sub. The lease also brings back a claim whose worker died or hung mid-send, which today stays SENDING.The public API and the senders.

In most rows, the change lands in claimNext, in insert or in a record, and the senders stay as they are. Persistence is the biggest change, because a claim held only in memory is lost with the process, and a database claim needs a lease so a dead worker's claim comes back.

What the interviewer looks for

Mid-level

A mid-level candidate shows a service that takes a request and sends it through an interface per channel, chosen from the user's settings. They retry a failed send and add some locking, even if one lock covers the whole send.

Senior

A senior candidate shows everything above and gives the reasons. They send on one channel with a fallback, sort failures into temporary and permanent, and record a notification that fails everywhere. They add an idempotency key and check it again under the lock, and they keep provider calls outside every lock.

Staff+

A staff candidate leads the conversation through the trade-offs without being asked. They explain why quiet hours belong at the one place a send starts, why a refused reused key is better than a silent success, and why a provider may still deliver twice without an id to drop repeats. They say what changes when the queue moves to a database.

Common mistakes

  • Sending on every channel. The user gets each message two or three times, and there is no fallback when one channel is down.
  • A subclass per channel. A notification that falls back from push to email would have to change its class.
  • Sending inside submit. The caller waits for the provider, and a retry or a quiet-hours wait holds its thread.
  • Checking the key only once. Two calls with one key can both pass the check before either inserts.
  • Calling a provider under the lock. One slow provider stops every caller and every worker.
  • Retrying every failure. A dead phone number uses up every attempt and delays the fallback.
  • Dropping a notification that fails everywhere. Nobody can find out what happened, or send it again once the cause is fixed.

Summary

  • Ask first whether a notification goes to every channel or to one. One channel at a time gives a fallback.
  • Keep channels as values in the user's settings, and put each provider behind ChannelSender.
  • submit records and queues. A worker calls deliverDue, and the caller never waits for a provider.
  • Check quiet hours once, just before a send, so retries, fallbacks and late workers all respect them.
  • Retry only temporary failures, with a wait per channel, then fall back. Keep a notification that fails everywhere, with every attempt.
  • An idempotency key makes a retried request safe. Check it again under the lock, and refuse a key reused for a different request.
  • Hold the lock only for bookkeeping, and never while calling a provider or the settings service.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.