Event-driven application components
What you will learn on this page
Section titled “What you will learn on this page”- How to decide which work belongs in a use case and which is a reaction that can follow from an event.
- How to give a program a closed, typed set of events, and named subscribers wired once at start-up, in C++.
- What changes between synchronous dispatch, where handlers run
inside
publish, and queued dispatch, where they run later: ordering, failures, and what the caller can assume. - How to retry a failed subscriber without repeating the ones that succeeded.
- What events cost in debugging, and how a trace of causes helps.
- When calling the other component directly is the better design.
The problem: a use case that calls everyone
Section titled “The problem: a use case that calls everyone”The registrar’s program enrolls students. Then billing wants to charge a fee for each seat, and students want a message when they get a seat, join the waitlist, or are charged. The first version adds each reaction to the use case.
Its problems show as the reactions grow:
- Every new reaction changes the use case. An SMS, a statistics
board, or an audit log each adds a dependency and a few lines to
enroll, and the same lines todrop, which promotes students too. - A failure in a reaction fails the command. If the mail server is
down,
sendthrows, and the student, who did get a seat, is told the enrollment failed. - The use case knows what billing does. The charge message is billing’s business, but it is written here, so a change to how fees work changes enrollment.
Events turn this around: the use case announces what happened, and each reaction subscribes to it. The rest of this page is about what that costs.
Step 1: classify the work
Section titled “Step 1: classify the work”Ask of each piece of work: must it succeed for the command to succeed, and does the caller need its result in the reply?
| Work | Must succeed with the command? | Reply needs it? | Where |
|---|---|---|---|
| Seat the student or add to waitlist | yes, it is the command | yes | the use case and the course |
| Charge the fee | it must happen, but can follow | no | a reaction to a seat |
| Tell the student | no; it can be retried | no | a reaction to each event |
| Tell the student about the charge | no | no | a reaction to billing’s event |
- Work that is the command, or whose result goes in the reply, stays in the use case. If the rule “a student may not have unpaid fees” decided whether to seat them, billing would be called directly, before the seat.
- Work that follows from what happened, and that the command should not wait for or fail because of, is a reaction.
- A reaction can publish its own event. Billing announces
FeeCharged, and the notifier reacts to that, so the use case does not know that a charge exists.
The components, and what each knows:
app::Enrollment, the use case: knows the course and aPublisher, not who listens.billing::Billing: knows the course’s events and publishes its own.notify::Notifier: knows the events it words. It does not call or include billing’s class, but it does namebilling::FeeCharged, so it knows that billing exists.- A dispatcher: knows who subscribed to what, and decides when handlers run. The example has two.
The events: a closed list of types
Section titled “The events: a closed list of types”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Every event the application passes between its components. A closed// list: a handler for a type that is not here does not compile, and a// new event is one more line here.// A std::variant holds exactly one of the listed types at a time and// remembers which. The first three are the course's own events from the// domain; FeeCharged is billing's. An Event holds its data by value, so// a queued Event stays valid after whatever published it is gone.using Event = std::variant<domain::StudentSeated, domain::StudentWaitlisted, domain::StudentPromoted, billing::FeeCharged>;
// One line of text for an event, used in the queued dispatcher's trace.std::string describe(const Event& event); // "S1 seated in CS101"
// What a handler may do with the dispatcher it was called from: publish// follow-up events. It cannot subscribe or run the queue.// An interface: `= 0` makes publish pure virtual, so each dispatcher// (SyncDispatcher, QueuedDispatcher) supplies its own version, and the use// case calls whichever one it was given without knowing which.class Publisher {public: // Takes the event by value: the dispatcher gets its own copy (or a // moved one) and can keep it as long as it likes. virtual void publish(Event event) = 0;
protected: // Protected and non-virtual: code that only has a Publisher& cannot // delete the dispatcher through it. Nobody owns a dispatcher through // this interface; it is only lent to use cases and handlers. ~Publisher() = default;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An event billing publishes, not the course: a fact about money.// Like the course's events, it is a plain struct of values (ids and an// amount), in the past tense, so it can be copied into a queue safely.struct FeeCharged { domain::StudentId student; domain::CourseCode course; int amount;};Eventis astd::variant, so every event the program passes is listed in one place. The event bus on the Observer vs Mediator page warned about payloads stored asstd::anyand cast back at run time; here, subscribing to a type that is not in the list does not compile.- Events are values that own their data: ids and numbers, not references to the course. That matters as soon as an event is queued, because the publisher’s objects may have changed or gone by the time it is handled.
- Events are facts in the past tense,
StudentSeated, not instructions likeChargeFee. The publisher says what happened; each subscriber decides what that means for it. Publisheris all a handler gets. It can publish a follow-up event, but it cannot subscribe, or run the queue from inside a handler.
The cost of a closed list is that every component that names Event
is rebuilt when an event type is added. Between separately built
parts, such as plug-ins, an open set of events behind a base class can
be the better trade; Plugin architecture
covers that boundary.
Subscribers: named, typed, wired once
Section titled “Subscribers: named, typed, wired once”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Who handles what, filled in once at start-up and then only read. Each// handler has a name, used in traces and failure records.// Both dispatchers read the same Subscribers, so the wiring is written once.class Subscribers {public: // Subscribes `handle` to events of type E, as in // on<domain::StudentSeated>("billing", ...). E is a template parameter // the caller writes in the angle brackets. std::function can hold any // callable with the right signature, such as a lambda. The typed // handler is wrapped in an untyped one that takes any Event, so all // entries can live in one vector whatever type each one wants. template <typename E> void on(std::string handler, std::function<void(const E&, Publisher&)> handle) { // The wrapper lambda keeps its own `handle`: the init-capture // `handle = std::move(handle)` moves the std::function into it. entries_.push_back( {std::move(handler), [handle = std::move(handle)](const Event& event, Publisher& out) { // std::get_if gives a pointer to the E inside the variant // if it holds an E right now, and nullptr if it holds any // other type. It does not compile if E is not in Event. const E* wanted = std::get_if<E>(&event); // E must be one of Event's types if (wanted == nullptr) return false; // not this handler's type: skip handle(*wanted, out); // may publish follow-up events through `out` return true; }}); }
// One subscription: the handler's name, and the wrapper that calls it. struct Entry { std::string handler; // Returns false, and does nothing, for an event of another type. std::function<bool(const Event&, Publisher&)> call; }; const std::vector<Entry>& entries() const { return entries_; } // in subscription order
private: std::vector<Entry> entries_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Start-up wiring: the one place that knows which component reacts to which// event. For any one event, its handlers run in the order of these calls,// so billing's handler runs before the notifier's. The lambdas capture billing// and the notifier by reference ([&billing], [¬ifier]), so the// subscriptions hold no copies and own nothing; the components must outlive// every dispatcher that uses these subscriptions.void wire(events::Subscribers& subscribers, billing::Billing& billing, notify::Notifier& notifier) { using events::Publisher; // lets the lambdas write Publisher, not events::Publisher // `const auto& event` is a generic lambda parameter; with on<E> the // event is a const E&. Billing gets `out` so it can publish FeeCharged. subscribers.on<domain::StudentSeated>( "billing", [&billing](const auto& event, Publisher& out) { billing.seated(event, out); }); subscribers.on<domain::StudentPromoted>( "billing", [&billing](const auto& event, Publisher& out) { billing.promoted(event, out); });
// One generic lambda, used for four event types: each on<E> below turns // it into a std::function for that E, and notifier.handle(event) then // picks the handle overload for that type. The notifier publishes // nothing, so the Publisher parameter is left unnamed. const auto tell = [¬ifier](const auto& event, Publisher&) { notifier.handle(event); }; subscribers.on<domain::StudentSeated>("notifier", tell); subscribers.on<domain::StudentWaitlisted>("notifier", tell); subscribers.on<domain::StudentPromoted>("notifier", tell); subscribers.on<billing::FeeCharged>("notifier", tell);}How this code works: The list that wire builds, and one event through it
wire makes six calls to on, so entries() holds six entries, in
this order. The index is the position in the vector; a queued failure
records it.
| Index | Name | Type the entry accepts | What it calls |
|---|---|---|---|
| 0 | billing |
StudentSeated |
billing.seated(event, out) |
| 1 | billing |
StudentPromoted |
billing.promoted(event, out) |
| 2 | notifier |
StudentSeated |
notifier.handle(event) |
| 3 | notifier |
StudentWaitlisted |
notifier.handle(event) |
| 4 | notifier |
StudentPromoted |
notifier.handle(event) |
| 5 | notifier |
FeeCharged |
notifier.handle(event) |
What one call, on<domain::StudentSeated>("billing", …), does:
- The type is written out. A lambda is not a
std::function, so the compiler cannot deduceEfrom it;on<domain::StudentSeated>names it. The lambda is then converted to the parameterhandle, astd::function<void(const domain::StudentSeated&, Publisher&)>. - A wrapper is made around it. The wrapper takes any
Event, andhandleis moved into the wrapper’s capture. The wrapper becomes the entry’scall, astd::functionthat takes anEventand returnsbool, and the entry is appended with the name"billing". - Later, a dispatcher calls every entry with every event. For an
Eventthat holdsStudentSeatedfor S1,std::get_iffinds it in entries 0 and 2, which call their handlers and returntrue; the other four get a null pointer and returnfalsewithout calling anything. AFeeChargedevent reaches only entry 5.
Who owns what: the Subscribers object owns the vector, each entry owns
its std::function, and that owns a copy of the lambda. The lambdas
hold only references to billing and notifier; tell is copied into
four entries, and all four copies refer to the same notifier. Nothing
here keeps billing or the notifier alive, which is why main declares
them before the subscribers and the dispatcher.
- Each handler is registered for one event type and is only called
with that type.
std::get_if<E>is what checks it, and it does not compile ifEis not one ofEvent’s types. - Each handler has a name, so a trace and a failure record can say which reaction ran or failed. Without names, a failure in a queue is “something threw”.
- All the wiring is in one function, called from the composition
root, as on the composition root
page. This is the answer to “what happens when a student gets a
seat?”: read
wire, rather than searching the program for subscribers. - The order of subscription is the order handlers run for one event. Billing is subscribed first, and the next section shows that this order can be visible to users.
Lifetimes are simpler than for screens. On the MVC, MVP, and
MVVM page, views came and went, so every
subscription was an object that disconnected on destruction. Here,
billing and the notifier live as long as the program. They are created
first, the subscriptions are made once, and nothing unsubscribes. The
lambdas capture billing and notifier by reference. Inside wire
those names are themselves references, and capturing a reference by
reference refers to the object it is bound to, so the lambdas still
work after wire returns. Both objects must outlive every dispatcher
that uses the subscriptions; main declares them first for that
reason. A component that can be removed while the
program runs needs a subscription handle again.
The publisher and the reactions
Section titled “The publisher and the reactions”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The use cases. It changes the course, then publishes what the course// recorded. It does not know who listens, or whether they run now or// later: that depends on the Publisher it is given.// Owns one Course by value (the example has a single course), and borrows// the Publisher.class Enrollment {public: // `publisher` must outlive this object. // The course is taken by value and moved in, so the Enrollment owns it. Enrollment(domain::Course course, events::Publisher& publisher) : course_{std::move(course)}, publisher_{&publisher} {}
// Each returns a reply starting "ok:" or "refused:". If a synchronous // handler throws, the exception comes out of these calls instead, after // the course has already changed. std::string enroll(const domain::StudentId& student); std::string drop(const domain::StudentId& student); const domain::Course& course() const { return course_; }
private: // Hands every event the course has recorded to the publisher, oldest // first. void publish_recorded();
domain::Course course_; events::Publisher* publisher_; // non-owning, never null};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The use case: change the course, publish what it recorded, word the// reply. It names no billing and no notifier; whatever reacts is decided by// the wiring and the dispatcher behind publisher_.std::string Enrollment::enroll(const domain::StudentId& student) { // The course decides and records an event (none for a refusal). const domain::JoinResult result = course_.enroll(student); publish_recorded(); // after the change, so handlers see the new state const std::string who = student.text(); const std::string what = course_.code().text(); switch (result) { case domain::JoinResult::seated: return "ok: " + who + " has a seat in " + what; case domain::JoinResult::waitlisted: return "ok: " + who + " is waiting for " + what; case domain::JoinResult::already_in_course: break; } return "refused: " + who + " is already in " + what;}
void Enrollment::publish_recorded() { // With a synchronous publisher, a handler that throws leaves here at // once: the course has changed, and any later events are lost. // take_events empties the course's list and returns it; the returned // vector lives until the loop ends. `event` is not const because each // one is moved out below. for (domain::CourseEvent& event : course_.take_events()) { // A CourseEvent has three possible types and an events::Event has // four, so one cannot be passed as the other directly. std::visit // calls the generic lambda with the concrete struct inside (for // example a StudentSeated&), and publish's Event parameter is made // from it. std::move hands over the ids instead of copying them. std::visit([this](auto& recorded) { publisher_->publish(std::move(recorded)); }, event); }}The use case changes the course first, then publishes what the
course recorded. An event therefore describes a change that has
already happened, and a handler that asked the course would see the
new state. An event is never published for a change that did not
happen. The comment in
publish_recorded is a real limit of the synchronous case, shown
below.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Charges the course fee whenever a student gets a seat, and announces// the charge. It knows the course's events, not the course.// Each handler takes the event and the Publisher of the dispatcher that// called it, so billing can announce FeeCharged without knowing which// dispatcher that is.class Billing {public: explicit Billing(int fee) : fee_{fee} {}
// Both charge the fee: a seat taken directly and a seat taken by // promotion from the waitlist cost the same. A waitlist place costs // nothing, so there is no handler for StudentWaitlisted. void seated(const domain::StudentSeated& event, events::Publisher& out); void promoted(const domain::StudentPromoted& event, events::Publisher& out);
const std::vector<FeeCharged>& charges() const { return charges_; }
private: void charge(const domain::StudentId& student, const domain::CourseCode& course, events::Publisher& out);
int fee_; std::vector<FeeCharged> charges_; // every charge made, oldest first};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Records the charge first, then announces it. With the synchronous// dispatcher, the FeeCharged handlers run inside this publish call, before// charge returns; with the queued one, publish only adds it to the queue.// If a FeeCharged handler throws synchronously, the charge is already kept.void Billing::charge(const domain::StudentId& student, const domain::CourseCode& course, events::Publisher& out) { // {student, course, fee_} builds a FeeCharged from its three members. charges_.push_back({student, course, fee_}); out.publish(charges_.back()); // a copy goes into the event}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Tells students what happened. Sending is simulated: a student with no// known address makes it throw, as an unreachable mail server would.class Notifier {public: // Makes `student` reachable; until then every message to them throws. void add_address(const domain::StudentId& student) { addresses_.insert(student); }
// One overload per event type; the wiring's generic lambda picks the // right one by the event's type. Each words one message and sends it, // and throws std::runtime_error if the student has no address (nothing // is then added to sent()). void handle(const domain::StudentSeated& event); void handle(const domain::StudentWaitlisted& event); void handle(const domain::StudentPromoted& event); void handle(const billing::FeeCharged& event);
const std::vector<std::string>& sent() const { return sent_; } // "to S1: ..."
private: // Throws std::runtime_error if `student` has no address. void send(const domain::StudentId& student, const std::string& text);
std::set<domain::StudentId> addresses_; // students who can be reached std::vector<std::string> sent_; // messages "sent", oldest first};Neither component includes the other’s class, or the use case.
Adding an SMS sender is a new class, a new parameter and a few lines
in wire, and one more object in main; billing, the notifier, and
the use case do not change.
The closed Event list has a cost here too: events/event.hpp
includes billing’s fee_charged.hpp, so every component that names
Event depends on billing’s event type, and the notifier names
billing::FeeCharged. That is usually acceptable inside one program;
it is what an open set of events would avoid.
Synchronous dispatch
Section titled “Synchronous dispatch”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Calls every matching handler before publish returns, in subscription// order. An event a handler publishes is handled at once, inside that// handler's call. An exception from a handler leaves publish at once:// later handlers for the event do not run.// `final`: no class can derive from it. `override` asks the compiler to// check that publish really replaces Publisher's virtual function.class SyncDispatcher final : public Publisher {public: // `subscribers` must outlive this dispatcher. explicit SyncDispatcher(const Subscribers& subscribers) : subscribers_{&subscribers} {}
// Offers the event to every entry in turn. An entry for another type // returns false and does nothing. `*this` is passed as the Publisher, so // a handler that publishes calls this same function again: a nested // call that finishes before the loop here moves on to the next entry. // No try/catch: a handler's exception leaves the loop and goes out // through publish to the use case, and then to its caller. void publish(Event event) override { for (const Subscribers::Entry& entry : subscribers_->entries()) entry.call(event, *this); }
private: const Subscribers* subscribers_; // non-owning, never null};This is Observer with a type filter: publish calls each matching
handler, in subscription order, and returns when they have all
returned. One enrollment, with billing subscribed before the notifier:
Text description of the diagram
A sequence diagram with four participants: Enrollment, SyncDispatcher, Billing, and Notifier. Enrollment publishes StudentSeated for S1 to the dispatcher. The dispatcher calls Billing’s seated. Billing publishes FeeCharged for S1 to the dispatcher, which, still inside Billing’s call, calls the Notifier’s handle for FeeCharged; the Notifier sends the charge notice and returns. The dispatcher returns to Billing, and Billing returns to the dispatcher. Only then does the dispatcher call the Notifier’s handle for StudentSeated, which sends the seat notice. The dispatcher returns to Enrollment with all handlers done. A note says the student is told about the charge before the seat.
Diagram source (Mermaid)
sequenceDiagram
participant E as Enrollment
participant D as SyncDispatcher
participant B as Billing
participant N as Notifier
E->>D: publish StudentSeated S1
D->>B: seated
B->>D: publish FeeCharged S1
D->>N: handle FeeCharged
N-->>D: sends the charge notice
D-->>B: returns
B-->>D: returns
D->>N: handle StudentSeated
N-->>D: sends the seat notice
D-->>E: returns, all handlers done
Note over E,N: the student is told about the charge before the seatWhat synchronous dispatch gives you:
- When
publishreturns, every reaction has happened. The caller can rely on it, and a test can check the results straight away. - A debugger shows the cause. Stopped in the notifier, the call stack shows billing, the dispatcher, and the use case above it.
- No queue, so no lifetime question about events waiting to be handled, and no second step that someone must remember to run.
And what it costs, all visible in the example’s output below:
- Ordering is depth-first. An event published by a handler is
handled before the remaining handlers of the event that caused it.
Here, that means the charge notice arrives first. Swapping the order
in
wirewould fix this case, which is the problem: correctness depends on the order of lines in a wiring function, and on which handlers publish. - A failing handler fails the command, after the change was kept.
With no address for S2,
enroll S2throws, although S2 is on the waitlist. The caller cannot tell “not enrolled” from “enrolled, but the message failed”. - The rest is skipped. When
drop S1promotes S2, billing charges S2, and the notifier fails onFeeCharged. The exception leaves billing, the dispatcher, and the use case, so the notifier never tells S2 about the promotion, and any later events the course recorded are never published. - A slow handler slows the command, because the use case waits for all of them.
How this code works: Synchronous dispatch: the program's three commands, and where each failure stops
Each command goes through the same layers: attempt in main calls
Enrollment::enroll or drop, which changes the Course (the change
is made and an event recorded), then publish_recorded takes the
recorded events out of the course, turns each into an Event, and
calls SyncDispatcher::publish. That calls entries 0 to 5 in order, and
a handler that publishes makes a nested call to the same publish.
The course has one seat; S1 has a mail address and S2 does not.
| Command | Course after | Handler calls, in order | How it ends |
|---|---|---|---|
enroll S1 |
S1 seated | entry 0 charges S1 and publishes FeeCharged; inside that call, entry 5 sends the charge notice; then entry 2 sends the seat notice |
returns ok: S1 has a seat in CS101 |
enroll S2 |
S2 waiting, position 1 | entry 3 throws no mail address for S2 |
the exception leaves publish, publish_recorded and enroll; attempt prints threw |
drop S1 |
S2 seated, nobody waiting | entry 1 charges S2 and publishes FeeCharged; inside that call, entry 5 throws |
the exception leaves both publish calls and drop; entry 4 never runs |
What exists after each failure:
- After
enroll S2throws: the course has S2 on its waitlist, and its list of recorded events is empty, becausetake_eventsmoved the event out before it was published. The vector that held it was destroyed as the exception leftpublish_recorded, so no object holds the event any more, and nothing records that the notice was not sent. Runningenroll S2again would only get “already in the course”, which records no event. - After
drop S1throws: S2 is seated, and billing’scharges_holds S2’s charge, becausechargeappends it before it publishes. TheFeeChargedevent was a copy made for the nestedpublishand is gone. The notifier’s entry 4 for the promotion was never called, so S2 is never told, and had the course recorded more events, the rest of the loop inpublish_recordedwould have been skipped too. - In both cases the caller sees only an exception, with nothing to say that the change was kept, so it cannot tell “not enrolled” from “enrolled, and the message failed”.
Queued dispatch
Section titled “Queued dispatch”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Holds published events until run() is called, then handles them// oldest first, including events published by handlers while it runs.// A handler that throws is recorded as a failure; the other handlers,// and later events, still run.class QueuedDispatcher final : public Publisher {public: // `subscribers` must outlive this dispatcher. explicit QueuedDispatcher(const Subscribers& subscribers) : subscribers_{&subscribers} {}
// publish runs no handler: it numbers the event (1, 2, 3, ... for the // dispatcher's whole life), notes which event was being handled when it // was published, and adds it to the back of the queue. void publish(Event event) override; // only queues it // Handles queued events, oldest first, until the queue is empty. Never // throws for a handler's failure: each one is caught and kept in // failures(). void run(); // until the queue is empty
// Runs each failed handler once more, oldest first, then run(). A // failure that has had `max_attempts` attempts is not retried: it // moves to given_up(), for a person to look at. void retry_failures(int max_attempts);
// One handler that threw for one event: enough to run exactly that // handler again with a copy of the same event, and to report why. struct Failure { std::size_t number; // the event's number, as in the trace Event event; std::size_t entry; // which subscription failed, as an index into entries() std::string handler; std::string reason; // what the latest attempt threw, as text int attempts; // how many times this handler has tried this event }; std::size_t pending() const { return queue_.size(); } const std::vector<Failure>& failures() const { return failures_; } const std::vector<Failure>& given_up() const { return given_up_; } const std::vector<std::string>& trace() const { return trace_; } // one line per handling
private: // One waiting event, with its number and the number of its cause. struct Queued { std::size_t number; std::size_t cause; // the event being handled when this was published; 0 if none Event event; };
const Subscribers* subscribers_; // non-owning, never null // A deque: run takes from the front while handlers add to the back. std::deque<Queued> queue_; std::vector<Failure> failures_; std::vector<Failure> given_up_; std::vector<std::string> trace_; std::size_t next_number_ = 1; std::size_t handling_ = 0; // the number of the event being handled; 0 between events};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// `next_number_++` uses the current number and then adds one. handling_ is// the event being handled right now (0 when publish is called from a use// case, between runs), so it becomes the new event's cause. The event is// moved into the queue, not copied.void QueuedDispatcher::publish(Event event) { queue_.push_back({next_number_++, handling_, std::move(event)});}
namespace {
// What a handler threw, as text. Anything is recorded, not only// std::exception, so no failure goes unrecorded.// A std::exception_ptr holds a caught exception of any type. Throwing it// again inside a try lets each catch test its type: anything derived from// std::exception gives its what() text; anything else (such as `throw 42`)// gives a fixed message.std::string reason_for(const std::exception_ptr& thrown) { try { std::rethrow_exception(thrown); } catch (const std::exception& error) { return error.what(); } catch (...) { return "an exception not derived from std::exception"; }}
} // namespace
// The loop condition is checked after every event, so events that handlers// publish while this runs are handled in the same call, after everything// that was already waiting.void QueuedDispatcher::run() { while (!queue_.empty()) { // Take the event out before any handler runs, so that it is // handled once even if a handler fails. // `current` is a local object moved (not copied) from the front, not a // reference into queue_, so handlers that push to queue_ cannot disturb it. const Queued current = std::move(queue_.front()); queue_.pop_front(); handling_ = current.number; // events published now name this one as cause
std::string line = "#" + std::to_string(current.number) + " " + describe(current.event); if (current.cause != 0) line += " (from #" + std::to_string(current.cause) + ")"; std::string handled; // the names of the handlers that ran, for the trace const std::vector<Subscribers::Entry>& entries = subscribers_->entries(); // An index, not a range-for, because a failure records which entry // failed so that retry_failures can call exactly that one again. for (std::size_t entry = 0; entry < entries.size(); ++entry) { // One try per handler: a throw stops only this handler, and the // loop goes on to the next entry. try { // Not this handler's event type: skip it, and leave it out // of the trace. if (!entries[entry].call(current.event, *this)) continue; // `?:` adds ", " before every name but the first. handled += (handled.empty() ? "" : ", ") + entries[entry].handler; } catch (...) { // `...` catches an exception of any type handled += (handled.empty() ? "" : ", ") + entries[entry].handler + " FAILED"; // Keep a copy of the event and the entry's index, with one // attempt made. std::current_exception() is the exception // this catch is handling. failures_.push_back({current.number, current.event, entry, entries[entry].handler, reason_for(std::current_exception()), 1}); } } trace_.push_back(line + ": " + (handled.empty() ? "no handlers" : handled)); } handling_ = 0; // between events again: a use case's publish has no cause}publishonly appends, so the use case returns as soon as the course has changed. Nothing has reacted yet;runhandles the queue later. In a server,runwould be called after each request, or by a loop of its own on the same thread.- Ordering is first in, first out. An event a handler publishes goes to the back of the queue, so the seat notice is handled before the charge it caused.
- Each handler is isolated. A handler that throws anything is
recorded as a failure, with the event’s number, which subscription
failed, the handler’s name, and the reason; the other handlers for
that event, and later events, still run.
catch (...)is used so that even an exception not derived fromstd::exceptionis recorded. Catching everything is only safe because it records the failure; the bad solution below catches and forgets. runtakes the event out of the queue before any handler runs, so each event is handled once, however its handlers end. (Handlers may publish, which grows the queue.std::deque::push_backkeeps references to existing elements valid, so a reference to the front would survive here, but not with astd::vector; moving the event out does not depend on which container is used.)- Every event has a number and a cause. An event published during
runrecords the number of the event being handled, so the trace can say “#3 … (from #1)”.
Text description of the diagram
A sequence diagram with four participants: Enrollment, QueuedDispatcher, Billing, and Notifier. Enrollment publishes StudentSeated for S1, and the dispatcher only queues it as event 1. A note says enroll returns, and run is called later. During run, the dispatcher calls Billing’s seated for event 1. Billing publishes FeeCharged for S1, which is queued as event 2. The dispatcher then calls the Notifier for StudentSeated, event 1, and next for FeeCharged, event 2. If S1 has an address, the Notifier sends the seat notice and then the charge notice. If not, both calls throw, and the dispatcher records each as a failure instead of letting the exception reach Enrollment. The diagram shows one enrollment on its own; in the program’s run below, S2’s enrollment is queued in between, so the numbers differ.
Diagram source (Mermaid)
sequenceDiagram
participant E as Enrollment
participant Q as QueuedDispatcher
participant B as Billing
participant N as Notifier
E->>Q: publish StudentSeated S1
Q-->>E: queued as event 1
Note over E,Q: enroll returns, later run is called
Q->>B: seated, event 1
B->>Q: publish FeeCharged S1
Q-->>B: queued as event 2
alt S1 has an address
Q->>N: handle StudentSeated, event 1
N-->>Q: sends the seat notice
Q->>N: handle FeeCharged, event 2
N-->>Q: sends the charge notice
else no address
Q->>N: handle StudentSeated, event 1
N-->>Q: throws, recorded as a failure
Q->>N: handle FeeCharged, event 2
N-->>Q: throws, recorded as a failure
endWhat it costs:
- When the command returns, nothing has reacted. A test, or a
caller, that checks billing straight after
enrollsees no charge. Anyone who readscharges()must know that it lags behind. - The queue is in memory, and so is the list of failures. In a
program that saves the course but not the queue, stopping between
enrollandrunkeeps the change and loses the events. Where that matters, the events are stored with the change in one transaction and sent from there: the outbox on Transaction and persistence boundaries. - The cause is no longer on the call stack. When the notifier runs, the use case has returned. The trace replaces the debugger’s stack, and is only as good as what it records.
- Failures must be looked at. A list of failures that nobody reads is a silent loss of messages.
How this code works: QueuedDispatcher in the program's run, event by event
The same wiring and commands as the synchronous run. “Queue” is what
queue_ holds after the step, with each event’s number and cause;
handling_ is the number publish would record as the cause.
| Step | Queue after | handling_ |
Entries that run | Recorded |
|---|---|---|---|---|
enroll S1 |
#1 (no cause) | 0 | none; enroll returns ok |
|
enroll S2 |
#1, #2 | 0 | none; enroll returns ok |
pending() is 2 |
run takes #1 |
#2, #3 (from #1) | 1 | 0 charges S1 and publishes #3; 2 sends the seat notice | #1 S1 seated in CS101: billing, notifier |
run takes #2 |
#3 | 2 | 3 throws | failure: #2, entry 3, 1 attempt |
run takes #3 |
empty | 3 | 5 sends the charge notice | #3 S1 charged 100 for CS101 (from #1): notifier |
run ends |
empty | 0 | ||
drop S1 |
#4 (no cause) | 0 | none; drop returns ok |
|
run takes #4 |
#5 (from #4) | 4 | 1 charges S2 and publishes #5; 4 throws | failure: #4, entry 4, 1 attempt |
run takes #5 |
empty | 5 | 5 throws | failure: #5, entry 5, 1 attempt |
What to notice:
- Every command returns
ok. The course changed before anything was published, and no handler runs inside the command, so a failing handler cannot reach the caller. - The charge notice for S1 now comes after the seat notice, because #3 joins the back of the queue and #1’s remaining handler, entry 2, runs first.
- After each failure, the state is complete and recorded. When
entry 3 throws for #2, the
catch (...)adds aFailureholding a copy of the event (currentisconst, so it is copied, not moved), the entry index, the name, and the reason, and the loop goes on to the next entry and the next event. At the end of the secondrun, the course has S2 seated, billing has charged S1 and S2 once each, S1 has both messages, andfailures()holds #2, #4 and #5, all for the notifier. handling_goes back to 0 whenrunends, so the eventdrop S1publishes has no cause, and the trace line for #4 has no “(from …)”.
Retrying a failed subscriber
Section titled “Retrying a failed subscriber”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Gives each recorded failure one more attempt, calling only the handler// that failed (by its entry index), not every handler of the event, so a// charge that succeeded is not made twice.void QueuedDispatcher::retry_failures(int max_attempts) { std::vector<Failure> again; // the failures that fail once more // std::exchange empties failures_ and hands its old contents to the // loop, which works on that returned vector; it lives until the loop // ends. Each failure ends up in exactly one place: given_up_, again, or // nowhere (it succeeded). for (Failure& failure : std::exchange(failures_, {})) { // Already tried max_attempts times: stop, and keep it for a person. if (failure.attempts >= max_attempts) { given_up_.push_back(std::move(failure)); continue; } // Events the handler publishes now are queued with this cause. handling_ = failure.number; std::string line = "retry #" + std::to_string(failure.number) + " " + failure.handler; try { // The same subscription, with the saved copy of the event. subscribers_->entries()[failure.entry].call(failure.event, *this); line += ": ok"; // succeeded: the failure is simply not kept } catch (...) { line += ": FAILED again"; failure.reason = reason_for(std::current_exception()); ++failure.attempts; again.push_back(std::move(failure)); } trace_.push_back(line); } handling_ = 0; failures_ = std::move(again); // what is still failing, waiting for the next retry // Handle events the retried handlers published. A handler that fails // during this run is added to failures_ with one attempt, as usual. run(); // events the retried handlers published}- Only the subscription that failed is run again, with the same event. It is found by its index, not its name, so a name used twice cannot rerun the wrong handler. Running every handler for the event would charge the student twice.
- That is not enough on its own. A handler that did part of its work and then threw, for example published a follow-up event, or charged and then failed, repeats that part when retried. A retried handler must be idempotent, or do its side effects last and all at once. Billing here publishes as its last step, and the notifier throws before it sends.
- Failures are retried oldest first, so among the retried
handlings, one student’s messages arrive in the order the events
happened. Events that retried handlers publish are queued, and
handled by
runafter all the retries. - A failure that fails again is kept, with one more attempt
counted. Once a failure has had
max_attemptsattempts, it is not tried again: it moves togiven_up(), for a person to look at.
How this code works: retry_failures(3) after S2's address is added
At the start, failures() holds the three failures from the run above,
each with 1 attempt, and the queue is empty.
- The list is taken.
std::exchange(failures_, {})moves the three failures into a temporary vector that the loop walks, and leavesfailures_empty. A failure that fails again goes to a separate vector,again, not to the list being walked. - None has run out of attempts. Each has 1 attempt, less than 3,
so none moves to
given_up(). - #2: entry 3 is called again with the stored
StudentWaitlistedevent, andhandling_is set to 2. S2 now has an address, so the notifier sends “you are number 1 on the waitlist for CS101”, and the trace getsretry #2 notifier: ok. The failure is not copied anywhere, so it is destroyed with the temporary vector. - #4 and #5 the same way: entry 4 sends the promotion notice and entry 5 the charge notice. Entry 1, billing’s handler for #4, ran without failing the first time, so it is not called again, and S2 is still charged once.
- The end.
againis empty, sofailures_stays empty;run()finds an empty queue, because the retried handlers published nothing. The output showsfailures left: 0.
If S2 still had no address, each retry would throw again: the catch
would store the new reason, raise the attempts to 2, and keep the
failure. A second call would raise them to 3. A third call would move
all three to given_up() without calling them, so with a limit of 3 a
handler is tried three times in all: once by run and twice by
retry_failures.
Running it
Section titled “Running it”The same script and wiring run through both dispatchers. S1 has a mail address; S2’s is added only near the end.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The composition root for the synchronous run. The locals are declared in// the order they depend on each other: the components, then the// subscriptions that refer to them, then the dispatcher that reads the// subscriptions, then the use case that borrows the dispatcher. They are// destroyed in reverse, so nothing outlives what it points to.// attempt(label, run), defined above, prints the label and the reply, or// "threw: " and the message if the call throws.void run_sync() { std::cout << "== synchronous dispatch ==\n"; billing::Billing billing{100}; notify::Notifier notifier; notifier.add_address(id("S1")); // S2's address is not known yet events::Subscribers subscribers; app::wire(subscribers, billing, notifier); events::SyncDispatcher dispatcher{subscribers}; app::Enrollment enrollment{software_design(), dispatcher}; // CS101 with one seat
// S1 is seated; billing and the notifier both run inside enroll. attempt("enroll S1", [&] { return enrollment.enroll(id("S1")); }); // S2 is waitlisted, then telling S2 throws: the caller sees a failure, // but S2 stays on the waitlist. attempt("enroll S2", [&] { return enrollment.enroll(id("S2")); }); // S2 is promoted and charged, then telling S2 about the charge throws // before the promotion notice is even tried. attempt("drop S1", [&] { return enrollment.drop(id("S1")); }); print_results(enrollment.course(), billing, notifier);}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same components and wiring, with a QueuedDispatcher: the use cases// only queue events, and handlers run when dispatcher.run() is called.void run_queued() { std::cout << "== queued dispatch ==\n"; billing::Billing billing{100}; notify::Notifier notifier; notifier.add_address(id("S1")); events::Subscribers subscribers; app::wire(subscribers, billing, notifier); events::QueuedDispatcher dispatcher{subscribers}; app::Enrollment enrollment{software_design(), dispatcher};
attempt("enroll S1", [&] { return enrollment.enroll(id("S1")); }); attempt("enroll S2", [&] { return enrollment.enroll(id("S2")); }); std::cout << "pending: " << dispatcher.pending() << '\n'; // #1 and #2, not yet handled // Handles #1 and #2, and #3, the charge billing publishes while // handling #1. Telling S2 fails and is recorded, not thrown. dispatcher.run(); attempt("drop S1", [&] { return enrollment.drop(id("S1")); }); dispatcher.run(); // #4, the promotion, and #5, billing's charge for it print_results(enrollment.course(), billing, notifier);
std::cout << "failures:\n"; for (const auto& failure : dispatcher.failures()) { std::cout << " #" << failure.number << ' ' << failure.handler << ": " << failure.reason << '\n'; } std::cout << "-- S2's address is added; the failures are retried --\n"; notifier.add_address(id("S2")); // Each failed notifier call (for #2, #4, #5) is run once more, and now // succeeds. Billing is not called again, so nobody is charged twice. dispatcher.retry_failures(3); print_results(enrollment.course(), billing, notifier); std::cout << "failures left: " << dispatcher.failures().size() << "\ntrace:\n"; for (const std::string& line : dispatcher.trace()) std::cout << " " << line << '\n';}== synchronous dispatch ==> enroll S1: ok: S1 has a seat in CS101> enroll S2: threw: no mail address for S2> drop S1: threw: no mail address for S2seated: S2; waiting: 0charged: S1 100 S2 100sent: to S1: you were charged 100 for CS101 to S1: you have a seat in CS101== queued dispatch ==> enroll S1: ok: S1 has a seat in CS101> enroll S2: ok: S2 is waiting for CS101pending: 2> drop S1: ok: S1 left CS101seated: S2; waiting: 0charged: S1 100 S2 100sent: to S1: you have a seat in CS101 to S1: you were charged 100 for CS101failures: #2 notifier: no mail address for S2 #4 notifier: no mail address for S2 #5 notifier: no mail address for S2-- S2's address is added; the failures are retried --seated: S2; waiting: 0charged: S1 100 S2 100sent: to S1: you have a seat in CS101 to S1: you were charged 100 for CS101 to S2: you are number 1 on the waitlist for CS101 to S2: a seat opened; you are enrolled in CS101 to S2: you were charged 100 for CS101failures left: 0trace: #1 S1 seated in CS101: billing, notifier #2 S2 waiting for CS101, position 1: notifier FAILED #3 S1 charged 100 for CS101 (from #1): notifier #4 S2 promoted into CS101: billing, notifier FAILED #5 S2 charged 100 for CS101 (from #4): notifier FAILED retry #2 notifier: ok retry #4 notifier: ok retry #5 notifier: okReading the output:
- Synchronous: S1’s two messages are in the wrong order.
enroll S2anddrop S1both throw, although each change was kept: the course shows S2 seated, and billing charged S2. S2 is never told anything. - Queued: both enrollments return
ok, with two events pending and nothing yet done. After both runs, S1’s messages are in the right order, and three handlings failed, all for the notifier, all for S2. - After the retry, S2 gets the three messages, in order, and each student is still charged once.
- The trace answers “why did this happen?”: event 3 is S1’s charge, caused by event 1, S1’s seat; event 4, S2’s promotion, was handled by billing and failed in the notifier.
class app::Enrollment
the use case, publishes
Data members
domain::Course course_;events::Publisher* publisher_;non-owning
Member functions
std::string enroll(const domain::StudentId& student);and dropconst domain::Course& course() const;
interface (abstract class) events::Publisher
all a handler may do
Member functions
virtual void publish(Event event) = 0;
class events::Subscribers
filled at start-up, then read
Member functions
void on<E>(std::string handler, std::function<void(const E&, Publisher&)> handle);const std::vector<Entry>& entries() const;in subscription order
class events::SyncDispatcher
final, implements Publisher
Data members
const Subscribers* subscribers_;non-owning
Member functions
void publish(Event event) override;handlers run now, exceptions escape
class events::QueuedDispatcher
final, implements Publisher
Data members
const Subscribers* subscribers_;non-owningstd::deque<Queued> queue_;events own their data
Member functions
void publish(Event event) override;only queuesvoid run();void retry_failures(int max_attempts);std::size_t pending() const;const std::vector<Failure>& failures() const;and given_upconst std::vector<std::string>& trace() const;
class billing::Billing
reacts to seats, publishes FeeCharged
Member functions
void seated(const domain::StudentSeated& event, events::Publisher& out);and promotedconst std::vector<FeeCharged>& charges() const;
class notify::Notifier
reacts to all four events
Member functions
void add_address(const domain::StudentId& student);void handle(const domain::StudentSeated& event);one overload per eventconst std::vector<std::string>& sent() const;
Testing each part
Section titled “Testing each part”Each dispatcher is tested through what the components did. The synchronous tests pin down its order and its failure behaviour, so a change to either is noticed:
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) if the two// values differ, and LLD_CHECK_THROWS(expression, type) unless the// expression throws that type. They come from the site's small test// header, lld_test.hpp. Components (from tests/fixture.hpp) is the// program's billing (fee 100), notifier and subscriptions, wired as in// main; student("S1") and course(1) make an id and a one-seat CS101.
// One handler, for StudentSeated only, records the ids it sees. The// waitlist event matches no subscription; the seat event is handled// before publish returns, so `seen` can be checked straight after.LLD_TEST(a_handler_runs_before_publish_returns_and_only_for_its_type) { events::Subscribers subscribers; std::vector<std::string> seen; subscribers.on<domain::StudentSeated>("seats", [&seen](const auto& event, events::Publisher&) { seen.push_back(event.student.text()); }); events::SyncDispatcher dispatcher{subscribers};
dispatcher.publish(domain::StudentWaitlisted{student("S2"), cs101(), 1}); dispatcher.publish(domain::StudentSeated{student("S1"), cs101()}); LLD_CHECK_EQ(seen.size(), std::size_t{1}); LLD_CHECK_EQ(seen[0], std::string{"S1"});}
// The surprise of synchronous dispatch: billing handles the seat first and// publishes FeeCharged, whose notifier handler runs at once, inside// billing's call. So the charge notice is sent before the seat notice.LLD_TEST(an_event_published_by_a_handler_jumps_ahead_of_later_handlers) { Components components; // billing is subscribed before the notifier components.notifier.add_address(student("S1")); events::SyncDispatcher dispatcher{components.subscribers}; app::Enrollment enrollment{course(1), dispatcher};
enrollment.enroll(student("S1")); const std::vector<std::string>& sent = components.notifier.sent(); LLD_CHECK_EQ(sent.size(), std::size_t{2}); LLD_CHECK_EQ(sent[0], std::string{"to S1: you were charged 100 for CS101"}); // too early LLD_CHECK_EQ(sent[1], std::string{"to S1: you have a seat in CS101"});}
// No address for S1: billing charges, then the notifier's FeeCharged// handler throws. The exception comes out of enroll, but the seat and the// charge are already made, and no message was sent.LLD_TEST(a_throwing_handler_reaches_the_caller_after_the_change_is_kept) { Components components; // S1 has no address, so the notifier throws events::SyncDispatcher dispatcher{components.subscribers}; app::Enrollment enrollment{course(1), dispatcher};
LLD_CHECK_THROWS(enrollment.enroll(student("S1")), std::runtime_error); LLD_CHECK(enrollment.course().contains(student("S1"))); // the change was kept LLD_CHECK_EQ(components.billing.charges().size(), std::size_t{1}); // billing ran first LLD_CHECK(components.notifier.sent().empty());}The queued tests check that nothing runs before run, the order of
follow-up events, failure isolation, and the exact trace:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Components (from tests/fixture.hpp) is billing (fee 100), the notifier// and the subscriptions, wired as in main; student("S1") and course(1)// make an id and a one-seat CS101. LLD_CHECK_EQ(actual, expected) records// a failure if the two values differ.
// The use case returns its reply while the event is still queued: no// handler has run until run() is called.LLD_TEST(publish_only_queues_until_run) { Components components; components.notifier.add_address(student("S1")); events::QueuedDispatcher dispatcher{components.subscribers}; app::Enrollment enrollment{course(1), dispatcher};
LLD_CHECK_EQ(enrollment.enroll(student("S1")), std::string{"ok: S1 has a seat in CS101"}); LLD_CHECK_EQ(dispatcher.pending(), std::size_t{1}); LLD_CHECK(components.billing.charges().empty()); // nothing has reacted yet dispatcher.run(); LLD_CHECK_EQ(dispatcher.pending(), std::size_t{0}); LLD_CHECK_EQ(components.billing.charges().size(), std::size_t{1});}
// The opposite of the synchronous order: billing's FeeCharged goes to the// back of the queue, so the seat notice (handled with #1) comes first.LLD_TEST(an_event_published_by_a_handler_waits_its_turn) { Components components; components.notifier.add_address(student("S1")); events::QueuedDispatcher dispatcher{components.subscribers}; app::Enrollment enrollment{course(1), dispatcher};
enrollment.enroll(student("S1")); dispatcher.run(); const std::vector<std::string>& sent = components.notifier.sent(); LLD_CHECK_EQ(sent.size(), std::size_t{2}); LLD_CHECK_EQ(sent[0], std::string{"to S1: you have a seat in CS101"}); LLD_CHECK_EQ(sent[1], std::string{"to S1: you were charged 100 for CS101"});}
// No address for S1: both notifier calls (the seat, then the charge)// fail and are recorded, while billing still charges. Nothing throws.LLD_TEST(a_failing_handler_is_recorded_and_the_others_still_run) { Components components; // S1 has no address events::QueuedDispatcher dispatcher{components.subscribers}; app::Enrollment enrollment{course(1), dispatcher};
enrollment.enroll(student("S1")); dispatcher.run(); LLD_CHECK_EQ(components.billing.charges().size(), std::size_t{1}); LLD_CHECK_EQ(dispatcher.failures().size(), std::size_t{2}); // the seat and the charge notices LLD_CHECK_EQ(dispatcher.failures()[0].handler, std::string{"notifier"}); LLD_CHECK_EQ(dispatcher.failures()[0].reason, std::string{"no mail address for S1"});}
// S1 has an address and S2 does not. The trace has one line per event:// #1 and #2 from the use cases, then #3, published by billing while #1// was handled, so it is marked "(from #1)".LLD_TEST(the_trace_names_each_event_its_cause_and_its_handlers) { Components components; components.notifier.add_address(student("S1")); events::QueuedDispatcher dispatcher{components.subscribers}; app::Enrollment enrollment{course(1), dispatcher};
enrollment.enroll(student("S1")); enrollment.enroll(student("S2")); dispatcher.run(); const std::vector<std::string>& trace = dispatcher.trace(); LLD_CHECK_EQ(trace.size(), std::size_t{3}); LLD_CHECK_EQ(trace[0], std::string{"#1 S1 seated in CS101: billing, notifier"}); LLD_CHECK_EQ(trace[1], std::string{"#2 S2 waiting for CS101, position 1: notifier FAILED"}); LLD_CHECK_EQ(trace[2], std::string{"#3 S1 charged 100 for CS101 (from #1): notifier"});}Billing and the notifier could also be tested alone, with no
dispatcher: billing by calling seated with an event and a fake
Publisher that records what was published, and the notifier by
calling handle with an event. The example does not include those
tests; that they need no dispatcher is one benefit of a handler that
only knows its events.
Comparing the two
Section titled “Comparing the two”| Question | Synchronous | Queued |
|---|---|---|
| Have the reactions run when the command returns? | yes | no; after run |
| Order of follow-up events | depth-first, inside the handler | first in, first out |
| A handler throws | the command throws, after its change was kept; later handlers skipped | recorded; the others run |
| Finding the cause | the debugger’s call stack | a trace with event numbers and causes |
| Lost if the program stops | nothing pending | everything still queued, unless stored |
| A slow handler | slows the command | slows the queue, not the command |
When it fits
Section titled “When it fits”- Several independent reactions to the same fact, owned by different parts of the program, that keep growing: notifications, billing, audit logs, statistics.
- Reactions that must not fail the command, or that can be retried later: messages, calls to other systems.
- Modules that should not depend on each other. On the modular monolith page, a module’s public events let another module react without including its classes.
Common mistakes
Section titled “Common mistakes”- Putting the command’s own rules in a handler. If seating a student depends on billing’s answer, that check is part of the command. A handler cannot refuse an enrollment that has already happened.
- Publishing before the change is kept. A handler then sees the old state, and if the change fails, the event announced something that never happened.
- Events that hold references or pointers to the publisher’s objects. With a queue, they dangle; with a synchronous dispatcher, they break as soon as someone switches to a queue.
- Depending on subscription order. If billing must run before the notifier, that is a hidden rule in the wiring; the order bug above is an example.
- Swallowing failures without recording which handler failed for which event.
- Event cycles. A handler whose event leads, through other
handlers, back to itself recurses until the stack overflows with a
synchronous dispatcher, and loops for ever with a queue. Keep the
chains short and visible in
wire, and follow-up events of a different type from their cause. - Retrying all handlers for an event, which repeats the ones that worked, such as charging twice.
- An event for everything. If every call becomes an event, nobody can follow what one command does, which is the event bus problem from Observer vs Mediator.
When the requirements change
Section titled “When the requirements change”- Students also get an SMS. A new class, a parameter and a few
lines in
wire, and one more object inmain; the use case, billing, and the notifier do not change. - Messages must not be lost when the program restarts. Store the
events with the change (the outbox), have
runread from there, and make handlers idempotent, since a restart can repeat a handler that had finished. - The notifier is slow, and should run on another thread. Neither
dispatcher is thread-safe. The queue would need a lock, or a
thread-safe queue. So would everything that both threads touch: the
notifier’s addresses, which
add_addresschanges from the main thread; billing’s charges, the sent messages, the failures, and the trace, which are read whilerunwrites them. And the cause, kept in the memberhandling_, would be wrong for an event the use case publishes on one thread while another runs the queue: it would have to be passed with each call instead. A planned page on concurrency covers that hand-off. Keeping events as values that own their data is what makes moving them to another thread possible at all. - Billing must refuse students with unpaid fees. That is now a
rule of the command: the use case asks billing before seating, by a
direct call. The
FeeChargedreaction can stay an event.
Exercise
Section titled “Exercise”Exercise: Handle a failing subscriber
The notifier fails for every student without a known address. Using the example’s components:
- With the synchronous dispatcher and no address for S1, what
does
enroll S1do to the caller, the course, billing, and the messages sent? Write a test that pins it down. - With the queued dispatcher, write a test showing that after
S1’s address is added,
retry_failuresdelivers both of S1’s messages in order, leaves no failures, and does not charge S1 twice. - Write a test for a retry that fails again: what should the dispatcher keep, and how does it stop retrying?
Show the explained answer
-
enrollthrowsstd::runtime_error, but the course has S1 seated and billing has charged S1, because billing ran before the notifier failed on billing’s ownFeeChargedevent. No message was sent. This is the testa_throwing_handler_reaches_the_caller_after_the_change_is_keptin the synchronous tests above. -
and 3. These tests are in the example and pass:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Two failures (the seat and charge notices for S1) are retried after the// address is added. Only the notifier runs again, in the original order,// and billing's one charge stays one.LLD_TEST(a_retry_runs_only_the_failed_handler) { Components components; // S1 has no address yet events::QueuedDispatcher dispatcher{components.subscribers}; app::Enrollment enrollment{course(1), dispatcher}; enrollment.enroll(student("S1")); dispatcher.run();
components.notifier.add_address(student("S1")); dispatcher.retry_failures(3); LLD_CHECK(dispatcher.failures().empty()); LLD_CHECK_EQ(components.billing.charges().size(), std::size_t{1}); // not charged twice const std::vector<std::string>& sent = components.notifier.sent(); LLD_CHECK_EQ(sent.size(), std::size_t{2}); LLD_CHECK_EQ(sent[0], std::string{"to S1: you have a seat in CS101"}); // still in order LLD_CHECK_EQ(sent[1], std::string{"to S1: you were charged 100 for CS101"});}
// With a limit of 2: the first retry fails again and raises attempts from// 1 to 2; the second retry finds attempts at the limit and moves both// failures to given_up() without calling the handler.LLD_TEST(a_failure_is_kept_with_its_attempts_until_the_limit) { Components components; events::QueuedDispatcher dispatcher{components.subscribers}; app::Enrollment enrollment{course(1), dispatcher}; enrollment.enroll(student("S1")); dispatcher.run();
dispatcher.retry_failures(2); // still no address LLD_CHECK_EQ(dispatcher.failures().size(), std::size_t{2}); LLD_CHECK_EQ(dispatcher.failures()[0].attempts, 2); dispatcher.retry_failures(2); // the limit is reached: not tried again LLD_CHECK(dispatcher.failures().empty()); LLD_CHECK_EQ(dispatcher.given_up().size(), std::size_t{2}); LLD_CHECK_EQ(dispatcher.given_up()[0].reason, std::string{"no mail address for S1"}); LLD_CHECK_EQ(components.billing.charges().size(), std::size_t{1});}
// `throw 42` throws an int, not a std::exception; catch (...) still// records it, with reason_for's fixed text.LLD_TEST(a_handler_that_throws_anything_is_still_recorded) { events::Subscribers subscribers; subscribers.on<domain::StudentSeated>("odd", [](const auto&, events::Publisher&) { throw 42; }); events::QueuedDispatcher dispatcher{subscribers}; dispatcher.publish(domain::StudentSeated{student("S1"), cs101()}); dispatcher.run(); LLD_CHECK_EQ(dispatcher.failures().size(), std::size_t{1}); LLD_CHECK_EQ(dispatcher.failures()[0].reason, std::string{"an exception not derived from std::exception"});}The retry runs only the failed subscription, the notifier’s, so
billing is not called again. The dispatcher keeps each failure that
fails again with its attempts count, and retry_failures takes the
limit: a failure that has reached it is moved to given_up() instead
of being tried again, so it can be reported to a person. The limit is
a policy for the program to choose; main uses 3, and the test uses
2 to reach it quickly. The last test checks that even an exception
not derived from std::exception is recorded, not lost.
Summary
Section titled “Summary”- Keep work that is the command, or that the reply needs, in the use case. Work that follows and must not fail the command can be a reaction to an event.
- Make events values that own their data, named as facts, in
a closed
std::variantso a handler for the wrong type does not compile. - Give handlers names, and wire them in one place at start-up.
- Synchronous dispatch is simple and easy to debug, but ordering is depth-first, and one failing handler fails the command after its change was kept.
- Queued dispatch isolates failures and keeps first-in, first-out order, but the command returns before anything has reacted, and an in-memory queue is lost when the program stops.
- Retry only the handler that failed, record attempts, and make handlers idempotent where a repeat is possible.
- When the caller needs an answer, or the steps must happen in order or together, call directly instead.