Transaction and persistence boundaries
What you will learn on this page
Section titled “What you will learn on this page”- What failure atomicity means: a use case either happens completely or leaves no trace, and how C++ code gets there by changing a copy and committing with steps that cannot throw.
- Who begins, commits, and rolls back: the application’s use case, not the domain, not the repositories, and not the caller.
- The guideline of one aggregate per transaction, why it exists, and when to break it on purpose.
- What to do when two transactions overlap: refuse the second commit and rerun the whole use case.
- How to change two stores without a transaction spanning both: an outbox in the first store, delivery at least once, and a receiver that ignores a message it has already handled.
The problem: one request, several changes, two stores
Section titled “The problem: one request, several changes, two stores”The registrar now charges a fee of 100 for each seat, including a seat taken by promotion from the waitlist. Billing is another part of the system, with its own store: it may be a separate module of a modular monolith with its own data, or a separate service. Enrolling a student must now:
- seat or waitlist them in the
Course; - count the course in their
StudentLoad, which allows at most three; - charge their billing account, if they were seated.
Dropping a seat can promote the next student from the waitlist, who must then be charged too.
Each step can fail on its own: the disk can be full, the connection lost, or the process stopped. Two requests can also arrive at once. The overview’s question returns here: if telling another part of the system fails, should the change stand?
The enrollment store is changed safely, but billing is a second write, and every way of ordering the two writes is wrong in some case:
- Commit, then charge. If the charge fails, or the process stops
between the two lines, the student has a seat and was never
charged. Retrying the request does not help: enrolling again says
already_in_course, so the charge is never reached. - Charge, then commit. If the commit fails, the student was charged for a seat they do not have.
- A retried charge. If the charge reached billing but the reply was lost, calling it again charges twice.
- Promotions are forgotten. The promoted student is decided
inside
Course::drop, so a caller that charges onenrollalone never charges them. - Overlapping requests. If another request enrolls someone in the
same course between this one’s
findandcommit, one of the two enrollments is lost, as the repository page described.
Step 1: classify the changes
Section titled “Step 1: classify the changes”List every change one use case makes, the store it lives in, and what it must be kept with:
| Change | Store | Must be true together with |
|---|---|---|
| The course’s seat or waitlist | enrollment | the student’s load (the three-course limit) |
| The student’s load | enrollment | the course’s seat or waitlist |
| “Charge S1 for CS101” recorded | enrollment | the seat: committed in the same transaction |
| The account’s amount owed | billing | the recorded charge, eventually |
Two kinds of “together” appear:
- Immediately: no reader may ever see a seat without the load, or the limit could be broken. These changes belong in one transaction, which needs them in one store.
- Eventually: the account may be updated a moment after the seat, as long as it is updated exactly once in effect and the intention to charge can never be lost. Changes in another store are made this way, by a message.
The rest of the page builds both: one transaction per use case for the first kind, and an outbox for the second.
Failure atomicity: the basics
Section titled “Failure atomicity: the basics”An operation that can fail offers one of three exception guarantees:
- Basic: if it throws, nothing leaks and every object is still valid, but its state may have changed.
- Strong: if it throws, the state is exactly as before. The operation is atomic with respect to failure: all or nothing.
- Nothrow: it never fails.
domain::enroll gives the basic guarantee across its two objects: it
changes the load first and the course second, so if the course’s
change threw, for example because memory ran out, the load would
already be changed. Each aggregate is valid, but the two disagree.
The usual way to get the strong guarantee is:
- Copy the state.
- Make every change, which may throw, on the copy.
- Commit by replacing the original with the copy, using only
operations that cannot throw, such as a
noexceptmove or swap.
If anything in step 2 throws, the copy is dropped and the original was never touched. This is the idea behind copy-and-swap, and it is what the store below does for a whole use case. Exception safety and failure atomicity builds these guarantees inside a single C++ operation, without a store.
The store and its transactions
Section titled “The store and its transactions”The example’s store is an in-memory stand-in for a database: it holds one set of tables, and only a transaction can change them.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An in-memory store holding one set of tables. Only a Transaction can// change them, so every change is committed whole or not at all.// `Tables` is a template parameter: any struct of containers works, such// as the enrollment tables, billing's tables, or a plain list of numbers// in the tests. Store<EnrollmentTables> and Store<BillingTables> are two// separate stores that share this code but no data.// Readers get committed(), a const reference to the tables as of the// last commit; nothing a reader does can change them.template <typename Tables>class Store {public: // Checked when the program is compiled: moving one Tables over // another must be noexcept (unable to throw). Commit's last step is such a // move, and this is what lets it promise that, once it starts // changing the store, nothing can throw and leave half a commit. static_assert(std::is_nothrow_move_assignable_v<Tables>, "a commit must not fail halfway");
Store() = default; Store(const Store&) = delete; // a copy would be a second, diverging store Store& operator=(const Store&) = delete;
const Tables& committed() const { return tables_; } int commits() const { return commits_; } int rollbacks() const { return rollbacks_; }
// Makes the next commit fail, as a full disk or a lost connection // would. For the demonstration and the tests. It is a one-shot flag: // the commit that sees it clears it, so only one commit fails. void fail_next_commit() { fail_next_commit_ = true; }
private: // `friend` lets Transaction, and only Transaction, read and replace // these private members. That is how "only a transaction can change // the tables" is enforced: the store itself has no public setter. friend class Transaction<Tables>; Tables tables_; // the committed tables, the only copy readers see // Counts commits. A transaction remembers the value it began with; if // it has changed by commit time, someone else committed in between. std::uint64_t version_ = 0; bool fail_next_commit_ = false; int commits_ = 0; // statistics for the demonstration only int rollbacks_ = 0; // transactions that ended without a commit};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// RAII: beginning is construction, and rollback is destruction without a// commit. The transaction works on a private copy of the tables, so the// store never sees a half-made change; dropping the copy is the rollback.// Use: make one as a local variable, change tables(), call commit(). If// the function leaves by return or by exception before commit() has// finished, the destructor runs and the store keeps its old tables.template <typename Tables>class Transaction {public: // Begins: copies every committed table into working_ (a full copy, // so this costs time in proportion to all the stored data) and notes // the store's version. The store must outlive the transaction, // because store_ is a plain pointer to it. explicit Transaction(Store<Tables>& store) : store_{&store}, working_{store.tables_}, base_version_{store.version_} {} // Ends. There is nothing to undo: the store was never touched, and // working_ is destroyed with the transaction. Only the counter // changes, so the demonstration can show how many rollbacks there // were. A transaction that changed nothing and was never committed // counts as a rollback too. ~Transaction() { if (!committed_) ++store_->rollbacks_; } // No copies, and so no moves either (declaring the copy operations // stops the compiler from providing moves): two objects for one // transaction could commit twice. Transaction(const Transaction&) = delete; Transaction& operator=(const Transaction&) = delete;
// The private copy, for the use case to read and change freely. Tables& tables() { return working_; }
// Throws Conflict if another transaction committed since this one // began, or Refused if the store cannot keep the changes. Either way, // nothing is kept. // Every check comes before the first change, so a throw from any of // the three `if`s leaves the committed tables and the version exactly // as they were (Refused has also cleared the one-shot failure flag). // After Conflict or Refused the transaction is still uncommitted, so // its destructor will count a rollback. void commit() { // Calling commit twice is a programming error, not a store failure. if (committed_) throw std::logic_error{"the transaction is already committed"}; // The version moved on: another transaction committed after this // one began, and this copy was made from tables that are now out // of date. Keeping it would silently throw the other's work away. if (store_->version_ != base_version_) throw Conflict{"another transaction committed first"}; // std::exchange sets the flag to false and returns its old value, // in one step: if a failure was requested, it happens now, once. if (std::exchange(store_->fail_next_commit_, false)) { throw Refused{"the store refused the commit"}; } // Nothing from here on can throw. // The copy replaces the committed tables. std::move hands over the // copy's contents instead of copying them again; the static_assert // in Store guarantees this move is noexcept. working_ is left in // a moved-from state, and is never read again. store_->tables_ = std::move(working_); ++store_->version_; // any other open transaction will now conflict ++store_->commits_; committed_ = true; // so the destructor does not count a rollback }
private: Store<Tables>* store_; // non-owning; the store must outlive this Tables working_; // the private copy every change is made to std::uint64_t base_version_; // the store's version when this began bool committed_ = false;};How this code works: Two transactions on one store, step by step
This trace follows the test the_second_of_two_overlapping_commits_is_refused
on a Store<Numbers>, whose tables are one std::vector<int>. “Store”
is what committed() shows; version_ starts at 0.
| Step | Store values |
version_ |
first copy |
second copy |
What happens |
|---|---|---|---|---|---|
first is made |
{} |
0 | {}, base 0 |
the constructor copies the tables and notes version 0 | |
second is made |
{} |
0 | {}, base 0 |
{}, base 0 |
a second, independent copy |
| both push a value | {} |
0 | {1} |
{2} |
only the copies change; a reader still sees {} |
first.commit() |
{1} |
1 | moved-from | {2} |
version 0 matches, no failure is due: the copy is moved in |
second.commit() throws |
{1} |
1 | moved-from | {2} |
version 1 is not base 0: Conflict, and nothing is changed |
| end of the test | {1} |
1 | second is destroyed uncommitted, so rollbacks() becomes 1 |
Three things to take from it:
- Nothing reaches the store before
commit. A transaction only ever writes to its ownworking_, so a reader ofcommitted()never sees a half-made change, and “rollback” is just letting the copy be destroyed. - The version is the whole conflict check. Each commit adds one to
version_. A transaction that began at version 0 and finds version 1 knows its copy was made from tables someone else has since replaced, so keeping it would erase their work. - The failure paths leave exactly this state. After
ConflictorRefused, the committed tables andversion_are as they were (Refusedhas also used up the requested failure). The transaction is still uncommitted, so its destructor counts one rollback when it goes out of scope. Callingcommita second time on a committed transaction throwsstd::logic_errorand changes nothing at all.
How it works:
- Beginning is construction. The constructor copies the committed
tables into
working_and remembers the store’sversion_. - Rollback is destruction without a commit. The destructor does not need to undo anything: the store was never changed, and the copy is destroyed with the transaction. Returning early, a refusal, and an exception all roll back by the same path, as RAII promises. The counter is there only so the example can show it.
commitchecks before it changes anything. It refuses a second commit, refuses withConflictif another transaction committed since this one began, and can be told to fail, as a full disk would. After those checks, the remaining steps cannot throw.- The
static_assertmakes “cannot throw” a compile-time fact for the move. A standard container’s move assignment isnoexceptwhen its allocator is always equal, asstd::allocatoris, and its comparison object moves without throwing. A custom allocator or comparator could change that, and the assertion would then stop the build instead of letting a commit fail halfway. std::exchangereads the “fail next commit” flag and clears it in one expression, so the forced failure happens once.
On ownership: the transaction holds a non-owning pointer to the
store, so the store must outlive it; in the example, every transaction
is a local variable inside a call on a store that lives in main. The
copy operations are deleted, which also removes the moves: a copied
transaction could commit twice, and a moved-from one would still roll
back in its destructor. Store deletes its copies too: a copy would
be a second store that silently stops seeing the first one’s commits.
Who owns the transaction
Section titled “Who owns the transaction”There are four candidates, and only one knows enough:
- The domain does not know a store exists, and should not:
Coursewould then be untestable without storage. - A repository knows one aggregate, not which changes belong to one use case. A repository that commits on every save gives the flawed example’s problem: the load is kept and the course is not.
- The caller, such as a web handler, knows when a request starts and ends, but not what storage is. If it opened transactions, it might also hold one open while waiting for a user, which keeps copies stale and makes conflicts likely.
- The application’s use case knows what one business action is: “enroll this student in this course”. One use case, one transaction, begun and committed in one place.
In the example, that one place is a small function every use case calls:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What one run of a use case's work hands back: the text for the caller,// and whether the work changed the tables. A refusal such as// "no_such_course" is a Result with changed == false, not an exception.struct Result { std::string reply; bool changed = false; // whether there is anything to commit};
// The one place that begins, commits, and retries. The work runs on the// transaction's tables and says whether it changed anything; if not,// nothing is committed. A Conflict reruns the whole work on fresh// tables, up to `attempts` times, because the work's decisions were made// on data that is now out of date. Any other exception propagates, after// the transaction's destructor has rolled back.// `Work` is a template parameter, so any callable fits: in practice a// lambda that takes `Tables&` and returns a Result. Because the work may// run up to `attempts` times, it must only change the tables it is given;// an email sent or a call made from inside it would happen once per run.template <typename Tables, typename Work>Result in_transaction(store::Store<Tables>& store, Work work, int attempts = 3) { // A loop with no condition: it ends only by `return` or by a throw. for (int attempt = 1;; ++attempt) { // Begin: a fresh copy of the committed tables on every attempt, so // a rerun sees whatever the conflicting commit changed. store::Transaction<Tables> transaction{store}; Result result = work(transaction.tables()); // Nothing changed (a refusal, or a read): return without // committing. The destructor then drops the copy and counts a // rollback. (If the work itself throws, the exception leaves at // the line above, and the destructor rolls back on the way out.) if (!result.changed) return result; try { transaction.commit(); return result; // kept; the destructor sees committed_ and counts nothing } catch (const store::Conflict&) { // Out of attempts: `throw;` rethrows this same Conflict to // the caller. Otherwise fall through to the end of the loop // body, where `transaction` is destroyed (a rollback), and // go round again with a new copy. if (attempt >= attempts) throw; } // Refused, and anything else, is not caught here: it leaves the // function, and the destructor rolls back on the way out. }}How this code works: in_transaction: every way one call can end
Each time round the loop, one Transaction is a local variable of the
loop body. Leaving the body, by return, by throw, or by reaching
its end, destroys it, and the destructor counts a rollback unless the
commit finished.
| What happens on this attempt | Committed? | What in_transaction does |
State of the store afterwards |
|---|---|---|---|
the work returns changed == false |
no | returns that Result |
unchanged; one rollback counted |
| the work throws | no | lets the exception out | unchanged; one rollback counted |
| commit succeeds | yes | returns the Result |
the copy is now the committed tables; version + 1 |
Conflict, attempts left |
no | goes round again with a fresh copy | unchanged by this attempt; one rollback counted |
Conflict on the last attempt |
no | throw; rethrows it to the caller |
unchanged by this attempt; one rollback counted |
Refused (or any other exception) |
no | lets the exception out, no retry | unchanged; one rollback counted |
Two details are easy to miss:
for (int attempt = 1;; ++attempt)has no condition, so the loop never ends by itself. Every row of the table above leaves byreturnorthrow, except “Conflict, attempts left”, which reaches the end of the loop body and goes round again.- A retry calls
workagain from the start, on a new copy of the tables. That is why the work may only change the tables it is given: anything else it did, such as sending a message, would be done once per attempt, including attempts whose changes were thrown away.
In a_conflict_reruns_the_whole_work_on_fresh_tables, the first run
sees an empty copy and pushes 10, but another transaction commits {1}
meanwhile, so the commit throws Conflict. The second run’s copy is
{1}, it pushes 11, and the commit succeeds: the store holds {1, 11}
and the work ran twice.
Its decisions:
- The work runs on the transaction’s tables and returns a
Result: the reply, and whether anything changed. A use case that refused, or only read, commits nothing. - A
Conflictreruns the whole work, not only the commit. The work’s decisions, such as “the course has a free seat”, were made on tables that another commit has since replaced, so they must be made again on fresh ones. Afterattemptstries, theConflictgoes to the caller. - Any other exception propagates, including
store::Refused. The transaction’s destructor has already rolled back by the time the caller sees it. A refused commit is not retried here: a real store may fail for a reason that will not pass, and the caller is better placed to decide. - The work must have no effects outside the tables. Because it may run more than once, a work that sent an email or called billing would do so once per attempt, and also when the commit then failed. Anything that leaves the store has to wait until the commit, which is what the outbox below arranges.
Text description of the diagram
A sequence diagram with five participants: the caller, Registrar enroll, the Transaction, domain enroll, and the enrollment Store. The caller asks to enroll S1 in CS101. The registrar begins a transaction inside in_transaction, and the transaction copies the committed tables from the store and notes the store’s version. The registrar calls domain enroll on the copied load and course, which replies seated. The registrar adds a charge message to the copied outbox and calls commit. There are three alternatives. If the version is unchanged and the store accepts, the transaction moves the copy into the store in a step that cannot throw, and the caller is told seated. If another transaction committed first, commit throws Conflict to the registrar; the copy is dropped and the whole work runs again on a fresh copy. If the store refuses the commit, commit throws store Refused; the destructor drops the copy, the store is unchanged, and the exception propagates to the caller.
Diagram source (Mermaid)
sequenceDiagram
participant C as caller
participant R as Registrar enroll
participant T as Transaction
participant D as domain enroll
participant S as enrollment Store
C->>R: enroll S1 in CS101
R->>T: begin, inside in_transaction
T->>S: copy the committed tables, note the version
R->>D: enroll, on the copied load and course
D-->>R: seated
R->>T: add a charge message to the copied outbox
R->>T: commit
alt the version is unchanged and the store accepts
T->>S: move the copy in, a step that cannot throw
R-->>C: seated
else another transaction committed first
T-->>R: Conflict
Note over R,T: the copy is dropped, and the whole work runs again on a fresh copy
else the store refuses the commit
T-->>R: store Refused
Note over T,S: the destructor drops the copy, and the store is unchanged
R-->>C: the exception propagates
endThe use case: three changes, one transaction
Section titled “The use case: three changes, one transaction”The enrollment store’s tables hold the two aggregates and an outbox, a queue of messages for billing:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A message for billing, written to the outbox in the same transaction// as the change that caused it, so it is committed only if the change is.struct ChargeMessage { std::string id; // unique, so billing can recognize a repeat domain::StudentId student; domain::CourseCode course; int amount = 0; // decided when the seat is taken, not when delivered};
// Everything the enrollment store holds, as one value. A transaction// copies all of it and commits all of it, so a course, a load, and an// outbox message changed together are kept together or not at all.// The members are standard containers, whose move assignment is// noexcept, which is what Store's static_assert requires.struct EnrollmentTables { std::map<domain::CourseCode, domain::Course> courses; // one aggregate per course std::map<domain::StudentId, domain::StudentLoad> loads; // one per student // Messages waiting for the relay, oldest at the front. A deque, // because the relay removes from the front and enroll adds at the back. std::deque<ChargeMessage> outbox; // The number in the next message id: 1 gives "m1". It is in the // tables, so it is committed or rolled back with the messages; a // failed commit does not use up a number. std::uint64_t next_message = 1;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The use cases. Each one is one transaction, begun and committed here// and nowhere else: the domain objects do not know there is a store, and// the caller only hears the result, or an exception if the commit failed.class Registrar {public: // Keeps a pointer to the store, which must outlive the registrar (in // main, both are locals and the store is declared first). Registrar(store::Store<EnrollmentTables>& store, int fee) : store_{&store}, fee_{fee} {}
// Set-up use cases: each adds one row in its own transaction, and // does nothing if the code or id is already there. void add_course(const domain::CourseCode& code, const std::string& title, int capacity); void add_student(const domain::StudentId& student);
// Each returns a short reply such as "seated", "waitlisted", // "no_such_course" or "left_seat". A refusal is a reply, and commits // nothing. A failed commit is an exception (store::Refused, or // store::Conflict after three attempts), and keeps nothing. std::string enroll(const domain::StudentId& student, const domain::CourseCode& course); std::string drop(const domain::StudentId& student, const domain::CourseCode& course);
std::string report() const; // reads the committed tables
private: store::Store<EnrollmentTables>* store_; // non-owning int fee_; // charged for each seat};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The enroll use case. All of its work is the lambda passed to// in_transaction, which runs it on the transaction's copy of the tables// and commits if it says it changed something. `[&]` lets the lambda use// `student`, `code` and this registrar's fee_ by reference; they all// outlive the call. The reply is the `.reply` of the Result that// in_transaction returns. If the commit fails, no reply is returned: the// exception goes to the caller instead.std::string Registrar::enroll(const domain::StudentId& student, const domain::CourseCode& code) { return in_transaction(*store_, [&](EnrollmentTables& tables) { // Look both aggregates up in the copy. find returns an // iterator: end() means "not there", and otherwise // course->second is the Course itself (->first is the key). const auto course = tables.courses.find(code); if (course == tables.courses.end()) return Result{"no_such_course", false}; const auto load = tables.loads.find(student); if (load == tables.loads.end()) return Result{"no_such_student", false};
// Three changes, one transaction: the course, the load, and // the charge message. A refusal commits nothing, even if a // step had already changed the copy. // The domain service changes the copied load and course in // place (they are references into the copy, not into the // store), and says what happened. const domain::EnrollDecision decision = domain::enroll(load->second, course->second); // Seated and waitlisted change both aggregates; the two // refusals, already_in_course and at_course_limit, change // neither, so there is nothing to commit. const bool changed = decision.status == domain::EnrollStatus::seated || decision.status == domain::EnrollStatus::waitlisted; // Turn the course's recorded events into outbox messages in // the same copy: a seat adds one ChargeMessage, and a // waitlist place adds none, but its event is still taken // out of the course. if (changed) queue_charges(tables, course->second, fee_); return Result{name(decision.status), changed}; }) .reply;}How this code works: One enroll request through the layers, and a failed commit
This follows the run’s third request, enroll S3 MA101, and the commit fails, from main down to the store and back. Before it, the five
set-up calls and the first two enrollments have made 7 commits, so the store’s
version_ is 7, the outbox holds m1 (S1 CS101), and next_message
is 2.
Who owns what. main owns both stores as local variables. The
Registrar holds a non-owning pointer to the enrollment store. The
Transaction is a local variable inside in_transaction, and owns its
copy of the tables. The domain objects being changed are entries in
that copy. Nothing below main owns the store.
mainto the application.stepruns its lambda, which callsregistrar.enroll(S3, MA101).- The use case hands its work to
in_transaction.enrollpasses the store and a lambda; this is the only place the use case meets transactions. - Begin.
in_transactionmakes aTransaction, which copies all ofEnrollmentTables(both courses, the three loads, the outbox withm1, andnext_message2) and notes base version 7. - The work, on the copy. The lambda finds MA101 and S3 in the
copy.
domain::enrolladds MA101 to the copied load and seats S3 in the copied course, which recordsStudentSeated. The result isseated, sochangedis true, andqueue_chargesturns the event intom2(S3 MA101, amount 100) at the back of the copied outbox and moves the copiednext_messageto 3. - Commit fails.
commitchecks: not yet committed; version 7 still equals base 7; butfail_next_commit_is true, sostd::exchangeclears it andcommitthrowsstore::Refused. - Unwinding.
Refusedis not caught by thecatchforConflict, so it leaves the loop body. TheTransactionis destroyed: one rollback, and the copy holding S3’s seat, S3’s load change andm2is freed. The exception then leavesin_transactionandRegistrar::enrollwithout a reply, andstepcatches it and printsfailed: the store refused the commit.
State after the failure. The committed tables are exactly as
before the request: MA101 seats no one, S3 takes no course, the outbox
holds only m1, and next_message is still 2, so the next message
will be m2 again. version_ is still 7, the forced failure is used
up, and the store has counted one rollback. The next request, enroll S3 CS101, begins from version 7 and commits normally, making it 8.
queue_charges takes the course’s events and adds a ChargeMessage
for each student who was seated or promoted, in the same tables. The
message carries the amount, the registrar’s fee at the time, so a
fee changed later does not change a charge already decided. It uses
an overloaded visitor with one handler per event type, as on the DDD
page, so a new event type is a compile error until someone decides
whether it is charged. The message is therefore committed in the same
transaction as the seat: if the commit fails, neither exists, and if
it succeeds, both do. A
promotion during drop produces a StudentPromoted event, so the
promoted student’s charge is queued by the same code, which fixes the
flawed example’s forgotten promotions.
domain::enroll only gives the basic guarantee, as noted above, but
it works on the transaction’s copy. If it threw halfway, the copy
would be dropped, so the use case as a whole has the strong guarantee.
One aggregate per transaction, and when not
Section titled “One aggregate per transaction, and when not”A common guideline in domain-driven design is to change one aggregate per transaction. Its reasons are real:
- an aggregate is drawn around the rules that must hold immediately, so a rule spanning two aggregates is often a sign the boundary is wrong;
- a smaller transaction overlaps with fewer others, so it conflicts, or waits, less often;
- aggregates in one transaction must live in one store, which stops them being stored apart later.
enroll breaks the guideline on purpose. The three-course limit
lives in StudentLoad, the seats live in Course, and the DDD
page chose to keep them as two
aggregates with a domain service between them. Both changes must be
true together, immediately, and here both are in one store, so one
transaction is the simple and correct choice.
The alternative is to follow the guideline: change one aggregate in
one transaction, and the other in a second, triggered by a message.
The order matters. Change first the aggregate whose rule can
refuse: StudentLoad::join can say at_limit, while Course::enroll
always seats or waitlists a student it does not already hold. Joining
the load first and enrolling in the course by message never breaks
the limit, and needs no undo for it. The other order, seat first and
count second, allows a moment in which a student holds four courses,
and needs code to undo the seat.
Even in the good order, two transactions cost something: a moment in which the load counts a course whose list does not yet show the student, a message to deliver and make idempotent, and more failure cases to test. That is worth paying when the two aggregates must live in different stores, or when one transaction would conflict too often. The charge already follows the guideline: the account is changed in its own transaction, in its own store.
The outbox and the relay
Section titled “The outbox and the relay”The account belongs to billing:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An aggregate in another part of the system, with its own store. It// remembers which charges it has taken, so a message delivered twice is// charged once. It lives only inside BillingTables, so it is changed only// through a transaction on billing's store.class Account {public: // A new account owes nothing and has taken no charges. explicit Account(domain::StudentId student) : student_{std::move(student)} {}
const domain::StudentId& student() const { return student_; } int owed() const { return owed_; }
// Adds the amount once per charge id. A repeated id changes nothing // and returns false. Remembering the id and adding the amount happen in // the same object, so they are committed together or not at all: a // receiver built this way is idempotent (doing it twice has the same // effect as doing it once). bool charge(const std::string& charge_id, int amount);
private: domain::StudentId student_; int owed_ = 0; std::set<std::string> taken_; // charge ids already applied};
// Everything billing's store holds: one account per student, created the// first time that student is charged. Store<BillingTables> is a second,// separate store; no transaction can span it and the enrollment store.struct BillingTables { std::map<domain::StudentId, Account> accounts;};The two stores share no transaction, so moving a message from the outbox to billing takes two: one that charges the account, and one that removes the message.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Moves committed charge messages from the enrollment store to billing.// The two stores share no transaction, so each message takes two:// charge the account in billing's store, then remove the message from// the outbox. If the second fails, the message stays and is delivered// again; the account ignores a charge id it has already taken.class BillingRelay {public: // Both stores must outlive the relay; it owns neither. BillingRelay(store::Store<EnrollmentTables>& enrollment, store::Store<billing::BillingTables>& billing) : enrollment_{&enrollment}, billing_{&billing} {}
// Handles every waiting message, oldest first; returns how many. // If a commit in either store fails, the exception stops the loop and // reaches the caller; the message that failed, and every later one, // stay in the outbox for the next call. int deliver();
private: store::Store<EnrollmentTables>* enrollment_; // non-owning store::Store<billing::BillingTables>* billing_; // non-owning};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One message at a time, oldest first, each in two transactions: charge in// billing's store, then remove from the enrollment outbox. The loop runs// until the committed outbox is empty. If either in_transaction call// throws (a Refused commit, or a Conflict on the last attempt), the// exception leaves deliver at once: everything committed before it stays// committed, and the message being handled is still in the outbox.int BillingRelay::deliver() { int delivered = 0; // messages handled, including repeats billing ignored while (!enrollment_->committed().outbox.empty()) { // A copy of the oldest committed message, not a reference: each // commit to the enrollment store replaces its tables, and a // reference into the old outbox would then point at destroyed data // (for example, if the removal's work were rerun after a conflict). const ChargeMessage message = enrollment_->committed().outbox.front();
// Transaction 1, in billing's store: one aggregate, the account. // The return value of in_transaction is not needed here. in_transaction(*billing_, [&](billing::BillingTables& tables) { // try_emplace finds the student's account, or makes a new one // (Account{message.student}) in the copy if there is none. // It returns a pair; .first is an iterator to the entry. auto account = tables.accounts.try_emplace(message.student, message.student).first; // charge returns false for an id the account has already taken. // Then changed is false, nothing is committed, and the owed // amount stays as it was: this is what makes a repeat harmless. const bool charged = account->second.charge(message.id, message.amount); return Result{charged ? "charged" : "already_charged", charged}; }); // If billing's commit threw (store::Refused), we never get here: // billing's copy was dropped, so no account and no charge was kept, // and the message is still in the outbox for the next call.
// Transaction 2, in the enrollment store: the message is done. in_transaction(*enrollment_, [&](EnrollmentTables& tables) { // Remove it only if it is still at the front of this // transaction's copy. If it is gone (something else removed // it), nothing changes and nothing is committed. const bool first = !tables.outbox.empty() && tables.outbox.front().id == message.id; if (first) tables.outbox.pop_front(); return Result{"removed", first}; }); // If this commit threw, the charge above is kept in billing but the // message stays in the outbox. The next deliver sends it again, and // the account's repeat check keeps the student from paying twice. ++delivered; } return delivered;}How this code works: BillingRelay::deliver, and what each failure leaves
deliver reads the committed outbox, takes a copy of its oldest
message, and runs two separate in_transaction calls, one per store.
Neither store knows about the other, so there is no moment at which
both changes are kept together. The order is chosen so that any
failure leaves the message in the outbox.
| Where it fails | Billing afterwards | Enrollment outbox afterwards | What the next deliver does |
|---|---|---|---|
| billing’s commit (transaction 1) | nothing kept, not even a new account | the message is still first | charges it, then removes it |
| the removal (transaction 2) | the charge is kept | the message is still first | billing ignores the repeat, then it is removed |
| no failure | the charge is kept | the message is removed | moves on to the next message |
In every row a throw leaves deliver at once, so later messages wait
too. Here is the run’s own sequence. Before the first call the outbox
holds m1 (S1 CS101) and m2 (S2 CS101), the enrollment store has
committed 9 times, and its next commit is set to fail.
| Call and message | Transaction 1 (billing) | Transaction 2 (enrollment) | Result |
|---|---|---|---|
first, m1 |
S1’s account is created, charged 100, committed | removing m1 is refused: rollback |
failed; S1 owes 100 |
second, m1 |
m1 already taken: changed false, no commit |
m1 is first, removed, commit 10 |
loop goes on |
second, m2 |
S2’s account is created, charged 100, committed | m2 is first, removed, commit 11 |
outbox empty: 2 delivered |
delivered counts m1 on the second call even though billing charged
nothing for it: it counts messages handled, not charges made. The
enrollment store ends the run with 11 commits and 2 rollbacks, the two
forced failures, which is the last line of the output.
The order of the two transactions decides what can go wrong:
- Charge, then remove (the example). If the removal fails, the message is still waiting and is delivered again: delivery happens at least once. The account remembers each charge id it has taken, so a repeat changes nothing; the receiver is idempotent. Together they behave as “exactly once in effect”.
- Remove, then charge. If the charge fails, the message is gone and the student is never charged: at most once. That is acceptable only for messages it is fine to lose.
Two smaller choices:
messageis a copy, not a reference into the outbox. A commit to the enrollment store replaces its committed tables. If the removal’s work were rerun after a conflict, another commit would already have replaced the tables a reference pointed into, and it would refer to destroyed data.- The message is read outside a transaction, which “Common mistakes” below warns against. It is safe here because nothing is decided from that read alone: the charge ignores a repeat, and the removal checks the id again inside its own transaction.
- The removal checks that the front message is still the one just delivered. If something else, such as a second relay, already removed it, nothing is removed and nothing is committed.
This also answers the overview’s question. A drop stands even if telling another part of the system fails: the drop and its message are committed together, and the message is delivered later, again if needed.
The same outbox could carry “you have a seat” emails for promoted students, but an email shows where idempotency stops. The account can ignore a repeat because remembering the id and changing the amount commit together, in billing’s transaction. An email sender cannot make “send” and “remember that I sent” one step: remembering first loses the email if it crashes before sending, and sending first sends it twice if it crashes before remembering. Unless the email provider accepts an idempotency key of its own, a rare duplicate is the price of never losing one.
Text description of the diagram
A sequence diagram with four participants: the BillingRelay, the enrollment Store, the billing Store, and S1’s Account. The relay reads the first committed message from the enrollment store, m1 for S1. It begins transaction 1 in the billing store, which copies billing’s tables, and asks the account to charge m1 for 100. The account replies charged and records m1 as taken, and the relay commits, so S1 owes 100. The relay then runs transaction 2 in the enrollment store to remove m1 from the outbox, but that commit fails and m1 stays. Later, deliver runs again. The relay reads the first committed message, which is m1 again, and asks the account to charge m1 for 100. The account replies that m1 is already taken, so nothing changes and nothing is committed. The relay removes m1 and commits.
Diagram source (Mermaid)
sequenceDiagram
participant R as BillingRelay
participant E as enrollment Store
participant B as billing Store
participant A as Account S1
R->>E: read the first committed message, m1 for S1
R->>B: transaction 1 begins, copying billing's tables
R->>A: charge m1, 100
A-->>R: charged, m1 is now taken
R->>B: commit, S1 owes 100
R->>E: transaction 2, remove m1 from the outbox
E-->>R: the commit fails, m1 stays
Note over R,E: deliver runs again later
R->>E: read the first committed message, m1 again
R->>A: charge m1, 100
A-->>R: already taken, nothing changes and nothing is committed
R->>E: remove m1, commitclass store::Store<Tables>
the committed tables
Data members
Tables tables_;std::uint64_t version_;counts commits
Member functions
const Tables& committed() const;int commits() const;and rollbacks()void fail_next_commit();for the demonstration and the tests
class store::Transaction<Tables>
RAII, begun on construction
Data members
Store<Tables>* store_;non-owningTables working_;std::uint64_t base_version_;
Member functions
explicit Transaction(Store<Tables>& store);copies the tables, the store must outlive this~Transaction();a rollback, if not committedTables& tables();the private copyvoid commit();throws Conflict or Refused, or keeps everything
namespace app
one transaction per use case
Functions
Result in_transaction(store::Store<Tables>& store, Work work, int attempts = 3);templatestruct EnrollmentTables { courses; loads; outbox; next_message; };
class app::Registrar
the use cases
Data members
store::Store<EnrollmentTables>* store_;non-owningint fee_;copied into each charge message
Member functions
Registrar(store::Store<EnrollmentTables>& store, int fee);std::string enroll(const domain::StudentId& student, const domain::CourseCode& course);std::string drop(const domain::StudentId& student, const domain::CourseCode& course);
class app::BillingRelay
outbox to billing, at least once
Data members
store::Store<EnrollmentTables>* enrollment_;non-owningstore::Store<billing::BillingTables>* billing_;non-owning
Member functions
int deliver();returns how many were delivered
class billing::Account
its own aggregate, in its own store
Data members
int owed_;std::set<std::string> taken_;charge ids already applied
Member functions
bool charge(const std::string& charge_id, int amount);once per id
Running it
Section titled “Running it”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The composition root and a scripted run. step(label, use_case), defined// above, prints the label, runs the lambda, and prints its reply, or// "failed: " and the exception's message if it throws. Each lambda// captures by reference ([&]) the registrar or relay it calls.int main() { // Two separate stores, declared first so that they outlive the // registrar and the relay, which keep pointers to them. Locals are // destroyed in reverse order, so the stores go last. store::Store<app::EnrollmentTables> enrollment; store::Store<billing::BillingTables> billing; app::Registrar registrar{enrollment, 100}; // a fee of 100 per seat app::BillingRelay relay{enrollment, billing};
// Set-up: five transactions, five commits. CS101 has a single seat. registrar.add_course(code("CS101"), "Software Design", 1); registrar.add_course(code("MA101"), "Linear Algebra", 30); for (const char* id : {"S1", "S2", "S3"}) registrar.add_student(student(id));
// S1 takes the only seat and queues m1; S2 is waitlisted (no message). step("enroll S1 CS101", [&] { return registrar.enroll(student("S1"), code("CS101")); }); step("enroll S2 CS101", [&] { return registrar.enroll(student("S2"), code("CS101")); }); // The next commit to the enrollment store will throw store::Refused. // The seat in MA101, S3's load, and the m2 message were all made in the // transaction's copy, and all three are dropped with it. enrollment.fail_next_commit(); step("enroll S3 MA101, and the commit fails", [&] { return registrar.enroll(student("S3"), code("MA101")); }); step("enroll S3 CS101", [&] { return registrar.enroll(student("S3"), code("CS101")); }); std::cout << registrar.report();
// Frees S1's seat: S2 is promoted, and m2 for S2 is queued in the same // transaction as the promotion. step("drop S1 CS101", [&] { return registrar.drop(student("S1"), code("CS101")); }); std::cout << registrar.report();
// The relay charges m1 in billing (committed there), then fails to // remove m1 from the outbox: S1 owes 100 and m1 is still waiting. enrollment.fail_next_commit(); step("deliver, and removing the first message fails", [&] { return std::to_string(relay.deliver()) + " delivered"; }); print_accounts(billing); // m1 again (billing sees a repeat and charges nothing), then m2. step("deliver again", [&] { return std::to_string(relay.deliver()) + " delivered"; }); print_accounts(billing); std::cout << registrar.report();
std::cout << "enrollment store: " << enrollment.commits() << " commits, " << enrollment.rollbacks() << " rollbacks\n";}> enroll S1 CS101seated> enroll S2 CS101waitlisted> enroll S3 MA101, and the commit failsfailed: the store refused the commit> enroll S3 CS101waitlistedCS101: seated S1; waiting S2 S3MA101: seated none; waiting noneS1 takes CS101S2 takes CS101S3 takes CS101outbox: m1 (S1 CS101)> drop S1 CS101left_seatCS101: seated S2; waiting S3MA101: seated none; waiting noneS1 takes noneS2 takes CS101S3 takes CS101outbox: m1 (S1 CS101) m2 (S2 CS101)> deliver, and removing the first message failsfailed: the store refused the commitS1 owes 100> deliver again2 deliveredS1 owes 100S2 owes 100CS101: seated S2; waiting S3MA101: seated none; waiting noneS1 takes noneS2 takes CS101S3 takes CS101outbox: emptyenrollment store: 11 commits, 2 rollbacksReading the output:
- S1 takes CS101’s only seat, and S2 is waitlisted. Only S1’s seat
queues a charge,
m1. - Enrolling S3 in MA101 changes a copy of all three tables, and the commit fails. The report shows that nothing was kept: MA101 has no one seated, S3’s load does not count it, and there is no charge message for it.
- S3 is then waitlisted for CS101. A waitlisted course counts towards
the load, so the report shows
S3 takes CS101. - Dropping S1 promotes S2, and the same transaction queues
m2for S2. - The first
delivercharges S1 form1in billing, and then the removal ofm1fails, so the exception stops the loop. S1 owes 100, andm1is still in the outbox. - The second
deliversendsm1again, which the account ignores, and thenm2. S1 still owes 100, not 200, and the outbox is empty. - S1 dropped CS101 and still owes 100: in this example the fee is not
refunded. A refund would be one more message, queued by
dropwhen a seat is left, in the same transaction. - The enrollment store saw 11 commits and 2 rollbacks: the two forced failures. A transaction that changes nothing also ends in a rollback, since there is nothing to keep; the relay’s repeated charge did that in the billing store, which is not counted here.
Testing
Section titled “Testing”The store, with a table of plain numbers, so the tests are about
transactions and not about courses. The conflict test makes another
transaction commit while the work is running, and checks that the
work ran twice and the second run saw the other’s change. The last
test is overtaken on every attempt, and checks that in_transaction
gives up after three and lets the Conflict through:
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. The tables here are Numbers, a struct holding one// std::vector<int>, so the tests are about transactions alone.
// Rollback by scope: the inner { } block ends, the transaction's// destructor runs without a commit, and the change to the copy is lost.LLD_TEST(a_transaction_destroyed_without_commit_changes_nothing) { store::Store<Numbers> store; { store::Transaction<Numbers> transaction{store}; transaction.tables().values.push_back(1); // changes the copy only } // destroyed here: a rollback LLD_CHECK(store.committed().values.empty()); LLD_CHECK_EQ(store.rollbacks(), 1);}
// A forced failure keeps nothing, and is used up by that one commit: the// next transaction commits normally.LLD_TEST(a_failed_commit_keeps_nothing_and_the_next_one_works) { store::Store<Numbers> store; store.fail_next_commit(); { store::Transaction<Numbers> transaction{store}; transaction.tables().values = {1, 2, 3}; LLD_CHECK_THROWS(transaction.commit(), store::Refused); } LLD_CHECK(store.committed().values.empty()); store::Transaction<Numbers> transaction{store}; transaction.tables().values = {4}; transaction.commit(); LLD_CHECK(store.committed().values == std::vector<int>{4});}
// Two transactions begin from the same version (0). The first to commit// moves the version to 1, so the second's commit sees a different version// and throws Conflict instead of overwriting the first one's work.LLD_TEST(the_second_of_two_overlapping_commits_is_refused) { store::Store<Numbers> store; store::Transaction<Numbers> first{store}; store::Transaction<Numbers> second{store}; first.tables().values.push_back(1); second.tables().values.push_back(2); first.commit(); LLD_CHECK_THROWS(second.commit(), store::Conflict); LLD_CHECK(store.committed().values == std::vector<int>{1}); // the first is not lost}
// The work counts its runs. On the first run only, another transaction// commits {1} while this one's copy is still the empty one, so the work// pushes 0 + 10 = 10 into a stale copy and its commit is a Conflict. The// second run gets a fresh copy, {1}, pushes 1 + 10 = 11, and commits.LLD_TEST(a_conflict_reruns_the_whole_work_on_fresh_tables) { store::Store<Numbers> store; int runs = 0; app::in_transaction(store, [&](Numbers& numbers) { if (++runs == 1) { // ++runs first adds one, then compares // Another transaction commits while this one is working. store::Transaction<Numbers> other{store}; other.tables().values.push_back(1); other.commit(); } // The value depends on what the copy holds, so it shows which // tables the run saw. size() is unsigned; static_cast makes it int. numbers.values.push_back(static_cast<int>(numbers.values.size()) + 10); return app::Result{"done", true}; }); LLD_CHECK_EQ(runs, 2); LLD_CHECK(store.committed().values == (std::vector<int>{1, 11}));}
// Every run is overtaken by another commit, so every commit conflicts.// After the third, in_transaction rethrows the Conflict. The others'// commits {1}, {1, 2}, {1, 2, 3} are kept; the work's zeros never are.LLD_TEST(in_transaction_gives_up_after_its_attempts) { store::Store<Numbers> store; int runs = 0; const auto always_overtaken = [&](Numbers& numbers) { ++runs; store::Transaction<Numbers> other{store}; // commits first, every time other.tables().values.push_back(runs); other.commit(); numbers.values.push_back(0); return app::Result{"done", true}; }; LLD_CHECK_THROWS(app::in_transaction(store, always_overtaken, 3), store::Conflict); LLD_CHECK_EQ(runs, 3); LLD_CHECK(store.committed().values == (std::vector<int>{1, 2, 3})); // none of the work's zeros}The use cases, checking all three tables after each one. A forced failed commit must leave the course, the load, and the outbox as they were:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each test makes a fresh World (defined above the snippet): an enrollment// store, a registrar with a fee of 100, course CS101 with one seat, and// students S1 and S2. world.tables() is the store's committed tables, so// every check reads only what a commit kept.
// One seat taken: the course, the load and the outbox all changed.LLD_TEST(an_enrollment_and_its_charge_message_commit_together) { World world; LLD_CHECK_EQ(world.registrar.enroll(student("S1"), code("CS101")), std::string{"seated"}); LLD_CHECK(world.tables().courses.at(code("CS101")).contains(student("S1"))); LLD_CHECK_EQ(world.tables().loads.at(student("S1")).courses().size(), std::size_t{1}); LLD_CHECK_EQ(world.tables().outbox.size(), std::size_t{1}); LLD_CHECK_EQ(world.tables().outbox.front().amount, 100);}
// The commit is forced to fail: the exception reaches the test, and none of// the three tables shows any trace of the enrollment.LLD_TEST(a_failed_commit_keeps_none_of_the_three_changes) { World world; world.store.fail_next_commit(); LLD_CHECK_THROWS(world.registrar.enroll(student("S1"), code("CS101")), store::Refused); LLD_CHECK(!world.tables().courses.at(code("CS101")).contains(student("S1"))); LLD_CHECK(world.tables().loads.at(student("S1")).courses().empty()); LLD_CHECK(world.tables().outbox.empty());}
// A refusal is a reply, not an exception, and it does not commit: the// store's commit count is the same after two refusals.LLD_TEST(a_refusal_commits_nothing) { World world; world.registrar.enroll(student("S1"), code("CS101")); const int commits = world.store.commits(); LLD_CHECK_EQ(world.registrar.enroll(student("S1"), code("CS101")), std::string{"already_in_course"}); LLD_CHECK_EQ(world.registrar.enroll(student("S9"), code("CS101")), std::string{"no_such_student"}); LLD_CHECK_EQ(world.store.commits(), commits);}
// The charge follows the seat: S2 waits with no message, and S1's drop// promotes S2 and queues S2's message in the same transaction.LLD_TEST(a_waitlisted_student_is_charged_when_promoted) { World world; world.registrar.enroll(student("S1"), code("CS101")); world.registrar.enroll(student("S2"), code("CS101")); // waitlisted: no charge yet LLD_CHECK_EQ(world.tables().outbox.size(), std::size_t{1}); LLD_CHECK_EQ(world.registrar.drop(student("S1"), code("CS101")), std::string{"left_seat"}); LLD_CHECK_EQ(world.tables().outbox.size(), std::size_t{2}); LLD_CHECK(world.tables().outbox.back().student == student("S2"));}The relay, with a failure between its two transactions and a failure in the first:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each test makes a fresh World (defined above the snippet): the two// stores, a registrar, a relay, and S1 already seated in CS101, so one// charge message for 100 is waiting. owed() reads S1's committed account.
// A failure between the two transactions: billing has charged, but the// message is not removed. The second deliver sends it again; the account// ignores the repeat, and only then is the message removed.LLD_TEST(a_message_delivered_twice_is_charged_once) { World world; world.enrollment.fail_next_commit(); // the charge commits, removing the message fails LLD_CHECK_THROWS(world.relay.deliver(), store::Refused); LLD_CHECK_EQ(world.owed(), 100); LLD_CHECK_EQ(world.enrollment.committed().outbox.size(), std::size_t{1}); LLD_CHECK_EQ(world.relay.deliver(), 1); // delivered again LLD_CHECK_EQ(world.owed(), 100); LLD_CHECK(world.enrollment.committed().outbox.empty());}
// A failure in the first transaction: billing keeps nothing (not even a// new, empty account), and deliver stops before the removal, so the// message waits and the next deliver charges it.LLD_TEST(a_failed_charge_leaves_the_message_waiting) { World world; world.billing.fail_next_commit(); LLD_CHECK_THROWS(world.relay.deliver(), store::Refused); LLD_CHECK(world.billing.committed().accounts.empty()); LLD_CHECK_EQ(world.enrollment.committed().outbox.size(), std::size_t{1}); LLD_CHECK_EQ(world.relay.deliver(), 1); LLD_CHECK_EQ(world.owed(), 100);}The forced failure is what makes these tests possible: each failure point can be reached on purpose, in a test that runs in milliseconds. A store adapter for a real database would need the same ability, for example by wrapping its connection in a test double that fails on request.
The costs, and when this fits
Section titled “The costs, and when this fits”The design costs:
- A function every use case goes through, and work written as a lambda that may run more than once.
- An outbox and a relay: another table, another loop to run and monitor, and a delay before billing is up to date.
- Remembered ids in every receiver. The account’s set of charge ids grows forever; a real receiver keeps them for a bounded time, or in a table that is cleaned up.
- Retries that can fail after
attemptstries, which the caller must report. - A message that always fails blocks the queue.
deliverstops at the first failure, so a message billing can never accept would stop every later one. Real relays count attempts and move such a message aside, to a “dead letter” queue that people look at.
It fits when:
- a use case changes more than one thing that must agree, such as a seat and a load;
- other parts of the system must hear about changes, and losing or doubling a message has a cost, as charging does;
- more than one request can change the same data at a time.
It is more than needed when:
- each use case changes one record in a store that already makes single writes atomic;
- the program has one user and no other systems, and a lost change can simply be made again;
- the store’s own transactions are used directly by one small
application layer: there, a function like
in_transactionover the database’s transaction is all that is needed, without a store of your own.
Common mistakes
Section titled “Common mistakes”- Calling another system inside the transaction. The call happens even if the commit then fails, and again on every retry. Record the intention in an outbox and act after the commit.
- Retrying only the commit. After a conflict, the decisions in the work are out of date. Rerun the whole work, on fresh data.
- Retrying on every exception. A refused rule or a bug will fail the same way each time. Retry what is known to be temporary, such as a conflict.
- Reading outside the transaction and writing inside it. Checking
store.committed()for a free seat and then seating in a transaction makes the check invisible to the conflict detection. Read what the decision depends on through the transaction’s tables. - Holding references into committed data across a commit. A
commit replaces the tables, so the references dangle. Copy what is
needed, as
delivercopies the message. - Transactions that wait for people. Opening a transaction when a form is shown and committing when it is submitted keeps stale copies for minutes and conflicts with everyone else. Begin it when the request arrives.
- A receiver that trusts delivery to happen once. With at-least-once delivery, repeats are normal, not errors.
When the requirements change
Section titled “When the requirements change”- A real database replaces the in-memory store.
Transactionbecomes a wrapper around the database’s transaction, and the database’s “could not serialize” or “row changed” failure is translated intoConflict. Many databases report such failures only at a stricter isolation level than their default, or when each row carries a version that an update checks, so that must be chosen on purpose. The domain and the shape ofin_transactioncarry over. The work does not: it changes whole in-memory maps here, and would instead go through repositories, as on the repository page, while the relay and the report would read through a transaction instead ofcommitted(). - Unrelated enrollments conflict too often. This store has one version for everything, so any two overlapping commits conflict, even for different courses. Give each aggregate its own version, as the repository page describes, and refuse a commit only if an aggregate it read has changed.
- Billing becomes a separate service over a network. The relay sends the message instead of opening billing’s store, and billing keeps the charge ids. Nothing in the enrollment use cases changes: they still only write to the outbox.
- Several relays run at once. Each message may then be delivered by two relays, which idempotency already allows; the removal’s id check keeps them from removing the wrong message. To avoid the duplicated work, a relay can claim a message in a transaction before delivering it.
- The client retries a request whose reply was lost. The same
problem appears one level up: enrolling twice is harmless, because
the domain answers
already_in_course, but a request such as “pay 100” is not. The request then needs an id of its own, kept like the account’s charge ids; Idempotency, retries, and duplicate handling covers this.
Exercise
Section titled “Exercise”Exercise: Assign transaction ownership
A small shop’s place order use case must reserve stock for each
item (an Inventory aggregate per product), create an Order
aggregate, take payment through an external payment provider, and
send a confirmation email. Inventory and orders are in one database.
- Which code begins and commits the transaction, and why not the
Orderclass or theInventoryRepository? - Which changes go in one transaction?
- Where does the call to the payment provider go, relative to the transaction?
- Where does the email go, and what must the email sender do?
- Two customers try to buy the last unit at once. What happens, and which code handles it?
- The order’s items span several products. Does “one aggregate per transaction” apply, and what would following it cost?
Show the explained answer
- The application’s place-order use case, through one function
like
in_transaction.Orderdoes not know there is a database, and the repository knows one aggregate, not which changes make up one order. The web handler calls the use case and hears the result. - The stock reservations, the new order, and an outbox message asking for the payment. They must be true together: an order with no reserved stock, or reserved stock with no order, is wrong at once.
- Outside, after the commit, driven by an outbox message, with the order’s id as the payment’s idempotency key so a repeat is not charged twice. The outcome comes back as another use case, such as “payment confirmed” or “payment failed”, which updates the order in its own transaction and, on failure, releases the stock. Calling the provider inside the transaction would charge the card even when the commit failed, and again on each retry.
- In the outbox too, but queued by the “payment confirmed” use case, in its transaction, so no email confirms an unpaid order. Delivery is at least once, and sending an email cannot commit together with remembering that it was sent, so a rare duplicate is possible unless the email provider accepts an idempotency key. The sender can remember ids to make duplicates rarer; accepting the rest is a decision to write down.
- With optimistic concurrency, as in this page’s store, both
transactions read one unit and reserve it; the first to commit
wins, and the second gets a conflict. (With locking, the second
would wait, then read zero.)
in_transactionreruns the second customer’s whole use case on fresh data, where the domain now refuses: out of stock. The store detects the conflict, the application retries, and the domain decides. A real database detects it only if it is asked to, by its isolation level or by a version on the stock row. - The guideline would put each product’s reservation and the order in separate transactions, linked by messages. That allows moments in which an order exists with only some items reserved, and needs code to undo reservations when a later one fails. With everything in one database and orders of a few items, one transaction is simpler; the guideline becomes worth its cost if inventory moves to its own store or popular products conflict too often.
Summary
Section titled “Summary”- Failure atomicity, the strong guarantee: a use case happens completely or leaves no trace. Change a copy, then commit with steps that cannot throw.
- The application’s use case owns the transaction: one use case, one transaction, begun and committed in one place. The domain and the repositories do not commit, and the caller does not open one.
- An RAII transaction makes rollback the default: return, refuse, or throw, and nothing is kept.
- One aggregate per transaction is a good default that keeps transactions small; break it on purpose when a rule spans two aggregates in one store.
- A conflict reruns the whole use case on fresh data, so the work must have no effects outside the store.
- To change another store, write a message to an outbox in the same transaction, deliver it at least once, and make the receiver idempotent.