Case study: notification service
What you will learn on this page
Section titled “What you will learn on this page”- How to keep three providers with three different libraries (one returns status codes, one throws, one returns an enum) out of your code, behind one small interface with one adapter each.
- How to turn “the order shipped” into an email, a push, and maybe a text, from templates, and why every message is rendered before the first one is sent.
- How a user’s choices (a channel turned off, no phone number) become recorded outcomes, and why some kinds of message ignore them.
- How to make a caller’s repeat harmless: one delivery per event and channel, keyed by an id the caller chooses.
- How to retry a provider that is down without a thread that sleeps, and how to test retries to the second without waiting.
- Where “exactly once” stops: why a lost reply means one email but two texts, and how the tests pin that down.
- How a change (quiet hours and rate limits) lands as two small classes and one new check before each attempt.
This page follows the order in How to approach a case study. It assumes Adapter, Observer, and Idempotency, retries, and duplicate handling. The idempotency page builds a retry loop and an idempotency key for one call to one service; this page puts them to work in a service that calls three providers for every event, and has to remember what each one did.
The request
Section titled “The request”“We send order emails straight from the order code, and texts from the payments code, with two different SMS libraries. Now we want push too. Can you build one thing that sends our notifications? People complain about getting the same message twice, and about getting nothing when the email provider has a bad day.”
Three complaints hide in the request. The sending code is spread over the product and tied to each provider. Some users get duplicates. And a provider’s outage loses messages instead of delaying them.
Clarifying questions
Section titled “Clarifying questions”Each question is here because its answer changes the design.
| Question | Answer (from the team) | What it changes |
|---|---|---|
| Which channels, and which providers? | Email, SMS, and push, one provider each for now. We have changed SMS provider twice in two years. | One interface for a channel, with one adapter per provider. Changing provider changes one class. |
| What do callers send: finished text, or “this happened”? | “This happened”: an order shipped, a payment failed. Wording is owned by the product team, not by the order code. | A caller names a kind and gives fields; the service owns the templates. |
| Does every kind go out on every channel? | No. Each kind lists its channels. Shipping is email and push; a failed payment is all three. | A kind maps channels to texts. |
| Can users turn things off? | Yes, per kind and channel: “no texts about shipping.” Some have no phone number or no app. | Preferences, checked per channel. A skipped channel is recorded, not silently dropped. |
| Is anything not optional? | Password reset codes. Users ask for those, so they go out even on a channel turned off. | A kind can be required. |
| Why do people get duplicates today? | The order code times out talking to us and tries again, and both calls send. | An idempotency key from the caller. A repeat of the same event sends nothing new. |
| What do the providers do when they fail? | Sometimes “busy, try later”, sometimes “that number is not a mobile”. The email provider can also time out after it accepted. | Two kinds of failure: retry later, or never. A retry must not send a second email. |
| How long may a message be late? | A few minutes is fine for all of these. After that, give up and record why. | A limited number of attempts with growing waits, then a final failure with the reason. |
| Must a caller wait while we retry? | No. The order code must not wait minutes because the push service is down. | The first attempt happens in the call; retries happen later, from a timer, not in the caller’s thread. |
| Do we need to know what happened to each message? | Support asks “did the customer get the shipping email?” every day. | A record per notification and channel: the outcome, the attempts, the last reason. |
| One thread or many? | One worker thread calls the service for now. | Step 1 is single-threaded and says so. |
Three answers decide the shape. “We changed SMS provider twice” makes
each provider an Adapter behind a Sender
interface. “The order code tries again” makes the caller’s id the
idempotency key of a
record. “Must not wait minutes” makes retries a schedule that something
else runs, not a loop that sleeps.
Confirmed:
- Kinds of notification, each with a template per channel, and a flag for required kinds.
- Email, SMS, and push, each through its own provider library.
- Per-user contact details, and per-user, per-kind, per-channel opt-out.
- One record per notification id and channel, and a repeat of an id sends nothing new.
- Retries of failures that may pass, with growing waits and a limit.
- A record of what happened, readable by support.
Assumed (to confirm with the team; see Assumptions):
- The caller makes the id from the event, not from the call:
order-1001-shipped, not a fresh random number per attempt. The id must be unique per event and user. - Callers check nothing about users; the service looks up addresses and preferences itself.
- The service runs as one process with its records in memory; a store that survives restarts is a later step (see Production limitations).
Out of scope: the providers’ real network protocols (the example uses fake libraries that behave like them), HTML email, translations, scheduling a message for later, and marketing campaigns to many users. Quiet hours and rate limits arrive as a change, below.
Requirements
Section titled “Requirements”Functional requirements.
- FR-1 Send by kind.
notifytakes an id, a user, a kind, and fields. It renders the kind’s template for each of its channels and sends each message to the user’s address on that channel. - FR-2 All or nothing up front. If any template needs a field that
was not given, or the kind is unknown, or a channel has no sender,
notifyfails and nothing is sent or recorded, on any channel. - FR-3 Preferences. A channel the user turned off for this kind is
skipped and recorded as
turned off, unless the kind is required. A channel the user has no address for is skipped and recorded asno address. - FR-4 Retries. A failure that may pass (busy, down, no answer) is tried again after a wait that doubles each time, up to a limit on attempts; then the delivery fails with the last reason. A failure that will never pass (a bad number) fails at once.
- FR-5 Once per event and channel. A second
notifywith an id already handled on a channel sends nothing on that channel and reportsduplicate, with what happened the first time. - FR-6 Records. For each id and channel, the service keeps the outcome, the number of attempts, the last reason, and when it last changed.
Non-functional requirements.
- NFR-1 Providers are replaceable. No code outside one adapter class knows a provider’s library. Adding or changing a provider changes no line of the notifier.
- NFR-2 The caller does not wait for retries.
notifymakes one attempt per channel and returns. Later attempts are made byrun_due, which the service calls from a timer. - NFR-3 Testable time. The time comes from an injected clock, so the tests check every wait to the second without sleeping.
- NFR-4 Not thread-safe, on purpose. One thread calls the notifier, and the documentation says so.
FR-5 is the team’s “same message twice” complaint, and FR-4 is “nothing when the provider has a bad day”. The two pull against each other: a retry is exactly how a message gets sent twice. Most of this design is about making them agree.
Use cases and acceptance criteria
Section titled “Use cases and acceptance criteria”The tests are named after these criteria. See Use cases, user stories, and acceptance criteria.
UC-1 Send a notification.
- AC-1.1 A notification goes out on every channel of its kind, and only those.
- AC-1.2 The templates are filled from the fields.
- AC-1.3 If one channel’s template needs a missing field, the whole call fails, nothing is sent or recorded, and the same id can be used again once the field is given.
- AC-1.4 An unknown kind, an empty id, or an empty user is an error.
- AC-1.5 Each channel uses the user’s own address for it.
- AC-1.6 A field value is inserted as it is, never expanded again.
UC-2 Respect the user’s choices.
- AC-2.1 A channel turned off for this kind is skipped and recorded
as
turned off; the other channels still go. - AC-2.2 A required kind goes out on a channel turned off.
- AC-2.3 A channel with no address is skipped and recorded as
no address. - AC-2.4 A user with no contact details gets nothing, and every
channel is recorded as
no address. - AC-2.5 A channel turned back on is used again.
UC-3 Talk to each provider.
- AC-3.1 Email status codes become results: 2xx is sent; 429, 503, and 504 are retry later; anything else is rejected.
- AC-3.2 SMS errors become results by the error’s own “retryable” flag.
- AC-3.3 Push results become results: an unknown device is rejected; an unavailable service is retry later.
- AC-3.4 An email carries the notification id as the provider’s deduplication key.
UC-4 A provider fails.
- AC-4.1 A failure that may pass is tried again after the wait, and not one second before.
- AC-4.2 The waits are 30 s, then 60, 120, 240, and so on, never more than 600 s.
- AC-4.3 After the last attempt, the delivery fails, and the record says why and after how many attempts.
- AC-4.4 A rejected message is not tried again.
- AC-4.5 A sender that throws is treated as “retry later”.
- AC-4.6 One channel failing does not stop the others.
UC-5 The caller repeats itself.
- AC-5.1 The same notification twice is sent once per channel; the
second call reports
duplicatewith the first outcome. - AC-5.2 A repeat while a retry is waiting sends nothing new.
- AC-5.3 An email whose provider reply was lost, and is retried, arrives once.
- AC-5.4 A text whose provider reply was lost, and is retried, arrives twice. This is a documented limit, not a goal.
UC-6 Setting up.
- AC-6.1 The notifier rejects a null sender, two senders for one channel, and a retry policy with no attempts or with bad waits.
- AC-6.2 A kind that uses a channel with no sender is an error, and then nothing is sent.
- AC-6.3 The catalog rejects malformed templates, a kind added twice, a kind with no name or no channels, and an SMS with a subject.
Invariants
Section titled “Invariants”Each invariant names the code that keeps it. See Invariants.
- INV-1 One record per id and channel. A record, once made, is
never replaced; a repeat changes nothing. Kept by
Notifier::notify, the only code that adds records, which checks for an earlier one first. - INV-2 Pending means scheduled. A delivery is
pendingexactly when one entry for it waits in the schedule,due_. Kept byNotifier::attempt, which either finishes a delivery or schedules it again, andrun_due, which removes an entry before attempting it. - INV-3 Attempts are bounded. A delivery is never attempted more
than
max_attemptstimes. Kept byattempt, which counts first and gives up at the limit. - INV-4 Final is final.
sent,failed,turned off, andno addressnever change. Kept by INV-2: only a scheduled delivery is attempted, and only a pending one is scheduled.
The random test makes 3,000 random steps, then checks INV-2 and INV-3
at the end of the run, and
compares the count of sent records on each channel with what each
fake provider actually delivered.
Entities and relationships
Section titled “Entities and relationships”The nouns from the answers: notification, event, kind, channel, provider, template, field, user, address, preference, attempt, failure, retry, record, duplicate, timer. Filtered:
- Notification is what a caller asks for: an id, a user, a kind, and
fields. A plain struct,
Notification. - Message is one rendered text for one channel and address, ready
for a provider. A plain struct,
Message. - Channel is one of three values. An
enum class Channel. - Provider has its own library, which we do not control. Each gets
an adapter,
EmailSender,SmsSender, andPushSender, behind the interfaceSender. - Kind and template are configuration: a
Kindnames its channels and has aTemplatepair for each; aCatalogholds them. - User, address, and preference become
ContactandPreferences. - Record becomes
Delivery: one per notification id and channel, with anOutcome. - Failure becomes
SendResult, with aSendStatusthat says whether to try again. - Retry, attempt, and timer become the
Notifier’s schedule,run_due, and aRetryPolicy. The time comes from aClock. - Event stays outside: it is how the caller learns that an order shipped. See Who calls notify?.
Text description of the diagram
Sender is an interface with channel and send. EmailSender, SmsSender, and PushSender implement it; each holds a pointer to its provider’s client, which it does not own. Notifier owns up to three senders, one per channel, in a map from Channel to unique_ptr of Sender. It also owns its records, a map from a key (notification id and channel) to a record, and its schedule, a multimap from a time to a key, and a RetryPolicy. It offers notify, run_due, find, and pending. Notifier reads a Catalog (add, find), a Preferences (contact, is_off), and a Clock (now), none of which it owns.
Diagram source (Mermaid)
classDiagram
class Sender {
<<interface>>
+channel() Channel*
+send(const Message&) SendResult*
}
class EmailSender {
-acme_mail Client* client_
-string from_
}
class SmsSender {
-textly Gateway* gateway_
}
class PushSender {
-pushy Api* api_
}
class Notifier {
-map~Channel, unique_ptr~Sender~~ senders_
-map~Key, Record~ records_
-multimap~TimePoint, Key~ due_
-RetryPolicy retry_
+notify(const Notification&) vector~Delivery~
+run_due() size_t
+find(id, Channel) const Delivery*
+pending() size_t
}
class Catalog {
+add(Kind)
+find(string_view) const Kind*
}
class Preferences {
+contact(user) const Contact*
+is_off(user, kind, Channel) bool
}
class Clock {
<<interface>>
+now() TimePoint*
}
Sender <|.. EmailSender
Sender <|.. SmsSender
Sender <|.. PushSender
Notifier *-- "0..3" Sender : senders_ (owns)
Notifier --> Catalog : reads
Notifier --> Preferences : reads
Notifier --> Clock : readsOwnership has two rules worth saying out loud. The notifier owns its senders, because a sender is part of how it works and nothing else should call one. It refers to the catalog, the preferences, the clock, and (through the adapters) the provider clients, which are owned by whoever builds the service, the composition root. Each of those must outlive the notifier. The demo declares them first, so they are destroyed last.
Class design
Section titled “Class design”The design below is step 1 of the example, the complete answer to FR-1 … FR-6. Quiet hours and rate limits are added in When the requirements change.
What a caller sends, and what a provider gets
Section titled “What a caller sends, and what a provider gets”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The three ways to reach a user. `enum class` keeps the names inside// the type (Channel::sms), and its values have an order (email, then// sms, then push), which is why the notifier's results come out in// that order: they are kept in std::map containers keyed by Channel.enum class Channel { email, sms, push };
// The channel's name for printing ("email"). It returns a// std::string_view, a read-only view of characters that are stored// elsewhere; here they are string literals, which live for the whole// program, so the view never dangles. constexpr lets it run at compile// time when the channel is known then.[[nodiscard]] constexpr std::string_view to_string(Channel channel) noexcept { switch (channel) { case Channel::email: return "email"; case Channel::sms: return "sms"; case Channel::push: return "push"; } return "?"; // only for a value outside the enum, which a cast could make}
// What a caller asks for: tell one user that something happened.// id is the idempotency key. It names the event, not the call: a caller// that is unsure whether its first call worked calls again with the same// id, and the user still hears about the event once per channel.struct Notification { std::string id; // "order-1234-shipped" std::string user; // "u-42" std::string kind; // "order-shipped" std::map<std::string, std::string> fields; // values for the templates // fields maps a placeholder name to its text: {"order", "1234"} fills // {order}. Every placeholder in the kind's templates needs an entry.};
// One rendered message for one channel, ready for a provider. The// notifier fills it in: the placeholders are already replaced, and `to`// is the user's address on this channel. A plain struct, copied and// moved like a value; it holds no pointers.struct Message { std::string id; // the notification's id, for providers that deduplicate Channel channel = Channel::email; std::string to; // an email address, a phone number, or a device token std::string subject; // empty for SMS std::string body;};Notification is the caller’s view: something happened to a user. A
Message is the provider’s view: a text and an address. Keeping them
apart means the caller never builds text, and a provider never sees a
kind or a field. The id travels into the Message for one reason: an
email provider can use it to drop a repeat (AC-3.4).
The comment on Notification::id carries the most important rule on
this page. The id names the event, so a caller that is unsure
whether its call worked can call again with the same id. If the caller
made a new id for every call, the service could not tell a repeat from
a second event, and FR-5 would be impossible to keep.
One interface for every provider
Section titled “One interface for every provider”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A provider's answer, reduced to the three things the notifier can do// next: stop (sent), schedule another try (retry_later), or give up// (rejected).enum class SendStatus { sent, // the provider accepted the message retry_later, // it may work later: the provider is busy, down, or did not answer rejected, // it will never work: a bad address, an unknown device};
// What send returns: the status, plus the provider's own words for// people to read. `= SendStatus::sent` gives the member a default, so a// SendResult made with no arguments is "sent" with no detail.struct SendResult { SendStatus status = SendStatus::sent; std::string detail; // the provider's reason, kept in the delivery record};
// One way to reach a user. Every provider's client library has its own// calls and its own way to fail; each Sender is an adapter that turns a// Message into that provider's call, and the provider's answer into a// SendResult. Nothing outside the adapters knows any provider's API.//// A provider's failure is a SendResult, not an exception. send may still// throw for something like std::bad_alloc; the Notifier treats any// exception as retry_later.class Sender {public: // Virtual, so that destroying an adapter through a Sender pointer (as // the notifier's std::unique_ptr<Sender> does) runs the adapter's own // destructor too. virtual ~Sender() = default; // `= 0` makes these pure virtual: Sender has no code for them, and // every adapter must write its own. channel() says which channel the // adapter serves; the notifier files each sender under that channel. [[nodiscard]] virtual Channel channel() const noexcept = 0; // Tries once to hand the message to the provider. No retrying here: // that is the notifier's job. [[nodiscard]] virtual SendResult send(const Message& message) = 0;
protected: // Protected: only an adapter can create, copy, or assign the Sender // part of itself. So code holding two Sender& cannot write a = b, // which would copy only the Sender part and none of the adapter's // own data (slicing). Sender() = default; Sender(const Sender&) = default; Sender& operator=(const Sender&) = default;};A Sender answers one question: did it go, and if not, is it worth
trying again? SendStatus has three values because the notifier needs
three different actions: stop, schedule a retry, or record a failure.
A bool would lose the difference between “the number is not a
mobile” and “the gateway is busy”, which is the difference between
giving up and trying in 30 seconds.
A failure is a value, not an exception, because it is an expected
answer: providers are busy every day. The notifier still catches
exceptions from send, so an adapter with a bug (or a std::bad_alloc)
delays a message instead of losing the whole call (AC-4.5).
The copy operations are protected, as on the
Strategy page, so a Sender& cannot be copied
by accident into a slice of itself.
The providers, and their adapters
Section titled “The providers, and their adapters”The example’s three provider libraries are fakes, written to behave
like real ones in the ways that matter here
(step-1/providers.hpp):
acme_mail::Client::submittakes anEnvelopeand returns an HTTP status code. It accepts a deduplication key: a second envelope with the same key is accepted and not delivered again.textly::Gateway::send_textreturns nothing and throwstextly::Error, which has aretryable()flag.pushy::Api::pushreturns anenum:ok,unregistered_device, orunavailable.
Each fake records what it delivered and can be told to fail its next call, including the nastiest case: failing after delivering, as a timeout does when the reply is lost.
The adapters turn those three styles into one:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each adapter refers to a provider client it does not own; the client// must outlive the adapter. Thread safety: as the client (not safe).//// `final` means no class may derive from these. `override` asks the// compiler to check that each function really replaces one in Sender.// Each stores a pointer, not a reference, to its client: a pointer// member keeps the adapter assignable, and a raw pointer says "used// here, owned elsewhere".
// Email through acme_mail. `from` is the shop's sender address, put on// every envelope; it is moved into from_ rather than copied.class EmailSender final : public Sender {public: EmailSender(acme_mail::Client& client, std::string from) : client_(&client), from_(std::move(from)) {}
[[nodiscard]] Channel channel() const noexcept override { return Channel::email; } [[nodiscard]] SendResult send(const Message& message) override;
private: acme_mail::Client* client_; std::string from_;};
// Texts through textly. `explicit`: a Gateway is never silently turned// into an SmsSender.class SmsSender final : public Sender {public: explicit SmsSender(textly::Gateway& gateway) : gateway_(&gateway) {}
[[nodiscard]] Channel channel() const noexcept override { return Channel::sms; } [[nodiscard]] SendResult send(const Message& message) override;
private: textly::Gateway* gateway_;};
// Pushes through pushy, to the device token in Message::to.class PushSender final : public Sender {public: explicit PushSender(pushy::Api& api) : api_(&api) {}
[[nodiscard]] Channel channel() const noexcept override { return Channel::push; } [[nodiscard]] SendResult send(const Message& message) override;
private: pushy::Api* api_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// acme_mail answers with an HTTP-style number. 2xx means accepted; 429// (too many requests), 503 (unavailable), and 504 (timed out) may work// later; any other code (400, a bad request) never will.SendResult EmailSender::send(const Message& message) { // The braces build an acme_mail::Envelope field by field, in the order // its members are declared: from, to, subject, text, dedupe_key. // The notification id is the dedupe key, so a retry after a lost // reply is not a second email. const int status = client_->submit({from_, message.to, message.subject, message.body, message.id}); const std::string detail = "status " + std::to_string(status); // "status 202" // `return {..., ...}` builds the SendResult from a status and a detail. if (status >= 200 && status < 300) return {SendStatus::sent, detail}; if (status == 429 || status == 503 || status == 504) return {SendStatus::retry_later, detail}; return {SendStatus::rejected, detail};}
// textly says nothing on success and throws textly::Error on failure,// with a flag for "worth trying again". Only that exception type is// caught: anything else is not a provider answer, so it goes up to the// notifier, which treats it as retry_later.SendResult SmsSender::send(const Message& message) { try { gateway_->send_text(message.to, message.body); return {SendStatus::sent, ""}; } catch (const textly::Error& error) { // ?: picks retry_later if the error is retryable, else rejected. // what() is the error's message, kept as the detail. return {error.retryable() ? SendStatus::retry_later : SendStatus::rejected, error.what()}; }}
// pushy answers with its own enum; each value maps to one SendStatus.// The subject becomes the push's title.SendResult PushSender::send(const Message& message) { switch (api_->push(message.to, message.subject, message.body)) { case pushy::Result::ok: return {SendStatus::sent, ""}; case pushy::Result::unregistered_device: return {SendStatus::rejected, "device not registered"}; case pushy::Result::unavailable: return {SendStatus::retry_later, "push service unavailable"}; } // Reached only for a value the switch does not list, such as one a // newer library version adds. Never retried: it is not understood. return {SendStatus::rejected, "unknown push result"};}Each adapter is a short translation, and each translation holds a decision the notifier should not have to know:
- Email decides which status codes are worth retrying. 429 (too
many requests), 503 (unavailable), and 504 (timeout) may pass; 400
will not. It also passes
message.idas the deduplication key, which is why an email retried after a lost reply arrives once (AC-5.3). - SMS catches the library’s own exception type and nothing else. Any other exception is not a provider answer, so it goes up to the notifier, which treats it as “retry later”.
- Push maps an enum to an enum. The final
returnafter theswitchis for a value outside the enum, which a newer library version might add.
An adapter refers to a client it does not own (client_ is a pointer,
so the adapter stays assignable and the “not owned” is visible in the
type). See Adapter: ownership and lifetime.
Templates
Section titled “Templates”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Text with {field} placeholders: "Your order {order} has shipped."// A field name is letters, digits, and '_'. There is no way to write a// literal brace; no message needs one yet.class Template {public: // Throws std::invalid_argument for a brace that does not open a // well-formed placeholder: "{name" (never closed), "name}" (a '}' on // its own), "{}" (no name), "{first name}" (a space in the name). // The text is taken by value and moved in, so a caller passing a // temporary string pays for no copy. explicit Template(std::string text);
// Every placeholder replaced by its field's value. A value is // inserted as it is and never expanded again, so a value that // contains "{code}" stays "{code}". Throws std::invalid_argument // naming the first field that has no value; then nothing is sent. // Fields the template does not use are ignored. [[nodiscard]] std::string render(const std::map<std::string, std::string>& fields) const;
[[nodiscard]] const std::string& text() const noexcept { return text_; }
private: std::string text_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Checks the whole text once, left to right. placeholder_end (a helper// above, in the file) looks at the text just after a '{' and returns the// index of the matching '}' if a name of letters, digits, and '_'// follows, or std::string::npos ("no position") if not.Template::Template(std::string text) : text_(std::move(text)) { for (std::size_t at = 0; at < text_.size(); ++at) { // A '}' met here is not closing any placeholder: closing braces // are jumped over below, so this one stands alone. if (text_[at] == '}') throw std::invalid_argument("a '}' with no '{' in: " + text_); if (text_[at] != '{') continue; // ordinary text: on to the next character const std::size_t end = placeholder_end(text_, at); if (end == std::string::npos) throw std::invalid_argument("a bad placeholder in: " + text_); at = end; // jump to the '}'; the loop's ++at then steps past it }}
// Builds the output in one pass: copy the text up to the next '{', put// the field's value in place of the placeholder, carry on after its '}'.
std::string Template::render(const std::map<std::string, std::string>& fields) const { std::string out; out.reserve(text_.size()); // room for at least the template's length, to grow less often std::size_t at = 0; // where the next piece of text to copy starts while (at < text_.size()) { const std::size_t open = text_.find('{', at); // the next placeholder, searching from at if (open == std::string::npos) { out.append(text_, at); // no placeholder left: copy the rest and stop break; } out.append(text_, at, open - at); // the plain text before the '{': open - at characters const std::size_t end = placeholder_end(text_, open); // well formed: checked when made // The name sits between the braces: it starts just after '{' and is // end - open - 1 characters long, which leaves out both braces. const std::string name = text_.substr(open + 1, end - open - 1); const auto found = fields.find(name); // an iterator: the entry, or fields.end() if (found == fields.end()) throw std::invalid_argument("no value for field '" + name + "'"); out += found->second; // inserted as it is, never expanded again at = end + 1; // continue in the template just after the '}', not in the value } return out;}How this code works: Template: checking and rendering
Both functions walk the text with an index, at, and both rely on the
helper placeholder_end(text, open): given the index of a {, it
returns the index of the } that closes a well-formed name, or
std::string::npos (the standard “no position”) if there is none.
The constructor looks at every character once.
- A
}on its own is an error. The only way to reach a}that does close a placeholder is from its{, and the loop jumps over those. - Any character other than
{is plain text:continuemoves on. - At a
{,placeholder_endmust find a name and a}, or the constructor throws. If it does,at = endputs the loop on the}, and the loop’s own++atsteps past it.
So a Template that exists has only well-formed placeholders, which is
why render can call placeholder_end without checking for npos.
render copies pieces of the text into out. A worked example,
with the email subject Your order {order} has shipped (30 characters)
and the field order set to 1001:
| Turn | at |
open (next {) |
What is appended | at afterwards |
|---|---|---|---|---|
| 1 | 0 | 11 | Your order (11 characters), then the value 1001 |
18 |
| 2 | 18 | npos |
the rest, has shipped; then break |
(loop left) |
On turn 1, placeholder_end returns 17, the index of the }. The name
starts at open + 1 = 12 and is end - open - 1 = 5 characters long:
order. The result is Your order 1001 has shipped.
The key line is at = end + 1: the scan continues in the template,
after the }. The value that was just appended is never scanned, so a
value of {tracking} stays as those ten characters.
A template is checked once, when it is made: a stray }, an empty
{}, or a name with a space is a mistake in configuration, and the
service should refuse to start rather than send broken text later
(AC-6.3). That leaves render with one way to fail, a missing field,
and it names the field in the error.
The value is appended as it is and the scan continues after the
placeholder, so a value is never read as a template. That matters
because values come from users: a customer whose name is {tracking}
gets Hi {tracking}, not someone else’s tracking link (AC-1.6).
Kinds and the catalog
Section titled “Kinds and the catalog”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One kind of notification: the channels it goes out on, and the text// for each. A required kind (a password reset code) is sent even on a// channel the user turned off, because it is not optional for them.struct Kind { // The subject and body for one channel, each a checked Template. struct Text { Template subject; // empty for SMS Template body; }; std::string name; bool required = false; // One entry per channel the kind goes out on, kept in Channel order. std::map<Channel, Text> channels;};
// All kinds, by name. Filled once at start-up, then only read.class Catalog {public: // Throws std::invalid_argument for an empty name, a name already // added, a kind with no channels, or an SMS with a subject. void add(Kind kind);
// nullptr for an unknown name. The pointer is valid while the // catalog lives (adding other kinds does not move this one). [[nodiscard]] const Kind* find(std::string_view name) const;
private: // std::less<> (a "transparent" comparison) lets find look up a // std::string_view key directly, without building a std::string. std::map<std::string, Kind, std::less<>> kinds_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Builds the shop's catalog and returns it by value (the Catalog is// moved out, or built in place, not copied). `inline` lets this// function be defined in a header that several files include.//// Each add takes a Kind written as nested braces, in the order of Kind's// members: {name, required, channels}. channels is a map, so it is a// list of {channel, {subject, body}} pairs. Each Template is checked as// it is made, and add checks the kind, so a typo here throws// std::invalid_argument when the program starts, not when a message is// sent.inline Catalog shop_catalog() { Catalog catalog; catalog.add({"order-shipped", false, // not required: the user may turn a channel off {{Channel::email, {Template("Your order {order} has shipped"), Template("Hi {name}, order {order} is on its way. Track it at {tracking}.")}}, {Channel::push, {Template("Order shipped"), Template("{order} is on its way")}}}}); catalog.add({"payment-failed", false, {{Channel::email, {Template("We could not take payment for {order}"), Template("Hi {name}, your card was declined for order {order}. Update it to keep the order.")}}, // An SMS has no subject, so its subject is an empty Template. {Channel::sms, {Template(""), Template("Payment for {order} failed. Update your card in the app.")}}, {Channel::push, {Template("Payment failed"), Template("Update your card for {order}")}}}}); catalog.add({"password-reset", true, // required: the user asked for it, and a reset cannot wait {{Channel::email, {Template("Your reset code"), Template("Your code is {code}. It expires in 10 minutes.")}}, {Channel::sms, {Template(""), Template("Reset code {code}, valid for 10 minutes.")}}}}); return catalog;}Catalog::find returns a pointer, nullptr for an unknown kind. The
pointer stays valid as other kinds are added, because a std::map never
moves its elements; the comment says so, since a std::vector of kinds
would not keep that promise. The map uses std::less<>, so find can
take a std::string_view without building a std::string.
Preferences
Section titled “Preferences”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// How to reach a user. An empty string means the user has no address on// that channel (no phone number given, no app installed).struct Contact { std::string email; std::string phone; std::string device; // the push token of the user's app};
// The user's address on one channel, as a reference into `contact`// (nothing is copied). The reference is only as good as the Contact it// points into, so use it while that Contact is still there.[[nodiscard]] inline const std::string& address(const Contact& contact, Channel channel) noexcept { switch (channel) { case Channel::email: return contact.email; case Channel::sms: return contact.phone; case Channel::push: return contact.device; } // Every path must return a reference to something that lives on, so // the fallback is a real member, never a temporary string. return contact.email; // not reached for a valid Channel}
// Each user's addresses and the channels they turned off, per kind.// In memory here; in a service, a table that the settings page writes.// Thread safety: not safe.class Preferences {public: // Adds or replaces the user's details. contacts_[user] makes an empty // entry if there is none yet; the new details are then moved in. void set_contact(const std::string& user, Contact contact) { contacts_[user] = std::move(contact); }
// A user may turn off one kind on one channel ("no SMS for order-shipped"). // An opt-out is one (user, kind, channel) entry in a set. emplace // builds the tuple in place; turning off twice changes nothing. void turn_off(const std::string& user, const std::string& kind, Channel channel) { off_.emplace(user, kind, channel); } // Removes the entry; erase of an entry that is not there does nothing. void turn_on(const std::string& user, const std::string& kind, Channel channel) { off_.erase(std::make_tuple(user, kind, channel)); }
// nullptr for a user with no contact details. Read it at once: a later // set_contact for the same user changes what it points to. [[nodiscard]] const Contact* contact(const std::string& user) const { const auto found = contacts_.find(user); // found->second is the Contact stored in the map; & gives its address. return found == contacts_.end() ? nullptr : &found->second; } // True if this user turned this kind off on this channel. The // notifier asks only for kinds that are not required. [[nodiscard]] bool is_off(const std::string& user, const std::string& kind, Channel channel) const { return off_.contains(std::make_tuple(user, kind, channel)); }
private: std::map<std::string, Contact> contacts_; // Every opt-out as a (user, kind, channel) tuple. A std::tuple groups // several values into one, and compares them in order, so it can be // the element of a std::set. std::set<std::tuple<std::string, std::string, Channel>> off_;};An empty address means “none”, which keeps Contact a plain struct.
contact returns a pointer into the map. The pointer stays valid,
because nothing erases a contact and a std::map never moves its
elements, but its comment warns that a later set_contact for the same
user changes the value it points to. The notifier reads it at once, in
notify, and keeps the address it needs in the Message.
The notifier
Section titled “The notifier”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// How hard to try. The defaults give at most four attempts, with waits// of 30 s, 60 s, and 120 s between them. std::chrono::seconds is a// number of seconds with the unit in its type, so a wait cannot be// mixed up with a count or with minutes by accident.struct RetryPolicy { int max_attempts = 4; // including the first std::chrono::seconds first_delay{30}; std::chrono::seconds max_delay{600};};
// The wait after attempt number `attempt` failed (1 for the first):// first_delay, doubled for each attempt before it, never above max_delay.// With the defaults: 30 s after attempt 1, 60 s after 2, 120 s after 3.// If more attempts were allowed it would go on 240 s, 480 s, then 600 s// (the cap) after attempt 6 and every later one.[[nodiscard]] std::chrono::seconds backoff(const RetryPolicy& policy, int attempt);
// Where one delivery stands. pending is the only one that changes// later; the others are final. duplicate is only ever reported to the// caller, never stored (the first record keeps its own outcome).enum class Outcome { pending, // waiting to be tried again sent, // the provider accepted it failed, // rejected, or still failing after the last attempt turned_off, // the user turned this kind off on this channel no_address, // the user has no address on this channel duplicate, // this notification id was already handled on this channel};
[[nodiscard]] std::string_view to_string(Outcome outcome) noexcept;
// What happened to one notification on one channel.struct Delivery { std::string id; // the notification's id Channel channel = Channel::email; Outcome outcome = Outcome::pending; int attempts = 0; // calls to the provider so far std::string detail; // the last provider reason, if any TimePoint updated; // when the outcome last changed};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Turns a notification into one message per channel, sends each through// that channel's Sender, and retries the ones that may work later.// It owns its senders. The catalog, the preferences, and the clock are// not owned and must outlive the notifier.//// Each (notification id, channel) is handled once: a repeat of an id is// a duplicate, so a caller may safely call again after a crash or a// timeout. Retries are not made by sleeping: a failed attempt is// scheduled, and run_due makes the attempts whose time has come. The// service calls run_due from a timer.//// Thread safety: not safe. One thread calls notify and run_due.class Notifier {public: // Throws std::invalid_argument for a null sender, two senders for one // channel, or a retry policy with no attempts, a first delay that is // not positive, or a max delay below the first. Notifier(const Catalog& catalog, const Preferences& preferences, const Clock& clock, RetryPolicy retry, std::vector<std::unique_ptr<Sender>> senders);
// Decides, for each channel of the kind, whether to send, renders the // message, and makes the first attempt now. Returns one Delivery per // channel of the kind, in channel order. // Throws std::invalid_argument for an empty id or user, an unknown // kind, or a template field missing from n.fields. Then nothing has // been sent or recorded, on any channel. std::vector<Delivery> notify(const Notification& n);
// Makes every attempt that is due now. Returns how many it made. std::size_t run_due();
// The record for one notification on one channel; nullptr if none. [[nodiscard]] const Delivery* find(const std::string& id, Channel channel) const; [[nodiscard]] std::size_t pending() const noexcept { return due_.size(); }
private: // One delivery's name: (notification id, channel). std::pair compares // the id first, then the channel, so it can be a std::map key. using Key = std::pair<std::string, Channel>; // Everything kept for one delivery: what to report, and what to send. struct Record { Delivery delivery; Message message; // kept until the outcome is final };
void attempt(Record& record); // The sender for a channel. Throws std::invalid_argument if there is // none, which notify uses as its "every channel has a sender" check. [[nodiscard]] Sender& sender_for(Channel channel) const;
// Pointers, not references, to what is not owned: shared, read only // (const), and required to outlive the notifier. const Catalog* catalog_; const Preferences* preferences_; const Clock* clock_; RetryPolicy retry_; // The senders, owned: std::unique_ptr deletes each adapter when the // notifier is destroyed. One per channel, looked up by channel. std::map<Channel, std::unique_ptr<Sender>> senders_; std::map<Key, Record> records_; // every delivery ever decided std::multimap<TimePoint, Key> due_; // pending deliveries, by when to try again // due_ is a multimap: sorted by time, so begin() is always the // earliest, and it may hold several keys for the same time. A // std::map would allow only one delivery per moment.};The notifier keeps two structures:
records_, every delivery ever decided, by (id, channel). This is the idempotency store and support’s answer to “did it go?”.due_, the schedule: for each pending delivery, when to try again. Astd::multimapkeeps it sorted by time, so the next one due is always atbegin(), and two retries due at the same second can both be there.
The Record keeps the Message until the outcome is final, so a retry
sends exactly the text the first attempt sent, even if the catalog or
the user’s address has changed since.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Two loops: the first decides and renders every channel and may throw;// the second stores and sends, and does not throw for anything in the// caller's input. The result has one Delivery per channel of the kind.std::vector<Delivery> Notifier::notify(const Notification& n) { if (n.id.empty() || n.user.empty()) throw std::invalid_argument("a notification needs an id and a user"); const Kind* kind = catalog_->find(n.kind); if (kind == nullptr) throw std::invalid_argument("unknown kind: " + n.kind); const Contact* contact = preferences_->contact(n.user); // nullptr: no details at all const TimePoint now = clock_->now(); // one time for every record made by this call
// Decide and render every channel first. A missing field or sender // then fails the whole call before anything is sent or recorded. std::vector<Record> decided; // local: thrown away untouched if anything below throws // Each map entry is unpacked into `channel` and its `text` (subject // and body templates), in Channel order: email, sms, push. for (const auto& [channel, text] : kind->channels) { // A new record, filled in member order: pending, no attempts yet, // no detail, made now, and an empty message for the moment. Record record{Delivery{n.id, channel, Outcome::pending, 0, "", now}, Message{}}; // `to` is left empty for now; it is filled in only if the message // will really be sent. render throws for a missing field. Message message{n.id, channel, "", text.subject.render(n.fields), text.body.render(n.fields)}; // Called only for its check; static_cast<void> drops the unused // [[nodiscard]] result on purpose. static_cast<void>(sender_for(channel)); // throws if there is none // The checks, in order; the first that matches decides. The // `if (init; condition)` form declares `earlier` for this if-else // chain only. In the third check, || stops at the first true part, // so *contact is read only when contact is not null. if (const auto earlier = records_.find(Key{n.id, channel}); earlier != records_.end()) { record.delivery.outcome = Outcome::duplicate; // "already sent", "already pending": what the first call led to. record.delivery.detail = "already " + std::string(to_string(earlier->second.delivery.outcome)); } else if (!kind->required && preferences_->is_off(n.user, n.kind, channel)) { record.delivery.outcome = Outcome::turned_off; } else if (contact == nullptr || address(*contact, channel).empty()) { record.delivery.outcome = Outcome::no_address; } else { // Copy the address now, so a later change to the user's // details does not change a retry. The outcome stays pending. message.to = address(*contact, channel); record.message = std::move(message); // moved, not copied: message is not used again } decided.push_back(std::move(record)); }
// Then act. A duplicate is reported, not recorded: the first record stays. std::vector<Delivery> result; // Record& (not a copy): each record is moved out of `decided` below. for (Record& record : decided) { if (record.delivery.outcome == Outcome::duplicate) { result.push_back(std::move(record.delivery)); continue; } const Key key{n.id, record.delivery.channel}; // emplace returns a pair: an iterator to the entry, and whether it // was added. .first->second is the Record now inside records_. The // first loop found no record for this key, so it is always added. // A std::map never moves its entries, so `stored` stays valid. Record& stored = records_.emplace(key, std::move(record)).first->second; if (stored.delivery.outcome == Outcome::pending) attempt(stored); // the first try, now result.push_back(stored.delivery); // a copy: the caller's answer, the record stays here } return result;}How this code works: Notifier::notify
-
Refuse a bad call at once. An empty id or user, or a kind the catalog does not know, throws before anything else happens.
contactmay benullptr; that is not an error, it just means every channel will be “no address”. -
First loop: one
Recordper channel, in a local vector. For each channel of the kind it renders the subject and body (this throws for a missing field), checks that a sender exists (this throws if not), and then picks one outcome, the first that fits:- a record for (id, channel) already exists:
duplicate, with the earlier outcome in the detail; - the kind is not required and the user turned this channel off:
turned_off; - no contact, or an empty address on this channel:
no_address; - otherwise the address is copied into the message, the message is
moved into the record, and the outcome stays
pending.
If anything throws during this loop,
decidedis a local variable and is simply destroyed.records_anddue_were only read. - a record for (id, channel) already exists:
-
Second loop: store, then try. A duplicate is moved into the result and not stored, so the first record is untouched. Any other record is moved into
records_;emplace(...).first->secondis a reference to the stored copy. Only apendingrecord gets a firstattempt. The result gets a copy of the storedDelivery, as it is after that attempt.
A worked example: the demo’s “payment failed”. Robin has all three
addresses and has turned off texts for payment-failed; no earlier
record has the id order-1002-payment.
| Channel | Earlier record? | Turned off? | Address? | Decided | After the second loop |
|---|---|---|---|---|---|
| no | no | robin@example.com |
pending | sent, 1 attempt | |
| sms | no | yes | (not checked) | turned off | turned off, stored |
| push | no | no | device-7 |
pending | sent, 1 attempt |
That is the three lines the demo prints under payment failed:. The
verification trace below follows order-1001-shipped through the same
code, including the repeat.
notify works in two loops, and the split is the point. The first loop
decides every channel and can throw: render, check that a sender
exists, check for an earlier record, check preferences and address.
Nothing is changed yet. The second loop acts: it stores the
records and makes the first attempts, and nothing in it can fail for a
reason the caller could fix. So when notify throws for a missing
field, no message has gone out and no record exists, and the caller can
fix the field and call again with the same id (AC-1.3).
Render everything first shows the version
that gets this wrong.
The order of the checks in the first loop is also a decision. A duplicate is checked before preferences, so a repeat reports what happened the first time, even if the user has since turned the channel off. A required kind skips the opt-out check, but not the address check: a reset code cannot go to a phone number the user never gave.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One try at one delivery: call the provider, then record the answer.// Every way out either ends the delivery (sent or failed) or puts it// back in due_ for later; none leaves it pending with no entry. It// does not throw for a provider's failure, even one that throws.void Notifier::attempt(Record& record) { const TimePoint now = clock_->now(); Delivery& delivery = record.delivery; // a reference: changes go into the stored record ++delivery.attempts; // counted first, so the count is right whatever send does SendResult result; // overwritten below on every path try { result = sender_for(delivery.channel).send(record.message); } catch (const std::exception& error) { // An adapter that throws (a bug, or std::bad_alloc) is treated as // "may work later", with the exception's message as the detail. result = {SendStatus::retry_later, error.what()}; } catch (...) { // `...` catches anything else, even a thrown non-exception result = {SendStatus::retry_later, "unknown exception"}; } delivery.detail = std::move(result.detail); // result is not needed after this delivery.updated = now; switch (result.status) { case SendStatus::sent: delivery.outcome = Outcome::sent; break; case SendStatus::rejected: delivery.outcome = Outcome::failed; break; case SendStatus::retry_later: // Attempts left: schedule the next one after the backoff for // this attempt number (30 s after the first, by default). if (delivery.attempts < retry_.max_attempts) { delivery.outcome = Outcome::pending; due_.emplace(now + backoff(retry_, delivery.attempts), Key{delivery.id, delivery.channel}); return; // keep the message for the next attempt } // That was the last attempt: give up, keeping the last reason. delivery.outcome = Outcome::failed; delivery.detail = "gave up after " + std::to_string(delivery.attempts) + " attempts: " + delivery.detail; break; } record.message = Message{}; // the outcome is final: the text is no longer needed}
// Called from a timer. Takes the earliest entries in due_, one at a// time, while they are due (at or before now), and attempts each.std::size_t Notifier::run_due() { const TimePoint now = clock_->now(); // read once: an attempt scheduled now is for later std::size_t made = 0; // An attempt schedules its retry after now (every delay is positive), // so this loop ends. while (!due_.empty() && due_.begin()->first <= now) { const Key key = due_.begin()->second; // a copy, so erasing the entry cannot spoil it due_.erase(due_.begin()); // erased first: attempt may add a new entry attempt(records_.at(key)); // at() throws if absent; every due key has a record ++made; } return made;}How this code works: Notifier::attempt and run_due
attempt, one try:
- Read the time once, take a reference to the stored
Delivery, and add one toattempts. - Call the channel’s sender inside
try. Whatever happens,resultends up holding an answer: the sender’s own, orretry_laterwith the exception’s message if the sender threw. - Move the provider’s reason into the delivery’s
detail, and setupdatedto the time. - Act on the status.
sentandrejectedare final.retry_laterwith attempts left goes back intodue_atnow + backoff(...)and returns early, keeping the message for the next try. With no attempts left it becomesfailed, with “gave up after” in front of the last reason. - Every final outcome reaches the last line, which replaces the message with an empty one: it will never be sent again.
run_due, the timer’s call. due_ is sorted by time, so
due_.begin() is always the earliest entry. The loop keeps taking it
while its time is at or before now: copy the key, erase the entry,
then attempt. A retry it schedules is for a time after now, so the
same loop never picks it up again.
A trace: AC-4.3. Four failures are queued for the push, the
default policy allows four attempts, and the first attempt is made by
notify at 09:00:00.
| When | Who calls attempt |
attempts |
Answer | Outcome | Next entry in due_ |
|---|---|---|---|---|---|
| 09:00:00 | notify |
1 | retry_later |
pending | 09:00:30 (backoff 30 s) |
| 09:00:30 | run_due |
2 | retry_later |
pending | 09:01:30 (backoff 60 s) |
| 09:01:30 | run_due |
3 | retry_later |
pending | 09:03:30 (backoff 120 s) |
| 09:03:30 | run_due |
4 | retry_later |
failed | none: 4 is not less than 4 |
The last detail is gave up after 4 attempts: push service unavailable,
which is what the test checks, and pending() is 0.
attempt counts the attempt first, so the count is right whatever
send does. Every way out of attempt either finishes the delivery
(and drops the message) or schedules it again, which is how INV-2 is
kept. The schedule time is now + backoff(...), and every delay is at
least first_delay, which the constructor checks is positive; that is
why the loop in run_due ends, as its comment says.
run_due erases the entry from due_ before calling attempt.
That keeps INV-2 simple: while attempt runs, the delivery has no
entry, and it adds at most one. It also means run_due holds no
iterator into due_ across a call that changes due_.
Text description of the diagram
A delivery starts in one of three outcomes when notify decides it: turned off (the user turned the channel off and the kind is not required), no address (the user has no address on the channel), or pending, with the first attempt made at once. From pending, an attempt that the provider accepts moves it to sent; a rejection moves it to failed; a “retry later” keeps it pending and schedules another attempt while attempts are left, and moves it to failed when none are. Turned off, no address, sent, and failed are final. Duplicate is not a state: it is what notify reports for a repeat, and the record keeps its first outcome.
Diagram source (Mermaid)
stateDiagram-v2
[*] --> turned_off : notify, channel off, kind not required
[*] --> no_address : notify, no address on this channel
[*] --> pending : notify, attempt made
pending --> pending : retry later, attempts left, scheduled
pending --> sent : provider accepted
pending --> failed : rejected
pending --> failed : retry later, no attempts left
turned_off --> [*]
no_address --> [*]
sent --> [*]
failed --> [*]Where each rule lives
Section titled “Where each rule lives”| Rule | Where it lives |
|---|---|
| Which provider calls to make | one adapter per provider |
| Which provider answers are worth retrying | each adapter, as a SendStatus |
| A missing field sends nothing | notify’s first loop, before anything is stored |
| A repeat sends nothing new | notify’s check of records_ |
| Opt-out, required kinds, addresses | notify’s first loop, using Preferences |
| How long to wait, and how often | RetryPolicy and backoff |
| When to try again | due_, filled by attempt, emptied by run_due |
| Templates are well formed | the Template constructor |
| What happened | records_, read by find |
Verification trace
Section titled “Verification trace”Take the step 1 demo: the push service fails once, and a caller sends
order-1001-shipped for user u-7 at 09:00.
Text description of the diagram
The order code calls notify with order-1001-shipped. The notifier renders the email and the push, and checks the records and the preferences. It sends the email through EmailSender, which reports sent with status 202, and the push through PushSender, which reports retry later because the push service is unavailable. The notifier schedules the push for 09:00:30 and returns: email sent, push pending. The order code calls notify again with the same id, and gets duplicate for both channels; nothing is sent. At 09:00:30 the timer calls run_due; the notifier sends the same push message again, PushSender reports sent, and run_due returns 1.
Diagram source (Mermaid)
sequenceDiagram
participant O as order code
participant N as Notifier
participant E as EmailSender
participant P as PushSender
participant T as timer
O->>N: notify(order-1001-shipped)
N->>N: render email and push, check records and preferences
N->>E: send(email)
E-->>N: sent, status 202
N->>P: send(push)
P-->>N: retry later, push service unavailable
N->>N: schedule push at 09:00:30
N-->>O: email sent, push pending
O->>N: notify(order-1001-shipped) again
N-->>O: email duplicate, push duplicate
T->>N: run_due() at 09:00:30
N->>P: send(push), the same message
P-->>N: sent
N-->>T: 1 attempt madeStep by step, in the code:
catalog_->find("order-shipped")finds a kind with email and push.contact("u-7")finds Robin’s details.- The first loop renders both messages, finds a sender for both, finds
no earlier record, sees neither channel turned off, and finds both
addresses.
decidedholds two pending records with their messages. - The second loop stores the email record and calls
attempt: attempts 1,EmailSenderreturnssentwithstatus 202, the message is dropped. - It stores the push record and calls
attempt: attempts 1,PushSenderreturnsretry_later. One attempt is less than four, so the record stayspendinganddue_gets 09:00:30 → (id, push). - The repeat: both
records_.findcalls succeed, so both channels areduplicate, with the detailalready sentandalready pending. Nothing is stored or sent. - At 09:00:30,
run_duefinds 09:00:30 ≤ now, erases it, and callsattempton the push record: attempts 2,sent.
Architecture and patterns
Section titled “Architecture and patterns”Text description of the diagram
Callers, the order code and the payments code, call notify on the Notifier. A timer calls run_due. Inside the notification service, the Notifier, which keeps the records and the schedule, reads the Catalog (kinds and templates), the Preferences (contacts and opt-outs), and the Clock, and sends through three adapters that implement Sender: EmailSender, SmsSender, and PushSender. Only the adapters depend on the provider libraries: EmailSender on acme_mail, SmsSender on textly, and PushSender on pushy.
Diagram source (Mermaid)
flowchart LR
subgraph Callers["callers"]
OC["order code"]
PC["payments code"]
end
subgraph Service["notification service"]
N["Notifier<br/>records, schedule"]
C["Catalog<br/>kinds, templates"]
PR["Preferences<br/>contacts, opt-outs"]
CL["Clock"]
subgraph Adapters["adapters: Sender"]
ES["EmailSender"]
SS["SmsSender"]
PS["PushSender"]
end
end
subgraph Providers["provider libraries"]
AM["acme_mail"]
TX["textly"]
PU["pushy"]
end
TM(["timer"])
OC -->|"notify"| N
PC -->|"notify"| N
TM -->|"run_due"| N
N --> C
N --> PR
N --> CL
N --> ES
N --> SS
N --> PS
ES --> AM
SS --> TX
PS --> PUWhere does provider code live?
Section titled “Where does provider code live?”The interface is the notifier’s, not any provider’s. It has no “envelope”, no status code, no device token type: only what the notifier needs to decide what to do next. That is what keeps provider details from leaking in, the leaky abstraction that a thin wrapper around one provider’s library usually becomes. The same shape appears, at the scale of a whole application, as the ports and adapters of Hexagonal architecture.
Who calls notify?
Section titled “Who calls notify?”Someone has to turn “order 1001 shipped” into a Notification. If the
order code builds it, the order code knows notification kinds and
template fields, and every new kind means editing it.
IllustrativeA fragment for explanation; not compiled on its own.
// What the order code publishes. It knows nothing about notifications.struct OrderShipped { std::string order_id; std::string customer; std::string customer_name; std::string tracking_url;};
// Subscribed to the order events when the service starts. It turns an// event into a notification, and takes the id from the event, so an// event that is delivered twice is still one notification.class ShippingNotifications {public: explicit ShippingNotifications(Notifier& notifier) : notifier_(¬ifier) {}
// Called once per OrderShipped event. It builds the Notification in // place: {id, user, kind, fields}. The deliveries notify returns are // not needed here, so static_cast<void> discards them on purpose. // A missing field would throw std::invalid_argument up to whoever // delivered the event. void on_shipped(const OrderShipped& event) { static_cast<void>(notifier_->notify({"order-" + event.order_id + "-shipped", event.customer, "order-shipped", {{"name", event.customer_name}, {"order", event.order_id}, {"tracking", event.tracking_url}}})); }
private: Notifier* notifier_; // not owned; must outlive this subscriber};The order code publishes what happened, and a small subscriber turns it into a notification. That is Observer (Observer) inside one process, or an event bus between processes; see Event-driven architecture. The example leaves the subscriber out, because the notifier does not care who calls it, but one line in it matters: the id comes from the event. Event buses usually deliver at least once, so the subscriber will see some events twice, and the notifier’s idempotency turns that into one message. (This sketch was compiled against the step 1 headers, not run.)
Retrying: sleep, or schedule?
Section titled “Retrying: sleep, or schedule?”The schedule is data, which is the deeper advantage. A sleeping
loop keeps its state on a thread’s stack, where nothing else can see
it, count it, or save it. A due_ entry can be counted (pending()),
printed for support, and, in a later version, written to a database so
that a restart does not forget it. See
Retrying: which, how often, how long to wait
for the backoff itself, and for jitter, which this example leaves out
because it has one user and one clock.
Render everything first
Section titled “Render everything first”What “once” means here
Section titled “What “once” means here”What is not here, and why
Section titled “What is not here, and why”- No Observer between the notifier and its senders. A
Senderis chosen by channel and asked a question that needs an answer. That is a call, not a broadcast. - No Factory for senders. The service builds three senders once, in
main. A factory would be one more class for one line of code. - No Strategy for retry policies. One policy, a struct of three
numbers, covers every channel the team named. A second policy for
some kind would be a field in
Kind, not a class hierarchy. - No message queue inside the notifier.
due_is a schedule, not a queue: it holds only retries, in time order. A real queue between services is the caller’s choice, upstream.
Building it step by step
Section titled “Building it step by step”The example has two steps, each a complete program with its own tests:
- Step 1 is the design above: the adapters, templates, kinds, preferences, and the notifier with its records and schedule.
- Step 2 is the change: quiet hours and rate limits. See When the requirements change.
The order inside step 1 is worth copying. The fake providers came
first, with their failure switches, because every later test needs
them. Then Sender and the three adapters, tested on their own against
the fakes (AC-3). Then templates and the catalog, then a notifier that
sent once with no retries, then the schedule and run_due, and last
the duplicate check, with the repeat tests written before it.
Scenarios
Section titled “Scenarios”The step 1 demo
Section titled “The step 1 demo”The demo builds a shop with the three kinds above, for one user, Robin, who has turned off texts about failed payments and about password resets. The push service fails once at the start.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The composition root: it owns every object, and declares each one// before the objects that refer to it.// 2 March 2026 at 09:00 UTC: year{2026} / 3 / 2 is a calendar date,// sys_days turns it into that day's midnight, and + 9h adds the time.ManualClock clock(sys_days{year{2026} / 3 / 2} + 9h);acme_mail::Client mail;textly::Gateway texts;pushy::Api push;const Catalog catalog = shop_catalog();Preferences preferences;// {email, phone, device}, in Contact's member order.preferences.set_contact("u-7", {"robin@example.com", "+15550100", "device-7"});preferences.turn_off("u-7", "payment-failed", Channel::sms);preferences.turn_off("u-7", "password-reset", Channel::sms);
// The adapters are made on the heap with std::make_unique and owned// by unique_ptrs; each refers to a fake client declared above.std::vector<std::unique_ptr<Sender>> senders;senders.push_back(std::make_unique<EmailSender>(mail, "shop@example.com"));senders.push_back(std::make_unique<SmsSender>(texts));senders.push_back(std::make_unique<PushSender>(push));// RetryPolicy{} is the default policy. std::move hands the senders to// the notifier, which now owns them; `senders` is left empty.Notifier notifier(catalog, preferences, clock, RetryPolicy{}, std::move(senders));
const Notification shipped{"order-1001-shipped", "u-7", "order-shipped", {{"name", "Robin"}, {"order", "1001"}, {"tracking", "https://t.example/1001"}}};push.fail_next(pushy::Result::unavailable); // the next push fails, as if the service were downstd::cout << "order shipped:\n";print(notifier.notify(shipped)); // print shows each Delivery on one line
std::cout << "the caller is unsure, and sends it again:\n";print(notifier.notify(shipped));
clock.advance(30s);std::cout << "30 s later, " << notifier.run_due() << " retry is due:\n";// find returns a pointer to the stored Delivery; * reads it, and the// braces make a one-element vector of (a copy of) it for print.print({*notifier.find("order-1001-shipped", Channel::push)});
std::cout << "payment failed:\n";print(notifier.notify({"order-1002-payment", "u-7", "payment-failed", {{"name", "Robin"}, {"order", "1002"}}}));
std::cout << "password reset (required):\n";print(notifier.notify({"reset-88", "u-7", "password-reset", {{"code", "493817"}}}));
std::cout << "providers delivered: " << mail.delivered().size() << " emails, " << texts.delivered().size() << " text, " << push.delivered().size() << " pushes\n";order shipped: email: sent after 1 attempt (status 202) push: pending after 1 attempt (push service unavailable)the caller is unsure, and sends it again: email: duplicate (already sent) push: duplicate (already pending)30 s later, 1 retry is due: push: sent after 2 attemptspayment failed: email: sent after 1 attempt (status 202) sms: turned off push: sent after 1 attemptpassword reset (required): email: sent after 1 attempt (status 202) sms: sent after 1 attemptproviders delivered: 3 emails, 1 text, 2 pushesRead the output against the rules:
- order shipped goes out by email at once; the push fails and waits.
- sends it again: both channels are duplicates, and each reports what happened the first time. Nothing is sent.
- 30 s later, the retry makes the second push attempt, and it goes.
- payment failed skips SMS, which Robin turned off for this kind.
- password reset is required, so the text goes even though Robin turned texts off for it too.
- providers delivered counts what the fakes delivered: three emails (shipping, payment, reset), one text (the reset), and two pushes (shipping, on its second attempt, and payment).
The tests are named after the acceptance criteria and run against the
real notifier and adapters, with the fake providers. A World builds
everything a test needs, in the order the notifier needs it.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Everything a test needs, declared in the order the notifier needs it:// each object is made before the objects that refer to it, and destroyed// after them.//// Members are built in the order they are declared, and destroyed in// the reverse order, so the notifier (last) goes first, while// everything it points to still exists. A fresh World per test means// no test can see another's messages or records.struct World { ManualClock clock{start}; // start: 2 March 2026, 09:00 UTC, defined above acme_mail::Client mail; textly::Gateway texts; pushy::Api push; Catalog catalog = shop_catalog(); // not const: ac_1_3 adds a kind to it Preferences preferences; // real_senders (above) makes the three real adapters around the fakes. Notifier notifier{catalog, preferences, clock, RetryPolicy{}, real_senders(mail, texts, push)};
// The body runs after every member is made. The notifier reads // preferences only when asked, so setting the contact now is fine. World() { preferences.set_contact("u-7", {"robin@example.com", "+15550100", "device-7"}); }};
// Three ready-made notifications for Robin (user u-7). Each takes the id// as an argument with a default, so a test can make a second, different// notification of the same kind: shipped("order-2-shipped").Notification shipped(std::string id = "order-1001-shipped") { return {std::move(id), "u-7", "order-shipped", {{"name", "Robin"}, {"order", "1001"}, {"tracking", "https://t.example/1001"}}};}Notification payment(std::string id = "order-1002-payment") { return {std::move(id), "u-7", "payment-failed", {{"name", "Robin"}, {"order", "1002"}}};}Notification reset(std::string id = "reset-88") { return {std::move(id), "u-7", "password-reset", {{"code", "493817"}}}; }VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a// failure if the condition is false; LLD_CHECK_EQ(actual, expected)// does the same for actual == expected and prints both values when they// differ (the operator<< functions at the top of this file let it print// an Outcome or a SendStatus); LLD_CHECK_THROWS(expression, type) fails// unless the expression throws that type. They come from the site's// small test header, lld_test.hpp. std::size_t{2} writes 2 with the type that size()// returns, so the comparison is between two values of one type.//// order-shipped goes by email and push: one Delivery each, in that// order, and each fake provider received one message.LLD_TEST(ac_1_1_a_notification_goes_out_on_every_channel_of_its_kind) { World w; const std::vector<Delivery> got = w.notifier.notify(shipped()); LLD_CHECK_EQ(got.size(), std::size_t{2}); LLD_CHECK(got[0].channel == Channel::email && got[0].outcome == Outcome::sent); LLD_CHECK(got[1].channel == Channel::push && got[1].outcome == Outcome::sent); LLD_CHECK_EQ(w.mail.delivered().size(), std::size_t{1}); LLD_CHECK_EQ(w.push.delivered().size(), std::size_t{1}); LLD_CHECK(w.texts.delivered().empty()); // order-shipped has no SMS}
// What the providers received is the template text with each {field}// replaced by the notification's value.LLD_TEST(ac_1_2_the_templates_are_filled_from_the_fields) { World w; static_cast<void>(w.notifier.notify(shipped())); const acme_mail::Envelope& email = w.mail.delivered().at(0); // at(0): the first, checked LLD_CHECK_EQ(email.subject, std::string("Your order 1001 has shipped")); LLD_CHECK_EQ(email.text, std::string("Hi Robin, order 1001 is on its way. Track it at https://t.example/1001.")); LLD_CHECK_EQ(w.push.delivered().at(0).title, std::string("Order shipped")); LLD_CHECK_EQ(w.push.delivered().at(0).body, std::string("1001 is on its way"));}
// A notification missing a field throws, and leaves no trace: nothing// sent, nothing recorded. Then the same id, with the field, goes out.LLD_TEST(ac_1_3_a_missing_field_fails_the_whole_call_and_sends_nothing) { World w; // Only the push, the last channel, needs {points}: the email would // render, and must still not be sent. w.catalog.add({"points-earned", false, {{Channel::email, {Template("Points for {order}"), Template("Hi {name}, thanks for {order}.")}}, {Channel::push, {Template("Points"), Template("You earned {points} points")}}}}); Notification n{"order-1001-points", "u-7", "points-earned", {{"name", "Robin"}, {"order", "1001"}}}; LLD_CHECK_THROWS(w.notifier.notify(n), std::invalid_argument); LLD_CHECK(w.mail.delivered().empty() && w.push.delivered().empty()); LLD_CHECK(w.notifier.find(n.id, Channel::email) == nullptr); // nothing recorded n.fields["points"] = "40"; // the caller fixes the field and calls again with the same id const std::vector<Delivery> fixed = w.notifier.notify(n); LLD_CHECK_EQ(fixed.at(0).outcome, Outcome::sent); // not a duplicate LLD_CHECK_EQ(w.push.delivered().at(0).body, std::string("You earned 40 points"));}
// Three bad calls, each refused with std::invalid_argument before any// message is sent.LLD_TEST(ac_1_4_an_unknown_kind_an_empty_id_or_no_user_is_an_error) { World w; Notification n = shipped(); n.kind = "order-lost"; LLD_CHECK_THROWS(w.notifier.notify(n), std::invalid_argument); LLD_CHECK_THROWS(w.notifier.notify(shipped("")), std::invalid_argument); n = shipped(); n.user.clear(); LLD_CHECK_THROWS(w.notifier.notify(n), std::invalid_argument); LLD_CHECK(w.mail.delivered().empty());}
// payment-failed uses all three channels; each provider gets the// matching part of Robin's Contact.LLD_TEST(ac_1_5_each_channel_gets_its_own_address) { World w; static_cast<void>(w.notifier.notify(payment())); LLD_CHECK_EQ(w.mail.delivered().at(0).to, std::string("robin@example.com")); LLD_CHECK_EQ(w.texts.delivered().at(0).number, std::string("+15550100")); LLD_CHECK_EQ(w.push.delivered().at(0).device, std::string("device-7"));}
// A value that looks like a placeholder is copied as plain text.LLD_TEST(ac_1_6_a_field_value_is_never_expanded_again) { World w; Notification n = shipped(); n.fields["name"] = "{tracking}"; // text a user typed into their profile static_cast<void>(w.notifier.notify(n)); LLD_CHECK_EQ(w.mail.delivered().at(0).text, std::string("Hi {tracking}, order 1001 is on its way. Track it at https://t.example/1001."));}ac_1_3 adds a kind whose last channel needs a field that only it
uses. A missing field on the first channel would fail early in both
the right and the flawed notify; only a field missing on a later
channel tells them apart. The test then gives the field and calls again
with the same id, which must not be a duplicate.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The payment-failed results are in channel order: at(0) email, at(1)// sms, at(2) push. A skipped channel still gets a record, so support can// see why nothing went.LLD_TEST(ac_2_1_a_channel_the_user_turned_off_is_skipped_and_recorded) { World w; w.preferences.turn_off("u-7", "payment-failed", Channel::sms); const std::vector<Delivery> got = w.notifier.notify(payment()); LLD_CHECK_EQ(got.at(1).outcome, Outcome::turned_off); LLD_CHECK(w.texts.delivered().empty()); LLD_CHECK_EQ(w.notifier.find(payment().id, Channel::sms)->outcome, Outcome::turned_off); LLD_CHECK_EQ(got.at(0).outcome, Outcome::sent); // the other channels still go LLD_CHECK_EQ(got.at(2).outcome, Outcome::sent);}
// password-reset is required, so turning off its SMS has no effect:// at(1), the text, is still sent.LLD_TEST(ac_2_2_a_required_kind_is_sent_even_when_turned_off) { World w; w.preferences.turn_off("u-7", "password-reset", Channel::sms); const std::vector<Delivery> got = w.notifier.notify(reset()); LLD_CHECK_EQ(got.at(1).outcome, Outcome::sent); LLD_CHECK_EQ(w.texts.delivered().size(), std::size_t{1});}
LLD_TEST(ac_2_3_a_channel_without_an_address_is_skipped_and_recorded) { World w; w.preferences.set_contact("u-7", {"robin@example.com", "", ""}); // no phone, no app const std::vector<Delivery> got = w.notifier.notify(payment()); LLD_CHECK_EQ(got.at(0).outcome, Outcome::sent); LLD_CHECK_EQ(got.at(1).outcome, Outcome::no_address); LLD_CHECK_EQ(got.at(2).outcome, Outcome::no_address); LLD_CHECK(w.texts.delivered().empty() && w.push.delivered().empty());}
// A user the preferences have never heard of: contact() is nullptr, so// every channel is no_address, and the loop checks each one.LLD_TEST(ac_2_4_a_user_without_contact_details_gets_nothing) { World w; Notification n = shipped(); n.user = "u-unknown"; for (const Delivery& d : w.notifier.notify(n)) LLD_CHECK_EQ(d.outcome, Outcome::no_address); LLD_CHECK(w.mail.delivered().empty() && w.push.delivered().empty());}
// turn_on undoes turn_off, so the text goes again.LLD_TEST(ac_2_5_a_channel_turned_back_on_is_sent_again) { World w; w.preferences.turn_off("u-7", "payment-failed", Channel::sms); w.preferences.turn_on("u-7", "payment-failed", Channel::sms); const std::vector<Delivery> got = w.notifier.notify(payment()); LLD_CHECK_EQ(got.at(1).outcome, Outcome::sent);}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each adapter on its own, with no notifier: fail_next makes the fake's// next call fail in a chosen way, and the test checks the SendStatus the// adapter turns it into. With no failure queued, the fake accepts.LLD_TEST(ac_3_1_email_statuses_become_results) { acme_mail::Client mail; EmailSender sender(mail, "shop@example.com"); // {id, channel, to, subject, body}, in Message's member order. const Message m{"n-1", Channel::email, "robin@example.com", "Hi", "Body"}; LLD_CHECK_EQ(sender.send(m).status, SendStatus::sent); for (const int status : {429, 503, 504}) { // each code that may work later mail.fail_next(status); LLD_CHECK_EQ(sender.send(m).status, SendStatus::retry_later); } mail.fail_next(400); const SendResult rejected = sender.send(m); LLD_CHECK_EQ(rejected.status, SendStatus::rejected); LLD_CHECK_EQ(rejected.detail, std::string("status 400"));}
LLD_TEST(ac_3_2_sms_errors_become_results) { textly::Gateway texts; SmsSender sender(texts); const Message m{"n-1", Channel::sms, "+15550100", "", "Body"}; texts.fail_next("busy", true); // the gateway throws a retryable textly::Error LLD_CHECK_EQ(sender.send(m).status, SendStatus::retry_later); texts.fail_next("not a mobile number", false); const SendResult rejected = sender.send(m); LLD_CHECK_EQ(rejected.status, SendStatus::rejected); LLD_CHECK_EQ(rejected.detail, std::string("not a mobile number")); LLD_CHECK_EQ(sender.send(m).status, SendStatus::sent); // no failure queued: accepted}
LLD_TEST(ac_3_3_push_results_become_results) { pushy::Api push; PushSender sender(push); const Message m{"n-1", Channel::push, "device-7", "Title", "Body"}; push.fail_next(pushy::Result::unavailable); LLD_CHECK_EQ(sender.send(m).status, SendStatus::retry_later); push.fail_next(pushy::Result::unregistered_device); LLD_CHECK_EQ(sender.send(m).status, SendStatus::rejected); LLD_CHECK_EQ(sender.send(m).status, SendStatus::sent); LLD_CHECK_EQ(push.delivered().size(), std::size_t{1}); // only the accepted push arrived}
// Through the notifier this time: the envelope's dedupe key is the// notification's id.LLD_TEST(ac_3_4_an_email_carries_the_notification_id_as_its_dedupe_key) { World w; static_cast<void>(w.notifier.notify(shipped())); LLD_CHECK_EQ(w.mail.delivered().at(0).dedupe_key, std::string("order-1001-shipped"));}The adapter tests use each fake on its own, without a notifier: an adapter is a translation, and a table of inputs and expected results is the whole specification. See Property-based and table-driven tests.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The push fails once at 09:00. Its retry is due at 09:00:30, so at// 09:00:29 run_due makes no attempt and at 09:00:30 it makes one, which// is accepted. w.clock.advance moves the fake clock; nothing sleeps.LLD_TEST(ac_4_1_a_failure_that_may_pass_is_retried_after_the_backoff) { World w; w.push.fail_next(pushy::Result::unavailable); const std::vector<Delivery> first = w.notifier.notify(shipped()); LLD_CHECK_EQ(first.at(1).outcome, Outcome::pending); LLD_CHECK_EQ(w.notifier.pending(), std::size_t{1}); w.clock.advance(29s); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{0}); // not yet w.clock.advance(1s); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{1}); const Delivery* push = w.notifier.find("order-1001-shipped", Channel::push); LLD_CHECK_EQ(push->outcome, Outcome::sent); LLD_CHECK_EQ(push->attempts, 2); LLD_CHECK(push->updated == start + 30s); LLD_CHECK_EQ(w.notifier.pending(), std::size_t{0});}
// backoff on its own, with the default policy: 30 s doubling each// time, never above 600 s.LLD_TEST(ac_4_2_the_backoff_doubles_up_to_a_limit) { const RetryPolicy policy{}; LLD_CHECK(backoff(policy, 1) == 30s); LLD_CHECK(backoff(policy, 2) == 60s); LLD_CHECK(backoff(policy, 3) == 120s); LLD_CHECK(backoff(policy, 5) == 480s); LLD_CHECK(backoff(policy, 6) == 600s); // capped LLD_CHECK(backoff(policy, 1000) == 600s);}
// Four failures queued, so all four attempts fail. Each wait (30 s,// 60 s, 120 s) is checked one second early (no attempt) and on time// (one attempt). After the fourth, the delivery has failed for good.LLD_TEST(ac_4_3_after_the_last_attempt_the_delivery_fails_with_the_reason) { World w; for (int i = 0; i < 4; ++i) w.push.fail_next(pushy::Result::unavailable); static_cast<void>(w.notifier.notify(shipped())); for (const seconds wait : {30s, 60s, 120s}) { w.clock.advance(wait - 1s); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{0}); // not a second early w.clock.advance(1s); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{1}); } const Delivery* push = w.notifier.find("order-1001-shipped", Channel::push); LLD_CHECK_EQ(push->outcome, Outcome::failed); LLD_CHECK_EQ(push->attempts, 4); LLD_CHECK_EQ(push->detail, std::string("gave up after 4 attempts: push service unavailable")); LLD_CHECK_EQ(w.notifier.pending(), std::size_t{0}); LLD_CHECK(w.push.delivered().empty());}
// "Never works" ends the delivery at once: failed, nothing scheduled.LLD_TEST(ac_4_4_a_rejected_message_is_not_retried) { World w; w.push.fail_next(pushy::Result::unregistered_device); const Delivery push = w.notifier.notify(shipped()).at(1); LLD_CHECK_EQ(push.outcome, Outcome::failed); LLD_CHECK_EQ(push.detail, std::string("device not registered")); LLD_CHECK_EQ(w.notifier.pending(), std::size_t{0});}
// A notifier built by hand, so that its push sender is the// ThrowingSender above (it throws on its first call only). Robin has no// email address here, so only the push is attempted. The exception// becomes a retry, and the retry is sent.LLD_TEST(ac_4_5_a_sender_that_throws_is_retried) { ManualClock clock(start); const Catalog catalog = shop_catalog(); Preferences preferences; preferences.set_contact("u-7", {"", "", "device-7"}); std::vector<std::unique_ptr<Sender>> senders; senders.push_back(std::make_unique<ThrowingSender>()); acme_mail::Client mail; senders.push_back(std::make_unique<EmailSender>(mail, "shop@example.com")); Notifier notifier(catalog, preferences, clock, RetryPolicy{}, std::move(senders)); const Delivery push = notifier.notify(shipped()).at(1); LLD_CHECK_EQ(push.outcome, Outcome::pending); LLD_CHECK_EQ(push.detail, std::string("socket closed")); // the exception's what() clock.advance(30s); static_cast<void>(notifier.run_due()); LLD_CHECK_EQ(notifier.find("order-1001-shipped", Channel::push)->outcome, Outcome::sent);}
// The email is rejected (400); the text and push still go.LLD_TEST(ac_4_6_one_channel_failing_does_not_stop_the_others) { World w; w.mail.fail_next(400); const std::vector<Delivery> got = w.notifier.notify(payment()); LLD_CHECK_EQ(got.at(0).outcome, Outcome::failed); LLD_CHECK_EQ(got.at(1).outcome, Outcome::sent); LLD_CHECK_EQ(got.at(2).outcome, Outcome::sent);}The retry tests move a ManualClock by hand. ac_4_3 checks every
wait twice: one second before it, run_due must make no attempt; at
it, exactly one. A test that only checked that each attempt happened
eventually would pass a backoff that waits 30, 30, 60 instead of 30,
60, 120. ac_4_5 uses a ThrowingSender, a
test double that throws on
its first call, for the failure that no fake provider produces: a bug
in an adapter.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same id twice: the second call reports duplicate on each channel,// with what the first call led to, and the providers got one each.LLD_TEST(ac_5_1_the_same_notification_twice_is_sent_once_per_channel) { World w; static_cast<void>(w.notifier.notify(shipped())); const std::vector<Delivery> again = w.notifier.notify(shipped()); LLD_CHECK_EQ(again.at(0).outcome, Outcome::duplicate); LLD_CHECK_EQ(again.at(0).detail, std::string("already sent")); LLD_CHECK_EQ(again.at(1).outcome, Outcome::duplicate); LLD_CHECK_EQ(w.mail.delivered().size(), std::size_t{1}); LLD_CHECK_EQ(w.push.delivered().size(), std::size_t{1}); LLD_CHECK_EQ(w.notifier.find("order-1001-shipped", Channel::email)->outcome, Outcome::sent); // unchanged}
// A repeat arrives while the push waits for its retry. It must not add// a second entry to the schedule: after the retry, nothing is pending// and exactly one push arrived.LLD_TEST(ac_5_2_a_repeat_while_a_retry_waits_sends_nothing_new) { World w; w.push.fail_next(pushy::Result::unavailable); static_cast<void>(w.notifier.notify(shipped())); const Delivery again = w.notifier.notify(shipped()).at(1); LLD_CHECK_EQ(again.outcome, Outcome::duplicate); LLD_CHECK_EQ(again.detail, std::string("already pending")); w.clock.advance(30s); static_cast<void>(w.notifier.run_due()); LLD_CHECK_EQ(w.push.delivered().size(), std::size_t{1}); LLD_CHECK_EQ(w.notifier.pending(), std::size_t{0});}
// fail_next(504, true): the fake delivers the email and still answers// 504, like a reply lost on the way back. The notifier retries, and the// provider drops the repeat because it has the same dedupe key.LLD_TEST(ac_5_3_an_email_whose_reply_was_lost_arrives_once) { World w; w.mail.fail_next(504, true); // delivered, but the reply never came back const std::vector<Delivery> first = w.notifier.notify(shipped()); LLD_CHECK_EQ(first.at(0).outcome, Outcome::pending); w.clock.advance(30s); static_cast<void>(w.notifier.run_due()); LLD_CHECK_EQ(w.notifier.find("order-1001-shipped", Channel::email)->outcome, Outcome::sent); LLD_CHECK_EQ(w.mail.delivered().size(), std::size_t{1}); // the provider dropped the repeat}
// The same lost reply for a text: fail_next(what, retryable, delivered// anyway). textly has no dedupe key, so the retry is a second text.LLD_TEST(ac_5_4_an_sms_whose_reply_was_lost_arrives_twice) { World w; w.texts.fail_next("timed out", true, true); // delivered, but the reply never came back static_cast<void>(w.notifier.notify(payment())); w.clock.advance(30s); static_cast<void>(w.notifier.run_due()); LLD_CHECK_EQ(w.notifier.find("order-1002-payment", Channel::sms)->outcome, Outcome::sent); // This provider has no dedupe key, so the user gets the text twice. // The test pins down the limit; it is not a goal. LLD_CHECK_EQ(w.texts.delivered().size(), std::size_t{2});}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_6_1_the_notifier_checks_its_senders_and_its_retry_policy) { ManualClock clock(start); const Catalog catalog = shop_catalog(); const Preferences preferences; acme_mail::Client mail; // A lambda that builds a Notifier from a policy and senders, so each // check below names only what it changes. [&] captures the clock, // catalog, and preferences by reference: the lambda uses these // objects themselves, not copies. const auto make = [&](RetryPolicy retry, std::vector<std::unique_ptr<Sender>> senders) { return Notifier(catalog, preferences, clock, retry, std::move(senders)); }; // In the calls, a bare {} is a default RetryPolicy, or an empty list // of senders; {0, 30s, 600s} is {max_attempts, first_delay, max_delay}. std::vector<std::unique_ptr<Sender>> with_null; with_null.push_back(nullptr); // a unique_ptr that owns nothing LLD_CHECK_THROWS(make({}, std::move(with_null)), std::invalid_argument); std::vector<std::unique_ptr<Sender>> twice; twice.push_back(std::make_unique<EmailSender>(mail, "a@example.com")); twice.push_back(std::make_unique<EmailSender>(mail, "b@example.com")); LLD_CHECK_THROWS(make({}, std::move(twice)), std::invalid_argument); LLD_CHECK_THROWS(make({0, 30s, 600s}, {}), std::invalid_argument); LLD_CHECK_THROWS(make({4, 0s, 600s}, {}), std::invalid_argument); LLD_CHECK_THROWS(make({4, 30s, 10s}, {}), std::invalid_argument);}
// Only an email sender. order-shipped also needs push, so notify throws// in its first loop, before the email is sent.LLD_TEST(ac_6_2_a_kind_on_a_channel_with_no_sender_is_an_error) { ManualClock clock(start); const Catalog catalog = shop_catalog(); Preferences preferences; preferences.set_contact("u-7", {"robin@example.com", "+15550100", "device-7"}); acme_mail::Client mail; std::vector<std::unique_ptr<Sender>> senders; senders.push_back(std::make_unique<EmailSender>(mail, "shop@example.com")); Notifier notifier(catalog, preferences, clock, RetryPolicy{}, std::move(senders)); LLD_CHECK_THROWS(notifier.notify(shipped()), std::invalid_argument); // no push sender LLD_CHECK(mail.delivered().empty()); // and no email either}
// Bad templates (unclosed, a lone '}', no name, a space in the name),// then bad kinds: a name already in the catalog, no channels, no name,// and an SMS with a subject. A refused kind is not added.LLD_TEST(ac_6_3_the_catalog_rejects_bad_kinds_and_templates) { LLD_CHECK_THROWS(Template("Hi {name"), std::invalid_argument); LLD_CHECK_THROWS(Template("Hi name}"), std::invalid_argument); LLD_CHECK_THROWS(Template("Hi {}"), std::invalid_argument); LLD_CHECK_THROWS(Template("Hi {first name}"), std::invalid_argument); Catalog catalog = shop_catalog(); LLD_CHECK_THROWS(catalog.add({"order-shipped", false, {{Channel::email, {Template("a"), Template("b")}}}}), std::invalid_argument); LLD_CHECK_THROWS(catalog.add({"empty", false, {}}), std::invalid_argument); LLD_CHECK_THROWS(catalog.add({"", false, {{Channel::email, {Template("a"), Template("b")}}}}), std::invalid_argument); LLD_CHECK_THROWS(catalog.add({"texted", false, {{Channel::sms, {Template("subject"), Template("b")}}}}), std::invalid_argument); LLD_CHECK(catalog.find("order-shipped") != nullptr); LLD_CHECK(catalog.find("texted") == nullptr);}A random run. The last test makes 3,000 random steps: notifications whose ids repeat often, provider failures of both kinds, and time passing. Then it lets time run until nothing is pending, and checks the invariants and the providers’ own counts.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 3,000 random steps: notifications (often repeats), provider failures of// both kinds, and time passing. Then time runs on until nothing is// pending. Whatever the order, every delivery ends sent or failed, each// sent delivery reached its provider exactly once, and nothing went out// for a delivery that was not sent. Fixed seed, so a failure repeats.LLD_TEST(inv_every_delivery_ends_once_whatever_fails) { World w; std::mt19937 random(2026); // a standard pseudo-random generator, seeded with 2026 // pick(n) is a whole number from 0 to n - 1. random() gives an // unsigned number; % n keeps the remainder after dividing by n. const auto pick = [&](int n) { return static_cast<int>(random() % static_cast<unsigned>(n)); }; int duplicates = 0; for (int step = 0; step < 3000; ++step) { // One of six actions: queue a failure on one of the three // providers (cases 0 to 2; each picks retryable or not), move time // up to 119 s and run the schedule (3), or notify (4 and 5, so // about a third of the steps). switch (pick(6)) { case 0: w.mail.fail_next(pick(2) == 0 ? 503 : 400); break; case 1: w.texts.fail_next("busy", pick(2) == 0); break; case 2: w.push.fail_next(pick(2) == 0 ? pushy::Result::unavailable : pushy::Result::unregistered_device); break; case 3: w.clock.advance(seconds{pick(120)}); static_cast<void>(w.notifier.run_due()); break; default: { // Only 400 ids, so the same id comes up again and again. const std::string id = "event-" + std::to_string(pick(400)); for (const Delivery& d : w.notifier.notify(pick(2) == 0 ? shipped(id) : payment(id))) { if (d.outcome == Outcome::duplicate) ++duplicates; } } } } // Then let time run in 600 s steps (the longest wait) until nothing is // pending; 100 steps is far more than four attempts need. for (int i = 0; i < 100 && w.notifier.pending() > 0; ++i) { w.clock.advance(600s); static_cast<void>(w.notifier.run_due()); } LLD_CHECK_EQ(w.notifier.pending(), std::size_t{0}); LLD_CHECK(duplicates > 100); // the run really did repeat notifications
// Count the final records per channel. static_cast<int>(c) turns // email, sms, push into 0, 1, 2, the index into sent. std::size_t sent[3] = {0, 0, 0}; int failed = 0; for (int n = 0; n < 400; ++n) { for (const Channel c : {Channel::email, Channel::sms, Channel::push}) { const Delivery* d = w.notifier.find("event-" + std::to_string(n), c); if (d == nullptr) continue; LLD_CHECK(d->outcome == Outcome::sent || d->outcome == Outcome::failed); LLD_CHECK(d->attempts >= 1 && d->attempts <= RetryPolicy{}.max_attempts); if (d->outcome == Outcome::sent) ++sent[static_cast<int>(c)]; if (d->outcome == Outcome::failed) ++failed; } } LLD_CHECK(failed > 50); // and failures of both kinds happened // What each fake delivered must equal the number of sent records on // its channel. A duplicate that went out, or a sent record whose // message never arrived, would break one of these. LLD_CHECK_EQ(w.mail.delivered().size(), sent[0]); LLD_CHECK_EQ(w.texts.delivered().size(), sent[1]); LLD_CHECK_EQ(w.push.delivered().size(), sent[2]);}The last three checks are the strongest in the file: the number of
sent records on each channel equals the number of messages the fake
provider delivered. A duplicate that was sent, or a sent record with
no delivery, breaks one of them.
Checking the tests. The tests were checked by 17 hand-written
mutations of the step 1 code, applied one at a time by a script to a
scratch copy (the script is not part of the example); 16
made at least one test fail. The one that survives removes the line in
attempt that drops the message once a delivery is final. That changes
only memory use: nothing reads a final record’s message, so no test
can see it.
When the requirements change
Section titled “When the requirements change”“Customers on the east coast get our ‘payment failed’ texts at 4 in the morning. And when our batch job retries a hundred payments, one customer can get ten texts in a minute. Can texts and pushes wait until morning, and can we cap how many one person gets?”
Two new rules, asked in one breath:
- FR-7 Quiet hours. A user may set a daily quiet period in their own time, which may cross midnight. A text or push of a kind that is not required waits until the period ends. Email is not held: it waits in the inbox anyway.
- FR-8 Rate limits. Each channel may have a limit, such as three texts per user per hour. A message over the limit waits until the window has room. A required message is never held, but it counts.
- FR-9 A hold is not an attempt. Waiting for the morning must not use up a retry.
UC-7 Quiet hours.
- AC-7.1 A text or push in quiet hours waits until they end, and the wait uses no attempt; email goes at once.
- AC-7.2 Quiet hours may cross midnight.
- AC-7.3 Quiet hours may lie within one day.
- AC-7.4 Quiet hours are in the user’s own time, at their offset from UTC.
- AC-7.5 A required kind ignores quiet hours.
- AC-7.6 A retry that falls in quiet hours waits without using an attempt.
- AC-7.7 Bad quiet hours are rejected: a start equal to the end, a time outside the day, or an offset beyond 14 hours.
UC-8 Rate limits.
- AC-8.1 A text over the limit waits until the window has room.
- AC-8.2 The window slides: it is the last hour, not the clock hour.
- AC-8.3 Limits are per user and per channel.
- AC-8.4 A required kind is not held, but it counts.
- AC-8.5 Only messages sent count, not one rejected or one waiting to retry.
- AC-8.6 Texts held through quiet hours meet the limit when the period ends.
- AC-8.7 Bad limits are rejected: a max below one, or a window that is not positive.
- AC-8.8 The log stays in order if the clock is set back.
What moved
Section titled “What moved”| File | Change |
|---|---|
quiet_hours.hpp |
new: QuietHours and quiet_until |
rate_limiter.hpp |
new: RateLimit, RateLimits, and RateLimiter |
preferences.hpp |
quiet hours per user: set_quiet_hours, clear_quiet_hours, quiet_hours |
notifier.hpp |
the constructor takes RateLimits; a Record remembers its user and whether it is required |
notifier.cpp |
attempt asks held_until first; a sent message is recorded in the limiter; run_due counts only real attempts |
| tests | the step 1 tests pass a RateLimits{} (no limits), and are otherwise unchanged |
The adapters, the providers, the templates, and the catalog did not
change. That is the payoff of keeping each rule in one place: both new
rules are about when to attempt, so they land in the one function
that decides when, attempt.
Quiet hours
Section titled “Quiet hours”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A daily period, in the user's own time, when texts and pushes wait.// The times are minutes after local midnight. An end before the start// means the period crosses midnight: {22h, 7h} is 22:00 to 07:00.// The offset from UTC is fixed, so when the user's clocks change for// daylight saving time the period is an hour off until the offset is// updated.// std::chrono::minutes holds a count of minutes, and 22h converts to it// (1320 minutes) without loss. A plain value: copied freely.struct QuietHours { std::chrono::minutes start{0}; std::chrono::minutes end{0}; std::chrono::minutes utc_offset{0}; // local time minus UTC: -5h for UTC-5};
// Throws std::invalid_argument unless start and end are two different// times within a day, and the offset is at most 14 hours either way.void check(const QuietHours& quiet);
// The moment the quiet period ends, if `at` is inside one; otherwise// nullopt. The start minute is inside the period; the end minute is not.// The answer is always later than `at`. Expects quiet hours that pass// check(), as Preferences::set_quiet_hours ensures.[[nodiscard]] std::optional<TimePoint> quiet_until(const QuietHours& quiet, TimePoint at);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Works on the user's local clock: find their date and time of day, see// which of three cases applies, build the end time on their clock, and// turn it back into UTC.std::optional<TimePoint> quiet_until(const QuietHours& quiet, TimePoint at) { using namespace std::chrono; // lets the body write days, minutes, floor, sys_days // Shift the UTC time by the offset, so that its date and time of day // read as the user's local ones. Shift back before returning. const TimePoint local = at + quiet.utc_offset; // floor<days> rounds down to midnight at the start of that day. A // sys_days is such a midnight, counted in whole days. const sys_days today = floor<days>(local); // Time since that midnight, rounded down to whole minutes: 04:00:30 // becomes 240 minutes. const minutes time_of_day = floor<minutes>(local - today);
sys_time<minutes> end; // a point in time counted in minutes, set by each quiet branch if (quiet.start < quiet.end) { // within one day, such as 13:00 to 14:00 if (time_of_day < quiet.start || time_of_day >= quiet.end) return std::nullopt; end = today + quiet.end; } else if (time_of_day >= quiet.start) { // across midnight, before it end = today + days{1} + quiet.end; } else if (time_of_day < quiet.end) { // across midnight, after it end = today + quiet.end; } else { return std::nullopt; } // Undo the shift: the end on the user's clock, back in UTC. The // minutes convert exactly to the clock's finer units. return TimePoint{end - quiet.utc_offset};}How this code works: quiet_until
- Shift to the user’s clock.
local = at + utc_offset. The result is not a real moment; it is a time whose date and time of day read as the user’s. With an offset of −5 hours, 09:00 UTC becomes 04:00. - Split it.
floor<days>(local)rounds down to that day’s midnight (today). What is left, rounded down to whole minutes, istime_of_day. - Pick the case. If
start < end, the period lies within one day, and it is quiet only fromstartup to (not including)end. Otherwise the period crosses midnight: fromstarton, it is the evening part, ending atendtomorrow; beforeend, it is the morning part, ending atendtoday; in between, it is not quiet. - Shift back.
endwas built on the user’s clock, so subtracting the offset turns it back into UTC.
Worked examples from AC-7.4, quiet hours 22:00 to 07:00 (start
1320 minutes, end 420), with Monday 2 March 2026 as the UTC date:
| UTC time | Offset | Their time | time_of_day |
Case | Returns (UTC) |
|---|---|---|---|---|---|
| Monday 09:00 | −5 h | Monday 04:00 | 240 | morning: 240 < 420 | Monday 12:00 |
| Monday 02:00 | −5 h | Sunday 21:00 | 1260 | neither: not quiet | std::nullopt |
| Monday 17:00 | +5:30 | Monday 22:30 | 1350 | evening: 1350 ≥ 1320 | Tuesday 01:30 |
The first row is the step 2 demo’s start: Robin’s text waits until 07:00 their time, 12:00 UTC. In the third, the end is Tuesday 07:00 their time, and 07:00 minus 5 hours 30 minutes is 01:30.
The function answers one question with a time: if now is quiet, when
does it stop? It shifts the UTC time by the user’s offset, so that
floor<days> finds the user’s date and the rest is their time of day.
Three cases follow:
- a period within a day, such as 13:00 to 14:00, ends today;
- a period across midnight, such as 22:00 to 07:00, ends tomorrow if it is evening, and today if it is early morning;
- otherwise it is not quiet.
The start minute is quiet and the end minute is not, so a period from 22:00 to 07:00 holds a message sent at 22:00 and lets one at 07:00 go. The tests pin each edge (AC-7.2, AC-7.3).
Rate limits
Section titled “Rate limits”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// At most `max` messages to one user on a channel in any `per` window.// The defaults are three an hour; {5, 30min} would be five per half hour.struct RateLimit { int max = 3; std::chrono::seconds per{3600};};using RateLimits = std::map<Channel, RateLimit>; // a channel not listed has no limit
// A sliding-window log: for each user and channel, the times of the// messages sent within the last window. A log holds at most `max`// times, plus any required messages sent past the limit; a log that// empties is removed when it is next checked.// Thread safety: not safe.class RateLimiter {public: // Throws std::invalid_argument for a max below 1 or a window that is // not positive. explicit RateLimiter(RateLimits limits);
// When `user` may next be sent a message on `channel`: `now` if the // window has room, otherwise the moment enough of the oldest times // have left it. Drops the times that have left the window. [[nodiscard]] TimePoint next_slot(const std::string& user, Channel channel, TimePoint now);
// Counts a message sent at `at`. void record(const std::string& user, Channel channel, TimePoint at);
private: using Key = std::pair<std::string, Channel>; RateLimits limits_; // A std::deque is a sequence that is quick to add to or remove from at // both ends; old times leave from the front. std::map<Key, std::deque<TimePoint>> sent_; // each log in time order};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Not const: it prunes the log as it answers. The answer is never// earlier than now.TimePoint RateLimiter::next_slot(const std::string& user, Channel channel, TimePoint now) { const auto limit = limits_.find(channel); if (limit == limits_.end()) return now; // this channel has no limit const auto log = sent_.find(Key{user, channel}); if (log == sent_.end()) return now; // nothing sent to this user lately
std::deque<TimePoint>& times = log->second; // a reference: pruning changes the stored log const std::chrono::seconds per = limit->second.per; // The window is (now - per, now]. A time at or before now - per has // left it; the log is in order, so those are all at the front. while (!times.empty() && times.front() <= now - per) times.pop_front(); if (times.empty()) { sent_.erase(log); // drop the empty log; `times` must not be used after this return now; } // max is an int (checked to be at least 1); size() is a std::size_t. // The cast makes both the same unsigned type before they are compared. const auto max = static_cast<std::size_t>(limit->second.max); if (times.size() < max) return now; // room for one more // The window has room once all but max - 1 of these times have left it. // Index size - max is the last of the times that must leave: with max // 3 and four times, it is times[1], so times[0] and times[1] go and // two remain. A time leaves exactly `per` after it was sent. return times[times.size() - max] + per;}
// Adds one sent message to the user's log for that channel.void RateLimiter::record(const std::string& user, Channel channel, TimePoint at) { if (!limits_.contains(channel)) return; // no limit: nothing to remember // operator[] makes an empty log the first time this user and channel // are seen. std::deque<TimePoint>& times = sent_[Key{user, channel}]; // The wall clock can be set back, so insert in order, not at the end. // upper_bound finds the first time later than `at` (a binary search, // which needs the log sorted); inserting there keeps it sorted. It // is usually end(), so this is usually an append. times.insert(std::upper_bound(times.begin(), times.end(), at), at);}How this code works: RateLimiter::next_slot and record
next_slot, step by step:
- No limit for this channel, or no log for this user and channel:
the answer is
now. - Drop from the front every time at or before
now - per. The log is sorted, so the old times are all at the front, and the loop stops at the first time still inside the window. - If that empties the log, erase it and answer
now. - If fewer than
maxtimes remain, there is room:now. - Otherwise, answer
times[size - max] + per, the moment that time, and every time before it, will have left the window.
record adds a time only for a limited channel, at the place that
keeps the log sorted.
A trace: the step 2 demo, three texts an hour. Times are UTC, with
Robin’s own time in brackets; each row shows the log as next_slot
leaves it, and the log after the text is sent and recorded.
| Now | Text | Log after pruning | Answer | Log afterwards |
|---|---|---|---|---|
| 09:00 (04:00) | reset (required) | not asked | (not held) | 09:00 |
| 12:00 (07:00) | payment 1002 | empty, so erased | now | 12:00 |
| 12:10 (07:10) | payment 1003 | 12:00 | now: 1 < 3 | 12:00, 12:10 |
| 12:10 (07:10) | payment 1004 | 12:00, 12:10 | now: 2 < 3 | 12:00, 12:10, 12:10 |
| 12:10 (07:10) | payment 1005 | 12:00, 12:10, 12:10 | times[0] + 1h = 13:00, held |
unchanged |
| 13:00 (08:00) | payment 1005 | 12:10, 12:10 | now: 2 < 3 | 12:10, 12:10, 13:00 |
When required messages overfill the log (AC-8.4). With a limit of
one an hour, the log can hold 09:00 and 09:10, because required texts
are never held. At 09:20, size - max is 1, so the answer is
times[1] + 1h = 10:10. At 10:10, pruning drops both times (each is at
or before 09:10), the log is erased, and the text goes.
The limiter keeps a sliding-window log: for each user and channel,
the times of the messages sent in the last window. To answer “when may
the next one go?” it first drops the times that have left the window.
If fewer than max remain, the answer is now. Otherwise the window has
room when enough of the oldest times have left it, which is the time
size - max places from the front, plus the window.
When the log holds exactly max times, that is the front: the oldest
message’s time plus an hour. It only differs when required messages
have pushed the log past the limit (AC-8.4): with a limit of one an
hour and two reset codes at 09:00 and 09:10, the next text that is not
required may go at 10:10, when both have left the window, not at
10:00.
record inserts in order instead of appending, because the clock is
wall-clock time, and a wall clock can be set back. With an append, a
time from before the change would sit after a later one, and pruning
from the front would stop too early (AC-8.8).
The check before each attempt
Section titled “The check before each attempt”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Returns false if the delivery was held instead.// As in step 1, one try at one delivery, and every way out either ends// the delivery or puts it back in due_. New: before calling the// provider, a delivery that is not required may be held. A hold puts it// back in due_ for later and changes neither its attempt count nor its// outcome (still pending); only its detail says why it waits.bool Notifier::attempt(Record& record) { const TimePoint now = clock_->now(); Delivery& delivery = record.delivery; // a reference: changes go into the stored record if (!record.required) { // `later` is a std::optional: it converts to true only if it holds // a time, and *later reads that time. if (const std::optional<TimePoint> later = held_until(record, now)) { due_.emplace(*later, Key{delivery.id, delivery.channel}); return false; // nothing was sent, so no attempt is counted } } ++delivery.attempts; // counted only now, once the provider will really be called SendResult result; // overwritten below on every path try { result = sender_for(delivery.channel).send(record.message); } catch (const std::exception& error) { // An adapter that throws (a bug, or std::bad_alloc) is treated as // "may work later", with the exception's message as the detail. result = {SendStatus::retry_later, error.what()}; } catch (...) { // `...` catches anything else, even a thrown non-exception result = {SendStatus::retry_later, "unknown exception"}; } delivery.detail = std::move(result.detail); // result is not needed after this delivery.updated = now; switch (result.status) { case SendStatus::sent: delivery.outcome = Outcome::sent; // Only a sent message counts toward the limit, required ones // too; a rejected or failed try does not. limiter_.record(record.user, delivery.channel, now); break; case SendStatus::rejected: delivery.outcome = Outcome::failed; break; case SendStatus::retry_later: // Attempts left: schedule the next one after the backoff for // this attempt number (30 s after the first, by default). if (delivery.attempts < retry_.max_attempts) { delivery.outcome = Outcome::pending; due_.emplace(now + backoff(retry_, delivery.attempts), Key{delivery.id, delivery.channel}); return true; // keep the message for the next attempt } // That was the last attempt: give up, keeping the last reason. delivery.outcome = Outcome::failed; delivery.detail = "gave up after " + std::to_string(delivery.attempts) + " attempts: " + delivery.detail; break; } record.message = Message{}; // the outcome is final: the text is no longer needed return true;}
// When a delivery must wait: through the user's quiet hours (texts and// pushes only), then until the channel's rate limit has room. Preferences// are read now, not when notify was called, so a change to quiet hours// applies to deliveries already waiting.std::optional<TimePoint> Notifier::held_until(Record& record, TimePoint now) { Delivery& delivery = record.delivery; if (delivery.channel != Channel::email) { // email is never held for quiet hours // Each `if (declaration)` runs its body only if the value is true: // a non-null pointer (the user has quiet hours), then an optional // that holds a time (now is inside them). if (const QuietHours* quiet = preferences_->quiet_hours(record.user)) { if (const std::optional<TimePoint> end = quiet_until(*quiet, now)) { delivery.detail = "held for quiet hours"; return end; } } } // next_slot returns now when there is room, so "later than now" means // the window is full. if (const TimePoint slot = limiter_.next_slot(record.user, delivery.channel, now); slot > now) { delivery.detail = "held by the rate limit"; return slot; } return std::nullopt; // no reason to wait: attempt it now}
// Called from a timer. Takes the earliest entries in due_, one at a// time, while they are due (at or before now), and attempts each.std::size_t Notifier::run_due() { const TimePoint now = clock_->now(); // read once: an attempt scheduled now is for later std::size_t made = 0; // An attempt schedules its retry after now (every delay is positive), // and a hold ends after now, so this loop ends. while (!due_.empty() && due_.begin()->first <= now) { const Key key = due_.begin()->second; // a copy, so erasing the entry cannot spoil it due_.erase(due_.begin()); // erased first: attempt may add a new entry // Counted only if the provider was really called, not for a hold. // records_.at(key) would throw if absent; every due key has a record. if (attempt(records_.at(key))) ++made; } return made;}How this code works: What changed in attempt, held_until, and run_due
Compared with step 1:
- A check comes first. For a kind that is not required,
attemptasksheld_until. If it returns a time, the delivery goes back intodue_for that time, andattemptreturnsfalsebefore++delivery.attempts. The outcome stayspending, the count stays the same, and only the detail changes, to say why it waits. held_untilasks two questions, in order. For a text or a push (never an email): does the user have quiet hours, and is now inside them? If so, the answer is the end of the period. Then, for any channel: doesnext_slotname a time after now? If so, that time. Otherwisestd::nullopt, and the attempt goes ahead exactly as in step 1.- A sent message is recorded in the limiter, required or not, so required messages use up room in the window even though they are never held.
attemptreturnsbool.run_duecounts only the calls that returnedtrue, so a delivery that is held again is not counted.notifydoes not need the answer and discards it withstatic_cast<void>.
A trace: AC-7.6, quiet hours 10:00 to 11:00 UTC, no rate limits.
| When | Called from | held_until |
attempts |
Result |
|---|---|---|---|---|
| 09:59:50 | notify |
not quiet: nullopt |
1 | push unavailable: due 10:00:20 |
| 10:00:20 | run_due |
quiet until 11:00 | 1 | held: due 11:00, run_due returns 0 |
| 11:00:00 | run_due |
11:00 is not quiet | 2 | sent, run_due returns 1 |
The retry that falls inside quiet hours costs no attempt: the push is sent on attempt two, as if quiet hours had never delayed it.
attempt now asks held_until first, unless the kind is required. A
hold schedules the delivery again, at the end of the quiet period or at
the next free slot, and returns before counting an attempt (FR-9).
The two checks run in a fixed order: quiet hours first, then the limit.
So texts held through quiet hours meet the limit when the period
ends, and only the first three go (AC-8.6 holds five texts until 10:00
and checks that).
The schedule needed no change. A hold is one more reason to put a
delivery in due_, and run_due already runs whatever is due. Its
loop still ends, because a hold is always for a time after now:
quiet_until returns the end of a period that contains now, and
held_until holds for a slot only when it is later than now.
Preferences are now read at two times, on purpose. Opt-out is
decided once, in notify: a user who turns texts back on does not get
last week’s skipped messages. Quiet hours are read at each attempt: a
user who changes them gets the change on deliveries that are still
waiting. A delivery already held keeps its time, though; if the user
clears their quiet hours, a held text still waits until the old period
ends.
run_due now returns the number of attempts it actually made, so a
delivery held again is not counted. The step 2 tests use that to tell
a hold from an attempt.
Step 2 tests
Section titled “Step 2 tests”The step 1 tests run unchanged against step 2, except for the new constructor argument. Then:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The tests use the step 1 helpers. World is the same bundle of clock,// fakes, catalog, preferences, and notifier, and World(limits) takes// rate limits (none by default). The clock starts at `start`, Monday// 2 March 2026, 09:00 UTC; `monday` (above) is that day's midnight.// LLD_TEST, LLD_CHECK, LLD_CHECK_EQ, and LLD_CHECK_THROWS come from the// site's test header, as on the step 1 tests.//// Quiet hours 08:00 to 10:00 UTC (offset 0), and a payment fails at// 09:00. The email goes; the text and push are held, with no attempt// used, until 10:00, and then each is sent on its first attempt.LLD_TEST(ac_7_1_texts_and_pushes_wait_for_quiet_hours_to_end) { World w; w.preferences.set_quiet_hours("u-7", {8h, 10h, 0min}); const std::vector<Delivery> got = w.notifier.notify(payment()); LLD_CHECK_EQ(got.at(0).outcome, Outcome::sent); // email is not held for (const Delivery& d : {got.at(1), got.at(2)}) { // the text and the push LLD_CHECK_EQ(d.outcome, Outcome::pending); LLD_CHECK_EQ(d.attempts, 0); // a hold is not an attempt LLD_CHECK_EQ(d.detail, std::string("held for quiet hours")); } LLD_CHECK(w.texts.delivered().empty() && w.push.delivered().empty()); w.clock.advance(59min); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{0}); w.clock.advance(1min); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{2}); // 10:00: quiet hours are over const Delivery* sms = w.notifier.find(payment().id, Channel::sms); LLD_CHECK_EQ(sms->outcome, Outcome::sent); LLD_CHECK_EQ(sms->attempts, 1); LLD_CHECK(sms->updated == start + 1h);}
// quiet_until on its own, for 22:00 to 07:00 at UTC: inside the period// it returns the next 07:00 (tomorrow's if it is evening); outside it,// an empty optional, so !quiet_until(...) is true. The start is inside// and the end is not, checked to the second.LLD_TEST(ac_7_2_quiet_hours_may_cross_midnight) { const QuietHours night{22h, 7h, 0min}; LLD_CHECK(quiet_until(night, monday + 23h) == TimePoint{monday + days{1} + 7h}); LLD_CHECK(quiet_until(night, monday + 3h) == TimePoint{monday + 7h}); LLD_CHECK(quiet_until(night, monday + 22h) == TimePoint{monday + days{1} + 7h}); // the start is quiet LLD_CHECK(quiet_until(night, monday + 6h + 59min + 59s) == TimePoint{monday + 7h}); LLD_CHECK(!quiet_until(night, monday + 7h)); // the end is not LLD_CHECK(!quiet_until(night, monday + 21h + 59min)); LLD_CHECK(!quiet_until(night, monday + 12h));}
// A period that does not cross midnight: 13:00 to 14:00.LLD_TEST(ac_7_3_quiet_hours_may_lie_within_a_day) { const QuietHours lunch{13h, 14h, 0min}; LLD_CHECK(!quiet_until(lunch, monday + 12h + 59min)); LLD_CHECK(quiet_until(lunch, monday + 13h) == TimePoint{monday + 14h}); LLD_CHECK(quiet_until(lunch, monday + 13h + 30min) == TimePoint{monday + 14h}); LLD_CHECK(!quiet_until(lunch, monday + 14h)); LLD_CHECK(!quiet_until(lunch, monday + 1h));}
// The same 22:00 to 07:00, for users five hours behind UTC and five and// a half hours ahead. The time passed in and the answer are UTC; the// comments give the user's own clock.LLD_TEST(ac_7_4_quiet_hours_are_in_the_users_own_time) { const QuietHours east_coast{22h, 7h, -5h}; // UTC-5 LLD_CHECK(quiet_until(east_coast, monday + 9h) == TimePoint{monday + 12h}); // 04:00 there LLD_CHECK(!quiet_until(east_coast, monday + 13h)); // 08:00 there LLD_CHECK(!quiet_until(east_coast, monday + 2h)); // 21:00 Sunday there LLD_CHECK(quiet_until(east_coast, monday + 3h) == TimePoint{monday + 12h}); // 22:00 Sunday there const QuietHours india{22h, 7h, 5h + 30min}; // UTC+5:30 LLD_CHECK(quiet_until(india, monday + 17h) == TimePoint{monday + days{1} + 1h + 30min}); // 22:30 there LLD_CHECK(!quiet_until(india, monday + 9h)); // 14:30 there}
// A reset code is required, so its text goes during quiet hours.LLD_TEST(ac_7_5_a_required_kind_ignores_quiet_hours) { World w; w.preferences.set_quiet_hours("u-7", {8h, 10h, 0min}); const std::vector<Delivery> got = w.notifier.notify(reset()); LLD_CHECK_EQ(got.at(1).outcome, Outcome::sent); LLD_CHECK_EQ(w.texts.delivered().size(), std::size_t{1});}
// A push fails at 09:59:50, before quiet hours (10:00 to 11:00). Its// retry comes due at 10:00:20, inside them, so it is held, still at one// attempt, and made at 11:00 as attempt two. `push` points at the stored// record, so it shows the record's later state as the test goes on.LLD_TEST(ac_7_6_a_retry_that_falls_in_quiet_hours_waits_without_using_an_attempt) { World w; w.preferences.set_quiet_hours("u-7", {10h, 11h, 0min}); w.clock.advance(59min + 50s); // 09:59:50 w.push.fail_next(pushy::Result::unavailable); static_cast<void>(w.notifier.notify(shipped())); // the retry is due at 10:00:20 w.clock.advance(30s); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{0}); // held, not attempted const Delivery* push = w.notifier.find(shipped().id, Channel::push); LLD_CHECK_EQ(push->attempts, 1); LLD_CHECK_EQ(push->detail, std::string("held for quiet hours")); w.clock.advance(59min + 40s - 1s); // 10:59:59 LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{0}); w.clock.advance(1s); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{1}); LLD_CHECK_EQ(push->outcome, Outcome::sent); LLD_CHECK_EQ(push->attempts, 2);}
// set_quiet_hours refuses start equal to end, a time outside one day// (below 0 or at 24h), and an offset beyond 14 hours either way; a// refused call stores nothing. 14 hours exactly is allowed.LLD_TEST(ac_7_7_bad_quiet_hours_are_rejected) { Preferences preferences; LLD_CHECK_THROWS(preferences.set_quiet_hours("u-7", {7h, 7h, 0min}), std::invalid_argument); LLD_CHECK_THROWS(preferences.set_quiet_hours("u-7", {-1min, 7h, 0min}), std::invalid_argument); LLD_CHECK_THROWS(preferences.set_quiet_hours("u-7", {22h, 24h, 0min}), std::invalid_argument); LLD_CHECK_THROWS(preferences.set_quiet_hours("u-7", {22h, 7h, 14h + 1min}), std::invalid_argument); LLD_CHECK_THROWS(preferences.set_quiet_hours("u-7", {22h, 7h, -14h - 1min}), std::invalid_argument); LLD_CHECK(preferences.quiet_hours("u-7") == nullptr); preferences.set_quiet_hours("u-7", {22h, 7h, -14h}); LLD_CHECK(preferences.quiet_hours("u-7") != nullptr); preferences.clear_quiet_hours("u-7"); LLD_CHECK(preferences.quiet_hours("u-7") == nullptr);}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// payment_for(n) (above) is a payment-failed notification with its own// id, "pay-n", so the calls are not duplicates of each other.//// Three texts an hour. Texts at 09:00, 09:10, and 09:20 go; the fourth,// at 09:30, is held until 10:00, when the 09:00 text has been in the// window for a full hour and leaves it.LLD_TEST(ac_8_1_a_text_over_the_limit_waits_until_the_window_has_room) { World w({{Channel::sms, {3, 1h}}}); // the RateLimits map: {channel, {max, per}} for (int n = 0; n < 3; ++n) { // at 09:00, 09:10, 09:20 const std::vector<Delivery> got = w.notifier.notify(payment_for(n)); LLD_CHECK_EQ(got.at(1).outcome, Outcome::sent); w.clock.advance(10min); } const std::vector<Delivery> fourth = w.notifier.notify(payment_for(3)); // at 09:30 LLD_CHECK_EQ(fourth.at(1).outcome, Outcome::pending); LLD_CHECK_EQ(fourth.at(1).attempts, 0); LLD_CHECK_EQ(fourth.at(1).detail, std::string("held by the rate limit")); LLD_CHECK_EQ(fourth.at(0).outcome, Outcome::sent); // email and push have no limit LLD_CHECK_EQ(fourth.at(2).outcome, Outcome::sent); w.clock.advance(30min - 1s); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{0}); w.clock.advance(1s); // 10:00: the 09:00 text has left the window LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{1}); LLD_CHECK_EQ(w.texts.delivered().size(), std::size_t{4});}
// Two an hour. The window is "the last hour", not "this clock hour": the// fourth text waits for the 09:40 one to leave, at 10:40.LLD_TEST(ac_8_2_the_window_slides) { World w({{Channel::sms, {2, 1h}}}); static_cast<void>(w.notifier.notify(payment_for(0))); // 09:00 w.clock.advance(40min); static_cast<void>(w.notifier.notify(payment_for(1))); // 09:40 w.clock.advance(10min); static_cast<void>(w.notifier.notify(payment_for(2))); // 09:50, held until 10:00 w.clock.advance(10min); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{1}); // 10:00: sent; the window is 09:40, 10:00 static_cast<void>(w.notifier.notify(payment_for(3))); // held until 10:40, not 11:00 w.clock.advance(40min - 1s); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{0}); w.clock.advance(1s); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{1}); LLD_CHECK_EQ(w.texts.delivered().size(), std::size_t{4});}
// One text and one push an hour. Robin's first payment uses both; Sam's// (u-8) still goes, and Robin's second is held on both limited// channels, while its email goes.LLD_TEST(ac_8_3_limits_are_per_user_and_per_channel) { World w({{Channel::sms, {1, 1h}}, {Channel::push, {1, 1h}}}); w.preferences.set_contact("u-8", {"sam@example.com", "+15550111", "device-8"}); static_cast<void>(w.notifier.notify(payment_for(0))); Notification other = payment_for(1); other.user = "u-8"; const std::vector<Delivery> theirs = w.notifier.notify(other); LLD_CHECK_EQ(theirs.at(1).outcome, Outcome::sent); // another user's text const std::vector<Delivery> again = w.notifier.notify(payment_for(2)); LLD_CHECK_EQ(again.at(0).outcome, Outcome::sent); // email has no limit LLD_CHECK_EQ(again.at(1).outcome, Outcome::pending); LLD_CHECK_EQ(again.at(2).outcome, Outcome::pending);}
// One text an hour. Two required reset codes, at 09:00 and 09:10, both// go, so the log holds two. A payment text at 09:20 waits until both// have left the window, 10:10, not just the first (10:00).LLD_TEST(ac_8_4_a_required_kind_is_not_held_but_counts) { World w({{Channel::sms, {1, 1h}}}); static_cast<void>(w.notifier.notify(reset("reset-1"))); // 09:00 w.clock.advance(10min); const std::vector<Delivery> second = w.notifier.notify(reset("reset-2")); // 09:10, over the limit LLD_CHECK_EQ(second.at(1).outcome, Outcome::sent); w.clock.advance(10min); static_cast<void>(w.notifier.notify(payment())); // 09:20: waits for both to leave, at 10:10 w.clock.advance(50min - 1s); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{0}); w.clock.advance(1s); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{1}); LLD_CHECK_EQ(w.texts.delivered().size(), std::size_t{3});
// The limiter itself names the right moment at once, not the first // time that leaves the window. RateLimiter limiter({{Channel::sms, {1, 1h}}}); limiter.record("u-7", Channel::sms, start); limiter.record("u-7", Channel::sms, start + 10min); LLD_CHECK(limiter.next_slot("u-7", Channel::sms, start + 20min) == start + 1h + 10min);}
// A rejected text and a text waiting to retry were never accepted, so// neither counts: the third text is still the first in the window.LLD_TEST(ac_8_5_only_messages_sent_count) { World w({{Channel::sms, {1, 1h}}}); w.texts.fail_next("not a mobile number", false); static_cast<void>(w.notifier.notify(payment_for(0))); // rejected w.texts.fail_next("busy", true); static_cast<void>(w.notifier.notify(payment_for(1))); // waiting to retry const std::vector<Delivery> third = w.notifier.notify(payment_for(2)); LLD_CHECK_EQ(third.at(1).outcome, Outcome::sent);}
// Five payments at 09:00, during quiet hours (08:00 to 10:00). At 10:00// all are due together: five pushes (no limit) and the first three// texts go; the other two texts are held again until 11:00, when the// window has room. A hold is not counted, so run_due returns 8.LLD_TEST(ac_8_6_held_texts_meet_the_limit_when_quiet_hours_end) { World w({{Channel::sms, {3, 1h}}}); w.preferences.set_quiet_hours("u-7", {8h, 10h, 0min}); for (int n = 0; n < 5; ++n) static_cast<void>(w.notifier.notify(payment_for(n))); w.clock.advance(1h); // 10:00 LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{8}); // 3 texts and 5 pushes LLD_CHECK_EQ(w.texts.delivered().size(), std::size_t{3}); LLD_CHECK_EQ(w.notifier.pending(), std::size_t{2}); w.clock.advance(1h); LLD_CHECK_EQ(w.notifier.run_due(), std::size_t{2}); LLD_CHECK_EQ(w.texts.delivered().size(), std::size_t{5});}
// A max below 1 or a window that is not positive is refused, by the// limiter itself and so by the notifier that builds one.LLD_TEST(ac_8_7_bad_limits_are_rejected) { LLD_CHECK_THROWS(RateLimiter({{Channel::sms, {0, 1h}}}), std::invalid_argument); LLD_CHECK_THROWS(RateLimiter({{Channel::sms, {3, 0s}}}), std::invalid_argument); LLD_CHECK_THROWS(World({{Channel::push, {3, -1s}}}), std::invalid_argument);}
// Times recorded out of order (the wall clock was set back) are kept// sorted, so the 09:00 time is the oldest and leaves first, at 10:00.LLD_TEST(ac_8_8_the_log_stays_in_order_if_the_clock_is_set_back) { RateLimiter limiter({{Channel::sms, {2, 1h}}}); const TimePoint t = start; limiter.record("u-7", Channel::sms, t + 10min); limiter.record("u-7", Channel::sms, t); // the clock was set back ten minutes LLD_CHECK(limiter.next_slot("u-7", Channel::sms, t + 20min) == t + 1h); // when the older one leaves LLD_CHECK(limiter.next_slot("u-7", Channel::sms, t + 1h) == t + 1h); LLD_CHECK(limiter.next_slot("u-7", Channel::email, t) == t); // no limit}ac_7_6 is the interaction that a design review would miss: a retry
of a failed push comes due at 10:00:20, inside quiet hours. It must be
held without using up an attempt, and then made at 11:00 as attempt
two.
The random test gives the user quiet hours across midnight at UTC−5 and limits on texts and pushes, and makes 3,000 random steps in which time moves by up to two hours at a time, so the run crosses many nights:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 3,000 random steps over about three weeks: notifications (often// repeats), provider failures, and time passing, for a user at UTC-5 with// quiet hours and limits on texts and pushes. Then time runs on until// nothing is pending. Every delivery ends sent or failed; each sent one// reached its provider exactly once; no text or push that is not// required went out in quiet hours; and no window held more than the// limit of them. Fixed seed, so a failure repeats.LLD_TEST(inv_holds_and_retries_keep_every_rule) { // Three texts an hour, five pushes per half hour; nights at UTC-5. const RateLimits limits{{Channel::sms, {3, 1h}}, {Channel::push, {5, 30min}}}; const QuietHours quiet{22h, 7h, -5h}; World w(limits); w.preferences.set_quiet_hours("u-7", quiet); std::mt19937 random(2026); // pick(n): a pseudo-random whole number from 0 to n - 1, as in step 1. const auto pick = [&](int n) { return static_cast<int>(random() % static_cast<unsigned>(n)); }; // As in step 1, but time moves up to 7199 s (two hours) per step, and // about one notification in four is a required reset code. for (int step = 0; step < 3000; ++step) { switch (pick(6)) { case 0: w.mail.fail_next(pick(2) == 0 ? 503 : 400); break; case 1: w.texts.fail_next("busy", pick(2) == 0); break; case 2: w.push.fail_next(pick(2) == 0 ? pushy::Result::unavailable : pushy::Result::unregistered_device); break; case 3: w.clock.advance(seconds{pick(7200)}); static_cast<void>(w.notifier.run_due()); break; default: { const int n = pick(400); static_cast<void>(w.notifier.notify(pick(4) == 0 ? reset("reset-" + std::to_string(n)) : payment("pay-" + std::to_string(n)))); } } } // Holds can last a night, so allow up to 1000 steps of 600 s here. for (int i = 0; i < 1000 && w.notifier.pending() > 0; ++i) { w.clock.advance(600s); static_cast<void>(w.notifier.run_due()); } LLD_CHECK_EQ(w.notifier.pending(), std::size_t{0});
std::size_t sent[3] = {0, 0, 0}; // For each channel, when each text or push that is not required was // sent. Delivery::updated is the time of the attempt that sent it. std::map<Channel, std::vector<TimePoint>> held_back; // sends that the rules applied to int failed = 0; for (int n = 0; n < 400; ++n) { for (const std::string prefix : {"pay-", "reset-"}) { for (const Channel c : {Channel::email, Channel::sms, Channel::push}) { const Delivery* d = w.notifier.find(prefix + std::to_string(n), c); if (d == nullptr) continue; LLD_CHECK(d->outcome == Outcome::sent || d->outcome == Outcome::failed); LLD_CHECK(d->attempts >= 1 && d->attempts <= RetryPolicy{}.max_attempts); if (d->outcome == Outcome::failed) ++failed; if (d->outcome != Outcome::sent) continue; ++sent[static_cast<int>(c)]; if (prefix == "pay-" && c != Channel::email) { LLD_CHECK(!quiet_until(quiet, d->updated)); // not sent in quiet hours held_back[c].push_back(d->updated); } } } } LLD_CHECK(failed > 50); LLD_CHECK_EQ(w.mail.delivered().size(), sent[0]); LLD_CHECK_EQ(w.texts.delivered().size(), sent[1]); LLD_CHECK_EQ(w.push.delivered().size(), sent[2]); // No window (t - per, t] ending at such a send holds more than max of them. // For each send at times[i], count the sends in the window that ends // there, (times[i] - per, times[i]]. In the sorted list, upper_bound // finds the first time after a value, so the two calls mark the // window's ends, and subtracting the iterators gives the count. for (auto& [channel, times] : held_back) { const RateLimit limit = limits.at(channel); std::sort(times.begin(), times.end()); for (std::size_t i = 0; i < times.size(); ++i) { const auto window_begin = std::upper_bound(times.begin(), times.end(), times[i] - limit.per); const auto window_end = std::upper_bound(times.begin(), times.end(), times[i]); LLD_CHECK(window_end - window_begin <= limit.max); } LLD_CHECK(times.size() > 50); // the rules were really exercised }}It checks the two new rules from the records alone: no text or push of
a kind that is not required was sent in quiet hours, and no window of
the limit’s length holds more than max of them.
Checking the tests. 20 mutations of the step 2 code were run the same way. The first run left four alive. Two exposed missing tests, which were then added: an offset below −14 hours was accepted, and the limiter’s answer when required messages fill the window was never checked directly (through the notifier, a hold that is too short just holds again). The other two cannot be seen from outside. Pruning a time that is exactly one window old, or not, gives the same answer, because a time at the boundary yields a slot of exactly now. Not erasing an empty log changes only memory. With the two new checks, 18 of the 20 fail at least one test.
The step 2 demo
Section titled “The step 2 demo”Robin is at UTC−5, with quiet hours from 22:00 to 07:00, and texts are limited to three an hour. The times printed are Robin’s.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The composition root, as in step 1: it owns every object, and// declares each one before the objects that refer to it. The clock// starts on 2 March 2026 at 09:00 UTC. Two helpers above main:// time_there prints a time on Robin's clock, and payment("1002")// makes a payment-failed notification for Robin and that order.ManualClock clock(sys_days{year{2026} / 3 / 2} + 9h); // 04:00 for Robinacme_mail::Client mail;textly::Gateway texts;pushy::Api push;const Catalog catalog = shop_catalog();Preferences preferences;preferences.set_contact("u-7", {"robin@example.com", "+15550100", "device-7"});const minutes offset = -5h;preferences.set_quiet_hours("u-7", {22h, 7h, offset}); // 22:00 to 07:00, Robin's time
std::vector<std::unique_ptr<Sender>> senders;senders.push_back(std::make_unique<EmailSender>(mail, "shop@example.com"));senders.push_back(std::make_unique<SmsSender>(texts));senders.push_back(std::make_unique<PushSender>(push));// The new argument is the RateLimits map: {{channel, {max, per}}}, so// at most three texts an hour; email and push have no limit.Notifier notifier(catalog, preferences, clock, RetryPolicy{}, {{Channel::sms, {3, 1h}}}, std::move(senders));
std::cout << time_there(clock.now(), offset) << ", payment failed:\n";print(notifier.notify(payment("1002")));
std::cout << time_there(clock.now(), offset) << ", password reset (required):\n";print(notifier.notify({"reset-88", "u-7", "password-reset", {{"code", "493817"}}}));
clock.advance(3h);std::cout << time_there(clock.now(), offset) << ", " << notifier.run_due() << " held deliveries go:\n";// Copies of the two stored Deliveries, read after run_due made the attempts.print({*notifier.find("order-1002-payment", Channel::sms), *notifier.find("order-1002-payment", Channel::push)});
clock.advance(10min);std::cout << time_there(clock.now(), offset) << ", three more payments fail; the texts:\n";// .at(1) is the second Delivery, the text (the kind's channels are// email, sms, push, in that order).for (const char* order : {"1003", "1004", "1005"}) print({notifier.notify(payment(order)).at(1)});
clock.advance(50min);std::cout << time_there(clock.now(), offset) << ", " << notifier.run_due() << " held delivery goes:\n";print({*notifier.find("order-1005-payment", Channel::sms)});
std::cout << "providers delivered: " << mail.delivered().size() << " emails, " << texts.delivered().size() << " texts, " << push.delivered().size() << " pushes\n";04:00, payment failed: email: sent after 1 attempt (status 202) sms: pending (held for quiet hours) push: pending (held for quiet hours)04:00, password reset (required): email: sent after 1 attempt (status 202) sms: sent after 1 attempt07:00, 2 held deliveries go: sms: sent after 1 attempt push: sent after 1 attempt07:10, three more payments fail; the texts: sms: sent after 1 attempt sms: sent after 1 attempt sms: pending (held by the rate limit)08:00, 1 held delivery goes: sms: sent after 1 attemptproviders delivered: 5 emails, 5 texts, 4 pushes- At 04:00 the payment email goes, and the text and push wait for 07:00. The reset code is required, so its text goes at once.
- At 07:00 both held deliveries go, each as its first attempt.
- At 07:10 three more payments fail. The reset text from 04:00 has left the window, so the window holds only the 07:00 text; two more fit, and the third is held until 08:00, an hour after the 07:00 text.
- At 08:00 the held text goes.
Presenting it in an interview
Section titled “Presenting it in an interview”A plan for 45 minutes, using the time boxes from The design workflow:
| Time | What to do | What to say |
|---|---|---|
| About 5 min | Ask which channels and providers, who owns the wording, what users can turn off, what is required, why duplicates happen, how late is too late. | “When the caller times out and tries again, is that the same notification?” |
| 5 min | Sketch Notification, Message, Sender with three adapters, Catalog, Preferences, and the Notifier. Say who owns what. |
“The notifier owns its senders; it only refers to the catalog and preferences, which outlive it.” |
| 10–15 min | Write Sender and one adapter, then notify in two loops, then attempt with its three outcomes. State INV-1 and INV-2. |
“Render everything first: a message that has gone cannot be taken back.” |
| 10 min | Retries as a schedule and run_due, a clock you can move, and the idempotency key. Walk the trace with a failed push and a repeat. |
“The id names the event, so a repeat is a duplicate. A lost SMS reply still means two texts.” |
| About 5 min | Take a change: quiet hours, rate limits, or a fallback channel. | “Both are about when to attempt, so they go in front of the attempt, and a hold does not use up a retry.” |
What is usually expected at each level
| Level | Usually expected |
|---|---|
| Junior | An interface for channels with one class per channel; templates with placeholders; skipping a channel the user turned off; a retry for a failed send; a few tests with fake channels. |
| Mid-level | All of the above, plus: retryable and permanent failures kept apart; a limit on attempts with growing waits; an idempotency key from the caller; a record per channel; preferences and required kinds; time from an injected clock. |
| Senior | All of the above, plus: rendering before sending, and why; retries as a schedule, not a sleep; idempotency per (id, channel); where exactly once stops, and the provider’s deduplication key; quiet hours across midnight; a rate limit and its algorithm; persistence of records and the schedule. |
These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.
Production limitations
Section titled “Production limitations”- Records live in memory. A restart forgets every record and every scheduled retry: pending messages are lost, and a caller’s repeat after the restart is sent again. A real service writes the record (with the message) to a database before the first attempt, in the same transaction as anything else it decides, and reads the schedule back on start-up.
- Records are never removed. Every id ever sent stays in
records_. A real store keeps records for as long as a repeat is plausible (days, not years), and a caller must not reuse an id after that. - SMS is at least once. A lost reply means a second text (AC-5.4). The fix is on the provider’s side.
- One thread.
Notifieris not thread-safe, and each provider’s client is called on the caller’s thread, so a slow provider still slowsnotifyfor its first attempt. A busy service would give each channel its own worker and queue. - Wall-clock time. Retries and holds are scheduled in wall-clock
time. If the clock is set forward, retries come early; set back, they
come late. The quiet hours need wall-clock time; the retry delays
would be better measured on
std::chrono::steady_clock. - Fixed UTC offsets. Quiet hours drift by an hour across daylight saving time changes, as the warning above says.
- Rate-limit logs for quiet users. A log is removed only when it is
next checked and found empty, so a user who stops receiving messages
leaves up to
maxtimes behind per channel. - No jitter. Many deliveries that failed in the same second retry
in the same second. With many users, add random jitter to
backoff, as Why jitter? explains. - The fakes are kind. Real providers also time out without answering at all, and an adapter needs a deadline on each call. The fakes always return at once.
Traceability
Section titled “Traceability”| Requirement | Design element | Code | Tests | Status |
|---|---|---|---|---|
| FR-1 send by kind | Catalog, Template::render, Notifier::notify |
step 1 catalog.*, notifier.cpp |
ac_1_1_…, ac_1_2_…, ac_1_5_…, ac_1_6_… |
Tested |
| FR-2 all or nothing up front | notify’s two loops |
step 1 notifier.cpp |
ac_1_3_…, ac_1_4_…, ac_6_2_… |
Tested |
| FR-3 preferences | Preferences, Kind::required, the first loop |
step 1 preferences.hpp, notifier.cpp |
ac_2_1_… to ac_2_5_… |
Tested |
| FR-4 retries | SendStatus, RetryPolicy, backoff, due_, run_due |
step 1 sender.hpp, notifier.* |
ac_3_1_… to ac_3_3_…, ac_4_1_… to ac_4_6_…, random test |
Tested |
| FR-5 once per event and channel | records_ keyed by (id, channel); email dedupe key |
step 1 notifier.cpp, adapters.cpp |
ac_3_4_…, ac_5_1_… to ac_5_4_…, random test |
Tested |
| FR-6 records | Delivery, find |
step 1 notifier.hpp |
most tests read records through find |
Tested |
| NFR-1 providers replaceable | Sender and three adapters |
step 1 sender.hpp, adapters.* |
ac_4_5_… puts in a different sender; nothing else in the notifier names a provider |
Tested |
| NFR-2 caller does not wait | one attempt in notify, the rest in run_due |
step 1 notifier.cpp |
ac_4_1_…, ac_5_2_… |
Tested |
| NFR-3 testable time | Clock, ManualClock |
step 1 clock.hpp |
every retry test; none sleeps | Tested |
| NFR-4 not thread-safe | documented on each class | step 1 headers | none: a statement, not a behaviour | Stated |
| FR-7 quiet hours | QuietHours, quiet_until, held_until |
step 2 quiet_hours.*, notifier.cpp |
ac_7_1_… to ac_7_7_…, step 2 random test |
Tested |
| FR-8 rate limits | RateLimiter, held_until, record on sent |
step 2 rate_limiter.*, notifier.cpp |
ac_8_1_… to ac_8_8_…, step 2 random test |
Tested |
| FR-9 a hold is not an attempt | attempt returns before counting |
step 2 notifier.cpp |
ac_7_1_…, ac_7_6_…, ac_8_1_… |
Tested |
Exercise
Section titled “Exercise”Exercise: Tell others when a delivery ends
Support wants an audit log of every final outcome, and the metrics team wants a count of failures per channel. Neither should be part of the notifier, and the notifier should not know they exist. Add a way for other code to hear about each delivery when its outcome becomes final. Start from step 2.
- What should the notifier know about the audit log and the metrics? What is the type of the thing it calls?
- Which outcomes are reported, and from which two places in the code? Should a duplicate be reported? A hold?
- Write it.
- What should happen if a listener throws?
- May a listener call
notify? Look at whatattemptandrun_duehold while a listener runs.
Show the explained answer
-
Nothing but a function to call. This is Observer: the notifier publishes “this delivery is final”, and listeners subscribe. With one event and no need to unsubscribe, a
std::function<void(const Delivery&)>is enough; an interface with one virtual function would also do, and would suit a listener with several events. The notifier keeps the functions in a vector. Astd::functionowns what it captures by value, but not what it refers to by reference or pointer: a listener that captures a reference to the audit log needs the log to outlive the notifier. -
The four final outcomes, once each.
sentandfailedbecome final inattempt, at the end, where the message is dropped.turned offandno addressare final from the start, innotify’s second loop. A duplicate is not a new outcome, so it is not reported; a hold or a retry is not final, so neither is reported. -
One way, in
notifier.hpp:IllustrativeA fragment for explanation; not compiled on its own.
// Called once for each delivery whose outcome becomes final: sent,// failed, turned off, or no address. Not for a duplicate, a hold, or// a retry. The Delivery is valid only during the call. A listener// must not call on_final; it may call notify with an id other than// the one being reported. Register listeners// before the first notify.using Listener = std::function<void(const Delivery&)>;void on_final(Listener listener) { listeners_.push_back(std::move(listener)); }[[nodiscard]] std::size_t listener_failures() const noexcept { return listener_failures_; }// private:void report(const Delivery& delivery) noexcept;std::vector<Listener> listeners_;std::size_t listener_failures_ = 0;and in
notifier.cpp, innotify’s second loop and at the end ofattempt:IllustrativeA fragment for explanation; not compiled on its own.
// in notifyif (stored.delivery.outcome == Outcome::pending) {static_cast<void>(attempt(stored));} else {report(stored.delivery); // turned off, or no address: final already}// at the end of attemptrecord.message = Message{}; // the outcome is final: the text is no longer neededreport(delivery);return true;// A listener that throws must not stop or undo a delivery: the state is// already updated, and the caller of notify or run_due could not tell// which channels went out.void Notifier::report(const Delivery& delivery) noexcept {for (const Listener& listener : listeners_) {try {listener(delivery);} catch (...) {++listener_failures_;}}} -
Catch it, count it, and carry on. By the time a listener runs, the message has gone and the record says so. If the exception left
notify, the caller would see a failure for a call that sent messages, and the channels after this one would be neither stored nor sent; a retry with the same id would then send those and report the rest as duplicates. If it leftrun_due, the remaining due deliveries would wait for the next tick. Neither is what an audit log’s bad day should cause. Soreportcatches everything, counts it inlistener_failures()for the metrics, and calls the remaining listeners. Makingreportnoexceptdocuments that nothing escapes. -
Yes, with a different id, and it is worth checking why. A listener runs inside
attempt, which holds a reference to aRecordinrecords_, and insiderun_due’s loop. A nestednotifyadds torecords_anddue_. Astd::mapand astd::multimapnever move their elements on insert, so the reference stays valid.run_dueholds no iterator while it callsattempt: it copies the key and erases the entry first, and readsbegin()again on each turn. With astd::vectorof records, the same nested call could reallocate it and leaveattemptholding a dangling reference. What a listener must not do is callon_final:push_backcan reallocatelisteners_whilereportiterates over it, and destroy the very function that is running. The comment says so.The id matters too. A listener for a
turned offdelivery runs insidenotify’s second loop, before the later channels of the same notification are stored. If it callednotifywith that id, the nested call would store and attempt those channels, and the outer loop would then find itsemplacerefused and attempt the stored record a second time: a stray entry indue_and a second report. So the comment allowsnotifyonly with another id. A listener that wants a fallback (a text when a push fails for good) makes one, such as"fallback-" + delivery.id. A sturdier notifier would treat a refusedemplacein the second loop as a duplicate.
This answer was checked in a scratch copy of step 2; it is not part of
the example in the repository. With these changes, four new tests (each
final outcome reported once, holds not reported and a failure reported,
a throwing listener that stops nothing, and a listener that calls
notify with a new id for a fallback text) passed along with the other
step 2 tests under GCC, Clang, and AddressSanitizer with
UndefinedBehaviorSanitizer. A reviewer also reproduced the problem with
a nested notify for the same id.
Summary
Section titled “Summary”- Put each provider behind an adapter that turns its own way of failing into one small answer: sent, retry later, or rejected.
- Let callers say what happened (a kind and fields), and own the wording in templates that are checked when they are made.
- Decide and render every channel before sending any. A message that has gone cannot be taken back, so it must come after everything that can fail.
- The caller’s id names the event. Keyed by (id, channel), records make a repeat harmless and tell support what happened.
- Schedule retries; do not sleep. A schedule is data that can be counted, tested with a manual clock, and later saved.
- Exactly once ends at the provider. With a deduplication key, a lost reply means one email; without one, two texts. Test the limit and write it down.
- Rules about when to send, such as quiet hours and rate limits, go in front of the attempt, and a hold must not use up a retry.