Aggregates & Factories
"Cluster the entities and value objects into aggregates and define boundaries around each. Choose one entity to be the root of each aggregate, and allow external objects to hold references to the root only" — Eric Evans, Domain-Driven Design Reference (2015), pattern "Aggregates"
Summary: An aggregate is a small cluster of entities and value objects with one root, one set of invariants and one transaction; everything outside it is referenced by identity and kept consistent eventually, and a factory is how a whole, valid aggregate comes into existence. Focus: The aggregate and its root, true invariants and the consistency boundary, Vernon's four rules (true invariants, small aggregates, reference by identity, eventual consistency outside) with their failure stories, the "whose job is it?" test, sizing symptoms in both directions, optimistic concurrency with a version on the root and retries, one aggregate per transaction and its four exceptions, lifecycle and identity, domain events and the outbox, one repository per aggregate, factories (standalone, factory method, reconstitution) versus constructors and Eloquent factories, and how aggregates map onto a modular monolith and microservices. Learning goal: Given a business rule list, draw aggregate boundaries that protect the true invariants and nothing more, implement the root with a version column, event recording and a factory in Go and Laravel, prove with tests that a concurrent edit cannot break an invariant, and move every cross-aggregate rule (for example "an order cannot be dispatched unpaid") onto events.
This chapter belongs to group DD 02 (Tactical Design). It builds on the two building blocks an aggregate is made of, Entities & Value Objects, and on the line around a model, Bounded Context. It owns the consistency boundary inside a context and how instances of it are created. The neighbours own the rest: why behaviour belongs on the root and not in services (Anemic vs Rich Domain Models), how aggregates are stored and found (Repositories), where logic that fits no aggregate lives (Domain, Application & Infrastructure Services), and what the root's events become on the wire (Domain Events vs Integration Events). Factory mechanics as a GoF pattern are in Creational Patterns; version columns and FOR UPDATE in depth are in Optimistic vs Pessimistic Locking; the cross-aggregate machinery is in Saga and Outbox.
The running example is the one used across the DDD path: an online ordering and fulfilment business with the contexts Sales, Fulfilment, Billing, Catalog and Identity. Here we design the Order aggregate in Sales and the Shipment aggregate in Fulfilment.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why a consistency boundary at all | Why aggregates exist |
| Evans 2003 to Vernon 2011, Helland, Dahan, Fowler | Where it comes from |
| Cluster, root, entry point | Aggregate and root |
| True vs false invariants, Rule 1 | Invariants and the consistency boundary |
| How big, contention, loading cost, Rule 2 | Design small aggregates |
| Ids not pointers, Eloquent lazy loading, Rule 3 | Reference by identity |
| "Whose job is it?", Rule 4 | Eventual consistency outside the boundary |
| The four reasons to break the rule | One aggregate per transaction |
Version column, retry, FOR UPDATE | Concurrency on the root |
| Creation, ids, "don't delete" | Lifecycle and identity |
| Root records events, outbox | Aggregates and domain events |
| One repository per aggregate | Aggregates and repositories |
| Standalone factory, factory method, reconstitution, Eloquent factories | Factories |
| Schema, save algorithm, error codes, per-product behaviour | Mechanics |
| Full Order and Shipment with tests | Go, Laravel |
| Giant Customer, aggregate-as-table, public setters | Solving the classic problems |
| Which boundary for which rule | Choosing |
| Monolith to distributed data | In architecture |
| Load only what you need, snapshots, read models | Performance |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concept catalogue.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Aggregate | A cluster of objects that is loaded, changed and saved as one unit | Order with its lines | Rules spread over many objects, nobody guards them |
| Aggregate root | The one entity outsiders may touch; it guards the rest | Order, not OrderLine | Code edits a line directly and breaks "max 20 lines" |
| Invariant | A rule that must be true after every transaction | total = sum of lines | Reports and invoices disagree |
| Consistency boundary | The line inside which invariants hold immediately | Order + lines, not Customer | Either nothing is protected or everything locks together |
| Reference by identity | Holding another aggregate's id, not the object | customerId, sku | Loading one order loads the whole database |
| Eventual consistency | Other aggregates catch up later, through events | Shipment created after OrderPaid | Giant transactions or lost updates |
| Version (optimistic lock) | A number on the root checked on every save | WHERE id = ? AND version = 7 | Two clerks silently overwrite each other |
| Factory | The code that assembles a whole, valid aggregate | OrderFactory::fromCart() | Half-built orders, invariants checked "later" |
| Reconstitution | Rebuilding an aggregate from storage, without creation rules or events | Order::reconstitute(...) | Loading an order re-fires OrderPlaced |
Vernon's four rules (each one is a block below):
| Rule | Plain words | Failure if ignored | Where |
|---|---|---|---|
| Model true invariants in consistency boundaries | Put inside only what must change together atomically | False invariants: unrelated edits conflict | Invariants |
| Design small aggregates | Root plus a few values; add entities only for a real rule | Contention, slow loads, memory | Small |
| Reference other aggregates by identity | Keep ids, look up when needed | Deep graphs, accidental multi-aggregate writes | By identity |
| Use eventual consistency outside the boundary | Cross-aggregate rules run later, in their own transactions | Giant transactions, distributed locks | Eventual |
Transactional or eventual? (the test from Vernon and Evans, details in Eventual consistency):
| Rule in our shop | Whose job is it to make it true? | Consistency | Mechanism |
|---|---|---|---|
| An order holds at most 20 lines | The shopper editing the order | Transactional, inside Order | Root checks; version column |
| Order total = sum of lines | The shopper | Transactional, inside Order | Derived, never stored separately |
| Stock is reserved for a placed order | The system (Inventory) | Eventual | OrderPlaced → saga step → compensation |
| An order cannot be dispatched unpaid | The system (Billing, Fulfilment) | Eventual | Shipment created only from OrderPaid |
| A customer's loyalty points reflect paid orders | The system | Eventual | Consumer of OrderPaid |
| A parcel dispatched marks the order dispatched | The system (Fulfilment) | Eventual | ParcelDispatched → Order.markDispatched() |
Why aggregates exist
Domain models have associations everywhere: an order has lines, lines point to products, the order belongs to a customer, the customer has addresses, payments and shipments. If any object may be changed by anyone at any time, there is no place where a rule such as "at most 20 lines" can be enforced, and no answer to the question what exactly does one transaction lock? Evans states the problem plainly in the DDD Reference: "It is difficult to guarantee the consistency of changes to objects in a model with complex associations." Locking more is not the answer either: "Cautious database locking schemes cause multiple users to interfere pointlessly with each other and can make a system unusable."
An aggregate answers both questions at once. It draws a line around a few objects, names one of them the root, and says: inside this line every rule holds after every transaction; outside it, nothing is promised immediately.
| Few large aggregates | Many small aggregates |
|---|---|
| Every rule can be checked in one transaction | Only true invariants are checked in one transaction |
| Unrelated edits conflict (one version for everything) | Edits to different aggregates never conflict |
| Loading cost grows with history | Loading cost bounded by design |
| Easy to write, feels "complete" | Needs events, sagas and a UI that accepts "pending" |
| Cannot be distributed: one unit, one node | Each aggregate can live on any node or shard |
| Good for: tiny, single-user tools | Good for: anything with concurrent users or growth |
The analogy we reuse on this page: the bill at a restaurant table. The waiter who owns your table owns your bill (the root). You can ask the waiter to add a dessert; you cannot walk into the kitchen and write on the kitchen's ticket (an internal part). The bill has rules: one currency, a total that equals the items, no items after it is paid. The kitchen (Fulfilment) gets a copy of the order and works on its own schedule; the payment terminal (Billing) is a different desk. Nobody locks the whole restaurant to pay one bill, and nobody expects the kitchen and the till to agree to the millisecond.
The picture shows the Order aggregate: one root holding id, status and version; lines and values inside the dashed boundary; the invariants the root enforces; outside code may only call the root; other aggregates appear as ids.
Three common misunderstandings, up front
- "An aggregate is an object graph, the bigger the better." Vernon: "aggregates are chiefly about consistency boundaries and not driven by a desire to design object graphs." A
Customerthat contains every order is the classic failure (Solving). - "An aggregate is a table (or an Eloquent model)." An aggregate is a domain concept that may span several tables (
orders,order_lines); and one Eloquent model per table with public attributes is the opposite of a root that guards its parts. - "All business rules must be checked in one transaction." Only the rules that must be true at every commit belong inside. Evans: "Within an aggregate boundary, apply consistency rules synchronously. Across boundaries, handle updates asynchronously."
Where it comes from
Evans, 2003. Domain-Driven Design (Addison-Wesley) introduced Aggregates, Factories and Repositories as the lifecycle patterns of Part II. The free DDD Reference (2015) restates them in short pattern form; we quote it throughout. It ties the boundary to transactions and distribution: "Use the same aggregate boundaries to govern transactions and distribution." and "Keep an aggregate together on one server. Allow different aggregates to be distributed among nodes."
Helland, 2007. Pat Helland's CIDR paper Life beyond Distributed Transactions: an Apostate's Opinion argued, from Amazon-scale experience, that scalable applications manipulate uniquely identified "entities" and that "Atomic Transactions Cannot Span Entities". Vernon later says of it: "What we call aggregate he calls entity."
Dahan, 2009. Udi Dahan's posts Don't Create Aggregate Roots (June 2009) and Don't Delete – Just Don't (September 2009) looked at the lifecycle: entities are created by a previous business state ("In any transition, the previous state is the aggregate root.") and are rarely deleted ("Orders aren’t deleted – they’re cancelled.").
Vernon, 2011. Vaughn Vernon's three-part essay Effective Aggregate Design (dddcommunity.org) gave the four rules of thumb used on this page, the "whose job is it?" test (which he credits to a discussion with Evans), and the four reasons to break the one-aggregate-per-transaction rule. The essay says it "is based on his upcoming book", Implementing Domain-Driven Design (2013), where it became the Aggregates chapter; we quote the essay, not the book.
Fowler, 2013. The bliki entry DDD_Aggregate (23 April 2013) is the short definition most people meet first: "A DDD aggregate is a cluster of domain objects that can be treated as a single unit."
Year Source What it added
1 2003 Evans, Domain-Driven Design Aggregate, root, factory, repository
2 2007 Helland, Life beyond Distributed Tx Entities as the unit of scale; no atomic tx across them
3 2009 Dahan, Don't Create Aggregate Roots Creation comes from a previous state (factory method)
4 2009 Dahan, Don't Delete - Just Don't Lifecycle ends in a business status, not DELETE
5 2011 Vernon, Effective Aggregate Design I-III Four rules, "whose job is it?", reasons to break rules
6 2013 Fowler, DDD_Aggregate bliki Load/save whole aggregates; tx never cross them
7 2015 Evans, DDD Reference Short pattern texts quoted on this pageThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, a comparison table, and the fix.
Aggregate and aggregate root Must-know
In plain words: an aggregate is a handful of objects that always travel together: you load all of them, change them through one door (the root), and save all of them in one transaction.
Common misunderstanding: "Any class with child collections is an aggregate root." Fowler warns that aggregates "are sometimes confused with collection classes"; and Dahan adds that "Aggregate roots aren’t a structural property of the domain model." A root is chosen because it protects a rule, not because it sits at the top of a tree.
Definition: an aggregate is a cluster of entities and value objects with a boundary and exactly one root entity. External objects may hold references only to the root ("references to internal members passed out for use within a single operation only", Evans). The root has global identity; inner entities have identity only within the aggregate. Invariants are defined for the aggregate as a whole and enforced by the root. Fowler: "Aggregates are the basic element of transfer of data storage - you request to load or save whole aggregates. Transactions should not cross aggregate boundaries."
The root's responsibilities:
| Responsibility | What it means in code | Our Order |
|---|---|---|
| Enforce invariants | Every command checks all rules before changing state | addLine checks status, currency, quantity, max lines |
| Expose behaviour, not data | Methods named in the ubiquitous language; no setters | place(), markPaid(), cancel() |
| Hide internals | Inner entities not reachable for mutation | line unexported in Go; immutable OrderLine in PHP |
| Be the only entry point | Repositories, services and other aggregates talk to the root | No OrderLineRepository |
| Own the concurrency token | One version for the whole boundary | version column on orders |
| Record what happened | Domain events collected on the root | OrderPlaced, OrderPaid, OrderCancelled |
Request: "add 2 mugs to order o-1"
1 App service: order = repo.get("o-1") loads root + lines (the whole boundary)
2 order.addLine("mug", 2, price) root checks: draft? same currency? 1..50? at most 20 lines?
3 root merges into its own line list no outside code touched a line
4 repo.save(order) UPDATE orders ... WHERE version = 7; rewrite lines; COMMIT
Wrong path: OrderLine::find(42)->update(['quantity' => 500]) -> no root, no rule, no version bumpReal scenario: an e-commerce order and its lines (classic); a clinic visit and its prescribed items; a playlist and its track positions (Fowler's examples); a bank transfer request with its legs; a seat map for one performance in a ticketing system.
Fix / how to use it: make inner entities unreachable for writes (unexported in Go, immutable value objects or private collections in PHP), give the root intention-revealing methods, and let the repository load and save only roots. The full code is in Go and Laravel.
Invariants and the consistency boundary (Rule 1) Must-know
In plain words: first list the rules that must be true at every commit; only the objects those rules touch go inside one aggregate.
Common misunderstanding: "If the business says products have backlog items, the backlog items go inside the product." Vernon's team did exactly that and invented rules such as "If a sprint has committed backlog items, we must not allow it to be removed from the system." His verdict: the large aggregate "was designed with false invariants in mind, not real business rules."
Definition: "An invariant is a business rule that must always be consistent." (Vernon, Part I). The consistency boundary "logically asserts that everything inside adheres to a specific set of business invariant rules no matter what operations are performed." Hence "aggregate is synonymous with transactional consistency boundary." A true invariant is one whose violation, even for a second, is a business error. A false invariant is a structural convenience presented as a rule.
Large Product aggregate (false invariants), optimistic locking on Product
Bill Joe
1 load Product v1 load Product v1
2 plan a backlog item; COMMIT -> v2
3 schedule a release; COMMIT -> fails: based on v1
"Nothing about planning a new backlog item should logically interfere with scheduling a new release!" (Vernon)Real scenario: in our shop, "at most 20 lines" and "total = sum of lines" are true invariants of Order. "The customer exists" is not: an order keeps a customerId, and Identity may deactivate the customer later. "Stock is available" is not: it is Inventory's rule, reached by a saga. A purchase order where "the sum of all line items must not surpass the total" (Evans' book example, as summarised by Vernon) has a true invariant that justifies lines inside the root.
How to tell them apart:
| Question | True invariant | False invariant |
|---|---|---|
| Is a second of violation a business error? | Yes (an invoice with a wrong total) | No (a stale "orders count" on the customer page) |
| Do experts state it, or did developers derive it from the class diagram? | Experts state it | Derived from "has" in a sentence |
| Does one user's action make it true? | Usually yes | Often another user or the system |
| What happens if it is enforced later by an event? | Visible bug | Small delay nobody notices |
Fix / how to use it: write the invariants down before drawing boxes (one line each, in the ubiquitous language), mark each as "same transaction" or "eventually", and draw the boundary around the first group only. In code, every command checks all invariants before mutating state, so a refused command leaves the aggregate unchanged (the Go test TestInvariantsRejectBeforeChangingState checks exactly that).
Design small aggregates (Rule 2) Must-know
In plain words: keep the root and the few values that must change with it; everything else becomes its own aggregate.
Common misunderstanding: "Small means one table per aggregate, or one field." Vernon: "The extreme would be an aggregate with only its globally unique identity and one additional attribute, which is not what's being recommended"; the right size is "the root entity and a minimal number of attributes and/or value-typed properties", where "The correct minimum is the ones necessary, and no more."
Definition: a small aggregate contains the root, value objects, and only those inner entities that a true invariant requires. Vernon reports from Niclas Hedhman's project that his team designed "approximately 70% of all aggregates with just a root entity containing some value-typed properties", the rest with two or three entities. Size is about what must load and lock together, not about lines of code.
Too large: Order inside Customer (one version on Customer)
1 09:00:01 tab A: customer.changeAddress() load Customer + 3,000 orders; COMMIT v41 -> v42
2 09:00:01 tab B: customer.placeOrder() load the same graph; COMMIT based on v41 -> conflict
3 09:00:02 warehouse: customer.orders[17].dispatch()conflict again; retry storms at peak
Too small: Order and OrderLine as separate aggregates (each with its own version)
1 T1 loads Order (19 lines counted by query) T2 loads Order (19 lines)
2 T1 inserts OrderLine #20; COMMIT T2 inserts OrderLine #21; COMMIT
3 -> 21 lines: the invariant "at most 20" lives in no single boundaryReal scenario: large-aggregate symptoms: frequent optimistic-lock failures on a hot root (a Product row touched by every sale), slow loads because a collection grows with history (all comments of a blog post, all bookings of a hotel), memory spikes in workers, and transactions that lock rows other users need. Too-small symptoms: rules re-implemented in sagas or nightly jobs, "check then insert" races between separate aggregates, and compensations for things that should simply have been refused.
| Symptom | Likely cause | Move |
|---|---|---|
Many ConcurrencyConflict on one root type | Unrelated edits share a version | Split along the conflicting use cases |
| Load time grows with the age of the record | Unbounded collection inside | Make the collection items their own aggregates, referenced by id |
| Command needs two aggregates' state to decide | Missing invariant, or wrong split | Merge parts into one aggregate (often with a new name) or use a domain service plus events |
| Saga compensates a rule that should never be broken | Boundary too small | Pull the rule's objects into one aggregate |
| Root has 40 methods and 15 collections | Several concepts in one | Find the hidden aggregates in the ubiquitous language |
Fix / how to use it: estimate the worst-case size with numbers (Vernon's Part III does a back-of-the-envelope count and ends with "25 objects maximum total"), favour value objects over inner entities, and measure conflicts and load times per aggregate type in production. Split only when a measurement or a new rule asks for it.
Reference other aggregates by identity (Rule 3) Must-know
In plain words: an order remembers the customer's id, not the customer object; when it needs the customer it asks for it, outside the order.
Common misunderstanding: "An object reference to another root is fine because it points to the root." Vernon: holding a reference "does not place the referenced aggregate inside the consistency boundary of the one referencing it", but it makes it trivially easy to modify both in one transaction and to load both every time.
Definition: "Prefer references to external aggregates only by their globally unique identity, not by holding a direct object reference". Dependent aggregates are looked up before calling the root: "Use a repository or domain service to look up dependent objects ahead of invoking the aggregate behavior." In the database this usually means no foreign key across aggregate (and certainly not across context) boundaries; inside one aggregate (order_lines.order_id) a foreign key is fine.
The picture shows five aggregates in five contexts. Order keeps customerId and sku values; Payment and Shipment keep the order id. The crossed solid arrow is the object graph we do not build.
Eloquent with object references (lazy loading)
1 $order = Order::find($id); SELECT * FROM orders WHERE id = ?
2 $order->customer->orders->count(); SELECT customers; SELECT all orders of the customer
3 $order->customer->name = 'X'; $order->push(); saves order AND customer: two aggregates, one tx
With identity references
1 $order = $orders->get($id); loads Order + lines only
2 $customer = $customers->get($order->customerId); explicit, separate read, outside the root
3 $orders->save($order); one aggregate savedReal scenario: an order page that renders the customer name with $order->customer->name and, three refactors later, a controller that changes the customer through the same path; a background job that serialises an order with every nested relation into a 4 MB payload; an N+1 storm when listing orders (see ORM Pitfalls). In Laravel, Model::preventLazyLoading() makes the temptation visible: "After preventing lazy loading, Eloquent will throw a Illuminate\Database\LazyLoadingViolationException exception when your application attempts to lazy load any Eloquent relationship."
| Reference style | Loads | Can modify both in one tx? | Distribution | Use when |
|---|---|---|---|---|
| Object reference, eager | Both always | Yes, easily | Impossible across nodes | Inside one aggregate only |
| Object reference, lazy | On first touch, hidden queries | Yes, accidentally | Impossible across nodes | Vernon's "Reason Four" exception: a measured query-performance need |
| Identity (typed id) | Only what you ask for | Only if you load both on purpose | Works across shards and services | Default between aggregates |
| Identity + read model | Prebuilt view | No (read only) | Works everywhere | Screens that show many aggregates together (CQRS) |
Fix / how to use it: typed ids (CustomerID, SKU, OrderRef) instead of objects; the application service loads what the command needs and passes values into the root; screens that combine many aggregates read from a query model, not from the domain model. Vernon names this cost directly: "You may have to use multiple repositories in a single use case to populate views", and points to CQRS when the query overhead hurts.
Use eventual consistency outside the boundary (Rule 4) Must-know
In plain words: when one change should cause another change in a different aggregate, record an event and let a separate transaction make the second change shortly after.
Common misunderstanding: "Eventual consistency is a technical compromise the business will not accept." Vernon: "Domain experts are sometimes far more comfortable with the idea of delayed consistency than are developers." Businesses ran on paper with delays of hours and days long before databases.
Definition: Vernon quotes Evans' book (p128): "Any rule that spans AGGREGATES will not be expected to be up-to-date at all times. Through event processing, batch processing, or other update mechanisms, other dependencies can be resolved within some specific time." The root records a domain event; subscribers each load their aggregate and change it in their own transaction; failures are retried until they succeed or a limit is reached, then compensated or reported.
Whose job is it? Vernon's tie-breaker, from a discussion with Evans: "ask whether it's the job of the user executing the use case to make the data consistent. If it is, try to make it transactionally consistent, but only by adhering to the other rules of aggregate. If it is another user's job, or the job of the system, allow it to be eventually consistent."
The map shows checkout. Only the first box is one transaction. Every dashed arrow is an asynchronous message processed in a separate transaction on one aggregate; the rule "an order cannot be dispatched unpaid" holds because a Shipment is only ever created from OrderPaid.
Cross-aggregate rule "an order cannot be dispatched unpaid", eventually consistent
1 Sales tx1: order.place() -> outbox: sales.order.placed.v1
2 Inventory tx2: reserve stock (saga) -> stock.reserved.v1 (or stock.rejected -> order.cancel())
3 Billing tx3: capture payment -> billing.payment.captured.v1
4 Sales tx4: order.markPaid() -> outbox: sales.order.paid.v1
5 Fulfilment tx5: Shipment::forPaidOrder(...) only constructor of Shipment; no OrderPaid, no shipment
6 Fulfilment tx6: shipment.dispatch() -> fulfilment.parcel.dispatched.v1
7 Sales tx7: order.markDispatched() root also refuses if not paid (defence in depth)Real scenario: stock reservation after order placement (saga with compensation if stock is gone, see Saga); loyalty points after payment; a backlog item status after task hours reach zero (Vernon's Part III, where the team asks whose job it is and finds a missing workflow preference); search index updates after a product change; a customer's "total spent" on a profile page.
| Option for a cross-aggregate rule | How | Advantage | Cost |
|---|---|---|---|
| Merge into one aggregate | Both parts inside one boundary | Atomic, simple | Bigger aggregate, more contention |
| Domain event + subscriber | Root records, outbox relays, handler updates the other aggregate | Small aggregates, independent scaling | Delay, retries, idempotency |
| Saga / process manager | State machine that issues commands and compensations | Multi-step, failure-aware | More code, timeouts (Saga) |
| Reconciliation job | Periodic check-and-fix | Catches what events missed | Long delay; still need events |
| Two aggregates, one transaction | Load both, save both | Immediate | Breaks the rule; acceptable only for the four reasons |
Fix / how to use it: for each cross-aggregate rule decide the acceptable delay with the domain expert, record a past-tense event on the root, publish it through an outbox, make each handler idempotent (Idempotent Consumers & Inbox), and show "pending" states in the UI rather than hiding the delay.
One aggregate per transaction, and the exceptions Important
In plain words: one command changes one aggregate instance and commits; if the use case needs more, the rest happens in later transactions.
Common misunderstanding: "A use case is a transaction." Vernon: "A user goal should not be viewed as synonymous with transaction." A checkout is one user goal and several transactions.
Definition: "a properly designed bounded context modifies only one aggregate instance per transaction in all cases." Vernon then calls it "a rule of thumb" and lists four reasons experienced practitioners break it.
| Reason (Vernon, Part II) | Example in our shop | Why it is acceptable | Guard rail |
|---|---|---|---|
| User interface convenience | Create 30 draft orders from a CSV upload in one request | Each new aggregate keeps its own invariants; batch = one by one | Only creation of independent aggregates |
| Lack of technical mechanisms | A legacy host with no queue, timer or background worker | Nothing else can deliver eventual consistency | Look for "user-aggregate affinity": one user per set of aggregates |
| Global transactions | Enterprise policy mandates two-phase commit (XA) | Policy, not design | Still modify one aggregate in your own context if you can |
| Query performance | A direct object reference to a rarely used, large part, lazily loaded | Measured performance need | Reference is read-only by convention |
Breaking the rule by accident (two aggregates, one tx, both versioned)
1 T1: load Order o-1 v3, Customer c-1 v9 T2: load Customer c-1 v9 (address change)
2 T1: order.place(); customer.addPoints() T2: customer.changeAddress(); COMMIT -> c-1 v10
3 T1: COMMIT -> Customer conflict -> the ORDER placement fails because of an address editReal scenario: a "place order and update customer statistics" transaction that fails whenever the customer edits their profile; an admin bulk action that modifies 500 orders in one transaction and holds locks for 40 seconds; an import job that is fine because it only creates aggregates.
Fix / how to use it: one command handler = load one aggregate, call one method, save; everything else is an event handler. If you must break the rule, write down which of the four reasons applies (an ADR line is enough).
Concurrency: the version on the root Must-know
In plain words: the root carries a number; every save says "only if the number is still what I read" and increments it; if someone else saved first, you reload and try again.
Common misunderstanding: "Only the root row needs a version when the root's own columns change." The version protects the whole boundary. If adding a line only inserts into order_lines without touching orders, two concurrent addLine calls both see 19 lines and both commit: 21 lines. The save must always update the root row with the version check, even when only a child changed.
Definition: optimistic concurrency control on an aggregate: the root has a version (integer or timestamp); load reads it; save executes a compare-and-set (UPDATE ... SET version = version + 1 WHERE id = ? AND version = ?); zero affected rows means a concurrent modification, which the application turns into a retry of the command on fresh state. Vernon's essay assumes exactly this: "Objects carry a version number that is incremented when changes are made and checked before they are saved to the database." Pessimistic locking (SELECT ... FOR UPDATE) is the alternative when conflicts are frequent and the work between read and write is short. Details and trade-offs: Optimistic vs Pessimistic Locking.
Max-lines race, version on the root (the protected version)
Client A Client B
1 load o-1: 19 lines, version 7 load o-1: 19 lines, version 7
2 addLine(tea): 20 lines OK addLine(cake): 20 lines OK (on its copy)
3 UPDATE orders ... WHERE version = 7 -> 1 row
4 rewrite lines; COMMIT (version 8)
5 UPDATE orders ... WHERE version = 7 -> 0 rows
6 ConcurrencyConflict -> retry: reload v8 (20 lines)
7 addLine(cake) -> ErrTooManyLines (final, not retried)Real scenario: two support agents editing the same order; a shopper with two tabs; a payment webhook and a cancellation arriving at the same second; the same PaymentCaptured message delivered twice to two workers.
| Strategy | How | Wins when | Loses when |
|---|---|---|---|
| Optimistic, version on root | Compare-and-set on save, retry command | Conflicts are rare; aggregates small | Hot aggregates: retry storms |
Pessimistic, FOR UPDATE on root | Lock root row at load, inside the tx | Short commands on hot aggregates (a seat map) | Long user think time; lock waits; deadlocks |
| Serializable isolation + retry | PostgreSQL SSI aborts with SQLSTATE 40001 | Rules span rows you cannot lock easily | Retries everywhere; needs a retry wrapper |
| Atomic single statement | UPDATE ... SET qty = qty - 1 WHERE qty > 0 | Counters with one rule | Rules that need the whole aggregate |
| Document store, one document per aggregate | MongoDB: "write operations are atomic on the single-document level" | Aggregate fits one document | Concurrent edits still need a version field |
| Conditional write | DynamoDB condition expression on a version attribute | Key-value aggregates | Error "The conditional request failed" must be retried by you |
Fix / how to use it: a version column on the root table, a repository that always bumps it, a ConcurrencyConflict error that is distinct from rule violations, and a bounded retry loop (3 attempts with small backoff) in the application service that reloads the aggregate. Never retry by re-saving the stale object. Rule violations (OrderRuleViolated, ErrTooManyLines) are never retried. There are no concurrent edits across aggregate instances to coordinate: each instance has its own version, which is exactly why small aggregates conflict less.
Aggregate lifecycle and identity Important
In plain words: an aggregate is born through a factory with an id, lives through business state changes, and usually ends in a final status (cancelled, closed, archived), not with a DELETE.
Common misunderstanding: "The database gives the aggregate its id when we insert it." Then events recorded before the first save have no id, and the factory cannot hand the id to anyone. Generate the identity before persistence.
Definition: the lifecycle is create (factory, invariants hold from the first moment, creation event recorded), reconstitute / change / save (many times, each time one transaction and one version bump), and end (a business status). Identity is global for the root (UUIDv7, ULID, or a sequence fetched before creation; see ID Generation); inner entities need only local identity (line position or SKU within the order). Dahan on the end of life: "Orders aren’t deleted – they’re cancelled. There may also be fees incurred if the order is canceled too late." On the start: "Customers don’t just appear out of thin air."
Lifecycle of Order o-1 (UUIDv7 generated by the factory)
1 create OrderFactory.fromCart -> Order(draft, version 0) no event yet (draft is private)
2 place order.place() -> OrderPlaced INSERT, version 1
3 pay order.markPaid() -> OrderPaid UPDATE ... version 1 -> 2
4 dispatch order.markDispatched() UPDATE ... version 2 -> 3
5 end status dispatched; after 7 years -> archived by retention job (no DELETE by users)Real scenario: "delete customer" that should be "close account" with retention rules; "delete product" that should be "discontinue" so old orders still show it (Dahan's example); GDPR erasure handled as an explicit command that anonymises, not as a cascade delete through aggregates.
| Stage | Owner | Typical code | Rule |
|---|---|---|---|
| Identity | Factory or id generator | Str::uuid7(), IDs.NextOrderID() | Before the first event |
| Creation | Factory / factory method | fromCart, reorder, Shipment::forPaidOrder | Whole and valid, or nothing |
| Change | Root methods | addLine, place, markPaid | One tx, one version bump |
| Reconstitution | Repository | reconstitute(...) | No events, no creation rules |
| End | Root method | cancel, close, archive | A status, with its own rules and events |
Fix / how to use it: ids from the factory, a constructor that cannot produce an invalid state, a reconstitute path that is separate from creation, and status transitions instead of deletes.
Aggregates and domain events Must-know
In plain words: when the root changes, it writes a short note about what happened; the repository saves the notes together with the aggregate, and others read them later.
Common misunderstanding: "Dispatch the event from inside the root, immediately." If the transaction then rolls back, subscribers have reacted to something that never happened; if the process crashes after commit but before dispatch, the event is lost.
Definition: a domain event is "Something happened that domain experts care about" (Evans). The root records events in a list during commands; the repository writes them to an outbox table in the same transaction as the aggregate; a relay publishes them; the root's event list is cleared only after commit. Evans connects events to aggregate boundaries directly: "We keep the aggregates internally consistent at all times, while making other changes asynchronously." Event naming, integration events and translation are the subject of Domain Events vs Integration Events; the relay is in Outbox.
Event recording with the outbox
1 order.place(now) root appends OrderPlaced to its pending list
2 repo.save(order): BEGIN
3 UPDATE orders ... WHERE version = 1
4 INSERT outbox(aggregate_id, aggregate_version = 2, 'sales.order.placed.v1', payload)
5 COMMIT event and state are durable together
6 order.markCommitted(2) pending list cleared only now
7 relay: SELECT ... FROM outbox WHERE published_at IS NULL -> publish -> mark publishedReal scenario: OrderPlaced starts Inventory's reservation and Billing's payment; OrderCancelled with refundDue = true starts a refund; ParcelDispatched notifies the customer and marks the order dispatched.
| Approach | Durable? | Same tx as aggregate? | Product |
|---|---|---|---|
| Root dispatches directly | No | No | Anti-pattern |
Laravel event with ShouldDispatchAfterCommit | No (in-process after commit) | Fires after commit | Laravel 13: "This interface instructs Laravel to not dispatch the event until the current database transaction is committed." |
| Outbox table + relay | Yes | Yes | Any SQL database; Debezium for CDC relays (CDC) |
| Event-sourced store (events are the state) | Yes | The append is the transaction | Marten on PostgreSQL (see Event Sourcing & CQRS) |
Fix / how to use it: pendingEvents() and markCommitted() on the root, the outbox insert inside the repository's transaction, and the aggregate version stored with each outbox row so consumers can detect gaps and order per aggregate.
Aggregates and repositories Important
In plain words: each aggregate type gets one repository that loads and saves the whole aggregate; inner parts never get their own.
Common misunderstanding: "Every table needs a repository." Evans: "Provide repositories only for aggregate roots that actually need direct access."
Definition: a repository gives "the illusion of an in-memory collection of all objects of that aggregate’s root type" (Evans). For aggregates this means: get(id) returns a fully reconstituted root (or a lazy proxy that behaves as one), save(root) persists the whole boundary plus pending events atomically and enforces the version. Interfaces, query methods, unit of work and mapping are in Repositories and Data Persistence in Design.
Repository per child entity (anti-pattern)
1 $line = $lineRepo->find(42); $line->quantity = 500; $lineRepo->save($line);
2 -> no root loaded, no invariant checked, no version bumped, Order total now wrong
One repository per aggregate
1 $order = $orders->get('o-1'); $order->addLine('mug', 2, $price); $orders->save($order);Real scenario: an OrderLineRepository added "for performance" to update one quantity; a ShipmentItemRepository used by a warehouse scanner app that bypasses the shipment's packing rules.
| Repository question | Answer for aggregates |
|---|---|
| How many per aggregate type? | One |
What does get return? | The root with everything inside the boundary |
What does save write? | Root row (with version check), inner rows, outbox rows, in one transaction |
| Who calls it? | Application services and event handlers, not the root itself (Vernon's "disconnected domain model" is a form of lazy loading he advises against) |
| Queries across many aggregates? | A read model, not the repository (CQRS) |
Fix / how to use it: delete child repositories; route every write through the root's repository; give list screens their own query service.
Factories Must-know
In plain words: a factory is the piece of code whose only job is to build a complete, valid aggregate, so callers never assemble one by hand.
Common misunderstanding: "Factory means Laravel's OrderFactory in database/factories." Eloquent model factories exist for tests and seeding; the Laravel 13 docs introduce them with "When testing your application or seeding your database, you may need to insert a few records into your database." They write rows with fake data and bypass the domain entirely. A DDD factory is production code inside the domain.
Definition: Evans: "When creation of an entire, internally consistent aggregate, or a large value object, becomes complicated or reveals too much of the internal structure, factories provide encapsulation." And: "Create an entire aggregate as a piece, enforcing its invariants." A factory may be a standalone object ("which may itself have no responsibility in the domain model but is still part of the domain design"), a factory method on another aggregate or on the root, or a named constructor for simple cases. Reconstitution (rebuilding from storage) is a different job: it must not record creation events or re-run creation-only rules. The GoF mechanics (Factory Method, Abstract Factory, Builder) are in Creational Patterns.
| Kind | Where it lives | Use when | Our example |
|---|---|---|---|
| Named constructor | Static method on the root | Creation is simple: a few checks | Order::draft($id, $customerId, $currency) |
| Standalone factory | Domain service-like object | Needs collaborators (price book, id generator), many steps | OrderFactory::fromCart() |
| Factory method on another aggregate | Method on the "previous state" | The business says X creates Y | Vernon: Product.planBacklogItem() returns a new BacklogItem |
| Factory method on the root | Method on the same type | A new instance derived from an old one | order.reorder() creates a new Order |
| Factory in another context | Message handler + constructor | Creation triggered by an event | Shipment::forPaidOrder() from OrderPaid |
| Reconstitution | Repository + reconstitute() | Loading from storage | No events, version restored |
| Eloquent model factory | database/factories | Tests and seeders only | Builds orders rows, not aggregates |
Factory method on another aggregate (Vernon, Part I)
1 product = productRepository.productOfId(tenant, productId)
2 backlogItem = product.planBacklogItem(summary, category, type, points) Product creates, is NOT modified
3 backlogItemRepository.add(backlogItem) only the new aggregate is saved
"These redesigned methods have a [CQS] query contract, and act as factories." (Vernon)Dahan's version of the same idea: "In any transition, the previous state is the aggregate root." Customers come from visitors, orders from carts, shipments from paid orders. Asking what existed just before this thing? often reveals the right factory method.
Real scenario: creating an order from a cart needs current Catalog prices, an id, a currency check and line merging: a standalone factory; a "buy again" button: a factory method on the old order; a shipment that must exist only for paid orders: a factory that takes the paid-order message; a quote that turns into an order with the quoted prices locked: a factory method on Quote.
| Constructor vs factory | Constructor | Factory |
|---|---|---|
| Collaborators (price book, clock, ids) | Awkward: passed in by every caller | Injected once |
| Many steps, each validated | Long parameter lists | Readable assembly |
| Callers depend on concrete classes | Yes | Interface can hide them (Evans: "does not require the client to reference the concrete classes") |
| Invariants on the result | Must still hold | Must still hold: the factory calls the root's methods |
| Good for | Simple roots and value objects | Complex assembly, creation from another state |
Fix / how to use it: the factory calls the root's own commands (addLine) so it cannot bypass an invariant; it returns a whole aggregate or throws; it generates identity; reconstitution is a separate static method used only by repositories; Eloquent factories stay in tests.
Mechanics
The schema of one aggregate Must-know
-- PostgreSQL. One aggregate (Order) = root table + inner table + outbox. Sales schema only.
CREATE TABLE orders (
id text PRIMARY KEY, -- UUIDv7 generated by the factory
customer_id text NOT NULL, -- reference by identity: NO foreign key to Identity
currency char(3) NOT NULL,
status text NOT NULL CHECK (status IN ('draft','placed','paid','dispatched','cancelled')),
total_minor bigint NOT NULL CHECK (total_minor >= 0),
version integer NOT NULL, -- the root's optimistic concurrency token
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz
);
CREATE TABLE order_lines (
order_id text NOT NULL REFERENCES orders(id) ON DELETE CASCADE, -- inside the boundary: FK is fine
position smallint NOT NULL,
sku text NOT NULL, -- reference to Catalog by identity
quantity smallint NOT NULL CHECK (quantity BETWEEN 1 AND 50),
unit_price_minor bigint NOT NULL,
PRIMARY KEY (order_id, position)
);
CREATE TABLE outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
aggregate_type text NOT NULL,
aggregate_id text NOT NULL,
aggregate_version integer NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;
-- Save = compare-and-set on the root, ALWAYS, even if only lines changed.
BEGIN;
UPDATE orders SET status = 'draft', total_minor = 4550, version = version + 1, updated_at = now()
WHERE id = 'o-1' AND version = 7; -- 0 rows -> ROLLBACK, raise ConcurrencyConflict
DELETE FROM order_lines WHERE order_id = 'o-1';
INSERT INTO order_lines VALUES ('o-1', 0, 'mug', 3, 1250), ('o-1', 1, 'tea', 1, 800);
COMMIT;
-- Pessimistic alternative for a hot aggregate: lock the ROOT row first, then work.
BEGIN;
SELECT version FROM orders WHERE id = 'o-1' FOR UPDATE; -- second writer waits here
-- ... load lines, run the command in the application, write rows ...
COMMIT;The database CHECK constraints are a safety net, not the model: the root rejects bad input with a domain error long before PostgreSQL would. Note what is not there: no customers foreign key, no products foreign key, no shipments table in this schema.
The save algorithm
repository.save(order)
1 snapshot = order.snapshot() state + version read at load time
2 BEGIN
3 if version == 0: INSERT root (version 1) duplicate id -> SQLSTATE 23505
4 else: UPDATE root ... WHERE id AND version 0 rows -> ROLLBACK -> ConcurrencyConflict
5 replace inner rows (or diff them) only rows of THIS aggregate
6 INSERT outbox rows for pending events same transaction
7 COMMIT serialization failure -> 40001; deadlock -> 40P01
8 order.markCommitted(version + 1) clear events only after a successful commitReplacing inner rows (delete + insert) is the simplest correct mapping for small aggregates. Larger ones diff the collection (insert new, update changed, delete removed); ORMs with a unit of work (Hibernate, Doctrine) do this through dirty checking, which Dahan calls "persistence by reachability" when new children are saved because the root's collection changed.
Errors you will see
| Where | Signal | Meaning | Retry? |
|---|---|---|---|
| Our repository (any SQL database) | UPDATE ... WHERE version = ? affects 0 rows | Concurrent modification of this aggregate | Yes: reload and re-run the command |
| PostgreSQL | SQLSTATE 40001 serialization_failure | REPEATABLE READ / SERIALIZABLE conflict (Isolation Levels) | Yes, whole transaction |
| PostgreSQL | SQLSTATE 40P01 deadlock_detected | Two transactions locking in different orders (Deadlocks) | Yes |
| PostgreSQL | SQLSTATE 23505 unique_violation | Same aggregate id inserted twice (or inbox dedup) | No; treat as "already exists" |
| MySQL / InnoDB | Error 1213 (deadlock), 1205 (lock wait timeout), 1062 (duplicate entry) | Same three cases in MySQL's numbering | 1213 yes, 1205 maybe, 1062 no |
| Laravel | DB::transaction(..., attempts: 5) | "the number of times a transaction should be retried when a deadlock occurs" (Laravel 13 docs): deadlocks only | Our ConcurrencyConflict needs our own loop |
| Laravel | Illuminate\Database\LazyLoadingViolationException | A relation was lazily loaded after preventLazyLoading() | No: fix the code |
| DynamoDB | "The conditional request failed" | Condition expression (for example the version) was false | Yes, reload |
| Our domain | OrderRuleViolated, ErrTooManyLines, ErrBadTransition | A business rule refused the command | Never |
Per-product behaviour
| Store | Natural aggregate unit | Atomicity | Concurrency token | Note |
|---|---|---|---|---|
| PostgreSQL | Root row + child rows | Any number of rows in one transaction | version column, or xmin system column | Aggregate boundary is a design choice, not enforced by the engine |
| MySQL / InnoDB | Same as PostgreSQL | Transactional | version column | Default REPEATABLE READ does not raise serialization errors; rely on the version check |
| MongoDB | One document per aggregate | "In MongoDB, write operations are atomic on the single-document level, even if modifying multiple values." | Version field in the filter of updateOne | Multi-document transactions exist but signal a boundary smell |
| DynamoDB | One item, or one partition key with several items | Single-item writes; TransactWriteItems for several | Condition expression on a version attribute | Partition key = aggregate id spreads load |
| Event store (Marten on PostgreSQL) | One stream per aggregate | Append to one stream | Expected version on append: Append(streamId, expectedVersion, events) | Snapshots bound replay cost (Event Sourcing) |
| Redis | One hash or JSON key per aggregate | MULTI/EXEC with WATCH | WATCH on the key | Use only if Redis is the system of record (Redis) |
Go
The running example in Go: the Sales Order aggregate with a standalone factory, a factory method, reconstitution and event recording; a repository contract; an in-memory and a PostgreSQL repository with optimistic locking and the outbox; an application service with a retry loop; and Fulfilment's Shipment. The module is docs/snippets/ddd/aggregates-factories/go; gofmt -l ., go vet ./... and go test ./... pass (stdlib only).
The aggregate root
Unexported line, read-only LineView copies, rules checked before any mutation, a derived total, and a state machine:
// Package sales is the Sales bounded context. Order is its aggregate root:
// lines and totals live inside the boundary; Customer, Product and Shipment
// live in other aggregates and are referenced by identity only.
package sales
import (
"errors"
"fmt"
"time"
)
type (
// OrderID is the global identity of the Order aggregate.
OrderID string
// CustomerID references the Customer aggregate (Identity context) by id.
CustomerID string
// SKU references a Catalog product by id, never by object.
SKU string
)
// Status is the Order state machine.
type Status string
const (
Draft Status = "draft"
Placed Status = "placed"
Paid Status = "paid"
Dispatched Status = "dispatched"
Cancelled Status = "cancelled"
)
// Invariants owned by the root. They hold after every command, in one transaction.
const (
MaxLines = 20
MaxQuantityPerLine = 50
)
// Domain errors are part of the model, phrased in the ubiquitous language.
var (
ErrNotEditable = errors.New("only a draft order can be edited")
ErrTooManyLines = fmt.Errorf("an order holds at most %d lines", MaxLines)
ErrBadQuantity = fmt.Errorf("quantity must be between 1 and %d", MaxQuantityPerLine)
ErrCurrencyMismatch = errors.New("all lines must use the order currency")
ErrEmptyOrder = errors.New("an order needs at least one line")
ErrNoSuchLine = errors.New("the order has no line for this SKU")
ErrBadTransition = errors.New("this status change is not allowed")
ErrAlreadyDispatched = errors.New("the order is already dispatched; request a return instead")
)
// Money is a value object: amount in minor units plus ISO 4217 currency.
type Money struct {
Minor int64
Currency string
}
// Add returns a new Money; both operands must share the currency.
func (m Money) Add(o Money) Money { return Money{Minor: m.Minor + o.Minor, Currency: m.Currency} }
// Times returns a new Money multiplied by n.
func (m Money) Times(n int) Money { return Money{Minor: m.Minor * int64(n), Currency: m.Currency} }
// line is an internal entity of the aggregate. It is unexported: outside code
// cannot hold a reference to it, so it cannot change a line behind the root's back.
type line struct {
sku SKU
quantity int
unitPrice Money
}
// LineView is a read-only copy handed to callers.
type LineView struct {
SKU SKU
Quantity int
UnitPrice Money
}
// Order is the aggregate root and the only entry point into the boundary.
type Order struct {
id OrderID
customer CustomerID
currency string
status Status
lines []line
version int // optimistic concurrency token, owned by the root
events []Event
}
// AddLine adds or merges a line. All rules are checked before any state changes.
func (o *Order) AddLine(sku SKU, qty int, unitPrice Money) error {
if o.status != Draft {
return ErrNotEditable
}
if unitPrice.Currency != o.currency {
return ErrCurrencyMismatch
}
for i := range o.lines {
if o.lines[i].sku == sku {
merged := o.lines[i].quantity + qty
if qty < 1 || merged > MaxQuantityPerLine {
return ErrBadQuantity
}
o.lines[i].quantity = merged
return nil
}
}
if qty < 1 || qty > MaxQuantityPerLine {
return ErrBadQuantity
}
if len(o.lines) >= MaxLines {
return ErrTooManyLines
}
o.lines = append(o.lines, line{sku: sku, quantity: qty, unitPrice: unitPrice})
return nil
}
// RemoveLine deletes the line for sku while the order is a draft.
func (o *Order) RemoveLine(sku SKU) error {
if o.status != Draft {
return ErrNotEditable
}
for i := range o.lines {
if o.lines[i].sku == sku {
o.lines = append(o.lines[:i], o.lines[i+1:]...)
return nil
}
}
return ErrNoSuchLine
}
// Place turns the draft into a commitment and records OrderPlaced.
// Stock reservation is NOT done here: Inventory reacts to the event (saga).
func (o *Order) Place(now time.Time) error {
if o.status != Draft {
return ErrBadTransition
}
if len(o.lines) == 0 {
return ErrEmptyOrder
}
o.status = Placed
o.record(OrderPlaced{OrderID: o.id, CustomerID: o.customer, Total: o.Total(), Lines: o.Lines(), At: now})
return nil
}
// MarkPaid is called when Billing reports the payment captured.
func (o *Order) MarkPaid(paymentRef string, now time.Time) error {
if o.status != Placed {
return ErrBadTransition
}
o.status = Paid
o.record(OrderPaid{OrderID: o.id, PaymentRef: paymentRef, Total: o.Total(), At: now})
return nil
}
// MarkDispatched is called when Fulfilment reports ParcelDispatched.
// The rule "an order cannot be dispatched unpaid" is enforced across aggregates by the
// event flow (Fulfilment only creates shipments for OrderPaid); this check is
// the root's own defence of its state machine.
func (o *Order) MarkDispatched(now time.Time) error {
if o.status != Paid {
return ErrBadTransition
}
o.status = Dispatched
return nil
}
// Cancel withdraws the order until it is dispatched.
func (o *Order) Cancel(reason string, now time.Time) error {
switch o.status {
case Dispatched:
return ErrAlreadyDispatched
case Cancelled:
return ErrBadTransition
}
wasPaid := o.status == Paid
o.status = Cancelled
o.record(OrderCancelled{OrderID: o.id, Reason: reason, RefundDue: wasPaid, At: now})
return nil
}
// Total is derived from the lines, so it can never disagree with them.
func (o *Order) Total() Money {
t := Money{Currency: o.currency}
for _, l := range o.lines {
t = t.Add(l.unitPrice.Times(l.quantity))
}
return t
}
// Lines returns a copy; callers cannot mutate the internal slice.
func (o *Order) Lines() []LineView {
out := make([]LineView, len(o.lines))
for i, l := range o.lines {
out[i] = LineView{SKU: l.sku, Quantity: l.quantity, UnitPrice: l.unitPrice}
}
return out
}
// ID returns the identity.
func (o *Order) ID() OrderID { return o.id }
// Customer returns the referenced customer id.
func (o *Order) Customer() CustomerID { return o.customer }
// Status returns the current state.
func (o *Order) Status() Status { return o.status }
// Version returns the optimistic concurrency token loaded from storage.
func (o *Order) Version() int { return o.version }
func (o *Order) record(e Event) { o.events = append(o.events, e) }Events recorded by the root
package sales
import "time"
// Event is a domain event recorded by the root. Events carry identities and
// values, never pointers to other aggregates. EventName is the class name in
// the ubiquitous language (OrderPlaced); the dotted, versioned integration
// type (sales.order.placed.v1) is assigned at the outbox, not here.
type Event interface{ EventName() string }
// OrderPlaced: the customer committed to buy. Inventory starts the
// stock-reservation saga from it; Billing starts collecting payment.
type OrderPlaced struct {
OrderID OrderID
CustomerID CustomerID
Total Money
Lines []LineView
At time.Time
}
// EventName implements Event.
func (OrderPlaced) EventName() string { return "OrderPlaced" }
// OrderPaid: payment captured. Fulfilment creates a Shipment from it.
type OrderPaid struct {
OrderID OrderID
PaymentRef string
Total Money
At time.Time
}
// EventName implements Event.
func (OrderPaid) EventName() string { return "OrderPaid" }
// OrderCancelled: the commitment was withdrawn; RefundDue tells Billing.
type OrderCancelled struct {
OrderID OrderID
Reason string
RefundDue bool
At time.Time
}
// EventName implements Event.
func (OrderCancelled) EventName() string { return "OrderCancelled" }
// PendingEvents returns a copy of the events recorded since the last commit.
// The repository writes them to the outbox in the same transaction as the root.
func (o *Order) PendingEvents() []Event { return append([]Event(nil), o.events...) }
// MarkCommitted is called by the repository only after COMMIT succeeded:
// it clears the events and adopts the new version.
func (o *Order) MarkCommitted(newVersion int) {
o.events = nil
o.version = newVersion
}Factory, factory method and reconstitution
OrderFactory.FromCart assembles a whole draft from a cart and Catalog prices; Reorder is a factory method on the root; Reconstitute rebuilds from storage without events:
package sales
import (
"errors"
"fmt"
)
// ErrUnknownSKU means the price book has no price for a cart item.
var ErrUnknownSKU = errors.New("the catalog has no price for this SKU")
// PriceBook is what the factory needs from Catalog: a price snapshot per SKU.
// It is an interface owned by Sales (the consumer), implemented by an adapter.
type PriceBook interface {
PriceOf(sku SKU, currency string) (Money, bool)
}
// IDs generates order identities before persistence (UUIDv7, ULID, ...).
type IDs interface{ NextOrderID() OrderID }
// CartItem is the input shape: what the shopper picked.
type CartItem struct {
SKU SKU
Quantity int
}
// OrderFactory is a standalone factory. It owns the complex assembly
// (identity, price snapshot, line merging) and returns an Order whose
// invariants already hold, or an error. Clients never see a half-built Order.
type OrderFactory struct {
IDs IDs
Prices PriceBook
}
// NewDraft creates an empty draft. Simple creation needs no factory object;
// this function is the "constructor" for the trivial case.
func NewDraft(id OrderID, customer CustomerID, currency string) (*Order, error) {
if id == "" || customer == "" {
return nil, errors.New("an order needs an id and a customer")
}
if len(currency) != 3 {
return nil, errors.New("currency must be an ISO 4217 code")
}
return &Order{id: id, customer: customer, currency: currency, status: Draft}, nil
}
// FromCart builds a whole draft as one piece. Every line goes through
// AddLine, so the factory cannot bypass the root's invariants.
func (f OrderFactory) FromCart(customer CustomerID, currency string, items []CartItem) (*Order, error) {
if len(items) == 0 {
return nil, ErrEmptyOrder
}
o, err := NewDraft(f.IDs.NextOrderID(), customer, currency)
if err != nil {
return nil, err
}
for _, it := range items {
price, ok := f.Prices.PriceOf(it.SKU, currency)
if !ok {
return nil, fmt.Errorf("%w: %s", ErrUnknownSKU, it.SKU)
}
if err := o.AddLine(it.SKU, it.Quantity, price); err != nil {
return nil, fmt.Errorf("sku %s: %w", it.SKU, err)
}
}
return o, nil
}
// Reorder is a factory method on the root: an existing Order creates a NEW
// Order aggregate (new identity, same lines, current prices). The old order is
// not modified, so only the new aggregate is saved in this transaction.
func (o *Order) Reorder(newID OrderID, prices PriceBook) (*Order, error) {
n, err := NewDraft(newID, o.customer, o.currency)
if err != nil {
return nil, err
}
for _, l := range o.lines {
p, ok := prices.PriceOf(l.sku, o.currency)
if !ok {
continue // discontinued products are dropped from a reorder
}
if err := n.AddLine(l.sku, l.quantity, p); err != nil {
return nil, err
}
}
if len(n.lines) == 0 {
return nil, ErrEmptyOrder
}
return n, nil
}
// Snapshot is the persistence shape of the aggregate, used only by repositories.
type Snapshot struct {
ID OrderID
Customer CustomerID
Currency string
Status Status
Lines []LineView
Version int
}
// Snapshot exports the state for a repository.
func (o *Order) Snapshot() Snapshot {
return Snapshot{ID: o.id, Customer: o.customer, Currency: o.currency, Status: o.status, Lines: o.Lines(), Version: o.version}
}
// Reconstitute rebuilds an Order from storage. It is a different job from
// creation: no events are recorded and creation-only rules (price lookup,
// "must start as draft") are not re-run. The stored data is trusted because
// only this aggregate ever wrote it.
func Reconstitute(s Snapshot) *Order {
o := &Order{id: s.ID, customer: s.Customer, currency: s.Currency, status: s.Status, version: s.Version}
for _, l := range s.Lines {
o.lines = append(o.lines, line{sku: l.SKU, quantity: l.Quantity, unitPrice: l.UnitPrice})
}
return o
}One repository per aggregate
package sales
import (
"context"
"errors"
)
// ErrConcurrencyConflict means another transaction saved this aggregate after
// we loaded it (the version column moved). Reload and re-run the command.
var ErrConcurrencyConflict = errors.New("order was modified concurrently")
// ErrNotFound means no aggregate has this identity.
var ErrNotFound = errors.New("order not found")
// OrderRepository is the one repository for the Order aggregate. There is no
// LineRepository: lines are reached only through the root.
type OrderRepository interface {
Get(ctx context.Context, id OrderID) (*Order, error)
// Save persists the whole aggregate and its pending events atomically,
// failing with ErrConcurrencyConflict if the stored version moved.
Save(ctx context.Context, o *Order) error
}PostgreSQL repository: version on the root, lines as a unit, outbox in the same transaction
Written against database/sql (use the pgx stdlib driver or lib/pq). With pgx directly, pgx.BeginFunc gives the same shape: "BeginFunc calls Begin on db and then calls fn. If fn does not return an error then it calls [Tx.Commit] on db." With sqlc, "the WithTx method allows a Queries instance to be associated with a transaction", so generated queries run inside the same Save transaction.
// Package postgres implements sales.OrderRepository with database/sql
// (driver: pgx stdlib or lib/pq). One Save = one transaction = one aggregate.
package postgres
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"academy/aggregates-factories/sales"
)
// OrderRepository maps the Order aggregate to orders, order_lines and outbox.
type OrderRepository struct{ DB *sql.DB }
// integrationTypes maps a domain event's class name to the dotted, versioned
// type of the published language. Only the outbox row carries the wire name.
var integrationTypes = map[string]string{
"OrderPlaced": "sales.order.placed.v1",
"OrderPaid": "sales.order.paid.v1",
"OrderCancelled": "sales.order.cancelled.v1",
}
// Get loads the root and its lines in one transaction snapshot. It loads
// exactly the boundary: no customer, no product, no shipment.
func (r OrderRepository) Get(ctx context.Context, id sales.OrderID) (*sales.Order, error) {
tx, err := r.DB.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
return nil, err
}
defer tx.Rollback()
s := sales.Snapshot{ID: id}
err = tx.QueryRowContext(ctx,
`SELECT customer_id, currency, status, version FROM orders WHERE id = $1`, id).
Scan(&s.Customer, &s.Currency, &s.Status, &s.Version)
if errors.Is(err, sql.ErrNoRows) {
return nil, sales.ErrNotFound
}
if err != nil {
return nil, err
}
rows, err := tx.QueryContext(ctx,
`SELECT sku, quantity, unit_price_minor FROM order_lines WHERE order_id = $1 ORDER BY position`, id)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
l := sales.LineView{UnitPrice: sales.Money{Currency: s.Currency}}
if err := rows.Scan(&l.SKU, &l.Quantity, &l.UnitPrice.Minor); err != nil {
return nil, err
}
s.Lines = append(s.Lines, l)
}
if err := rows.Err(); err != nil {
return nil, err
}
return sales.Reconstitute(s), tx.Commit()
}
// Save writes the whole aggregate. The root row is ALWAYS updated with a
// version check, even when only a line changed: that is what serialises two
// concurrent AddLine calls and protects the MaxLines invariant.
func (r OrderRepository) Save(ctx context.Context, o *sales.Order) error {
s := o.Snapshot()
tx, err := r.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
newVersion := s.Version + 1
if s.Version == 0 {
_, err = tx.ExecContext(ctx,
`INSERT INTO orders (id, customer_id, currency, status, total_minor, version)
VALUES ($1, $2, $3, $4, $5, 1)`,
s.ID, s.Customer, s.Currency, s.Status, o.Total().Minor)
if err != nil {
return err // a duplicate id surfaces as SQLSTATE 23505
}
} else {
res, err := tx.ExecContext(ctx,
`UPDATE orders SET status = $2, total_minor = $3, version = version + 1, updated_at = now()
WHERE id = $1 AND version = $4`,
s.ID, s.Status, o.Total().Minor, s.Version)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return sales.ErrConcurrencyConflict
}
}
// Lines are part of the boundary: replace them as a unit.
if _, err := tx.ExecContext(ctx, `DELETE FROM order_lines WHERE order_id = $1`, s.ID); err != nil {
return err
}
for i, l := range s.Lines {
if _, err := tx.ExecContext(ctx,
`INSERT INTO order_lines (order_id, position, sku, quantity, unit_price_minor)
VALUES ($1, $2, $3, $4, $5)`,
s.ID, i, l.SKU, l.Quantity, l.UnitPrice.Minor); err != nil {
return err
}
}
// Domain events go to the outbox in the SAME transaction (see the Outbox chapter).
for _, e := range o.PendingEvents() {
eventType, ok := integrationTypes[e.EventName()]
if !ok {
return fmt.Errorf("no integration type for %s", e.EventName())
}
payload, err := json.Marshal(e)
if err != nil {
return fmt.Errorf("encode %s: %w", e.EventName(), err)
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO outbox (aggregate_type, aggregate_id, aggregate_version, event_type, payload)
VALUES ('order', $1, $2, $3, $4)`,
s.ID, newVersion, eventType, payload); err != nil {
return err
}
}
if err := tx.Commit(); err != nil {
return err
}
o.MarkCommitted(newVersion) // clear events only after a successful commit
return nil
}In-memory repository with the same contract
// Package memory is an in-memory OrderRepository with the same optimistic
// concurrency contract as the PostgreSQL one. Tests and the lab use it.
package memory
import (
"context"
"sync"
"academy/aggregates-factories/sales"
)
// Repository stores snapshots (never live pointers), so two loads give two
// independent copies, exactly like two database reads.
type Repository struct {
mu sync.Mutex
rows map[sales.OrderID]sales.Snapshot
Outbox []sales.Event
}
// New returns an empty repository.
func New() *Repository { return &Repository{rows: map[sales.OrderID]sales.Snapshot{}} }
// Get reconstitutes a fresh copy of the aggregate.
func (r *Repository) Get(_ context.Context, id sales.OrderID) (*sales.Order, error) {
r.mu.Lock()
defer r.mu.Unlock()
s, ok := r.rows[id]
if !ok {
return nil, sales.ErrNotFound
}
return sales.Reconstitute(s), nil
}
// Save is a compare-and-set on the version: the equivalent of
// UPDATE orders SET ..., version = version + 1 WHERE id = $1 AND version = $2.
func (r *Repository) Save(_ context.Context, o *sales.Order) error {
r.mu.Lock()
defer r.mu.Unlock()
current, exists := r.rows[o.ID()]
switch {
case !exists && o.Version() != 0:
return sales.ErrNotFound
case exists && current.Version != o.Version():
return sales.ErrConcurrencyConflict
}
next := o.Snapshot()
next.Version = o.Version() + 1
r.rows[o.ID()] = next
r.Outbox = append(r.Outbox, o.PendingEvents()...) // same "transaction"
o.MarkCommitted(next.Version)
return nil
}Application service: one aggregate per transaction, retry on conflict
// Package app holds application services: load one aggregate, call one
// command, save it. No business rule lives here.
package app
import (
"context"
"errors"
"time"
"academy/aggregates-factories/sales"
)
// MaxAttempts bounds the optimistic-concurrency retry loop.
const MaxAttempts = 3
// Retry re-runs fn while it fails with a concurrency conflict. fn must load
// the aggregate itself, so every attempt works on fresh state; re-saving the
// stale object would only conflict again (or worse, overwrite).
func Retry(ctx context.Context, fn func(ctx context.Context) error) error {
var err error
for attempt := 1; attempt <= MaxAttempts; attempt++ {
err = fn(ctx)
if !errors.Is(err, sales.ErrConcurrencyConflict) {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Duration(attempt*attempt) * 5 * time.Millisecond):
}
}
return err
}
// Orders is the Sales application service.
type Orders struct {
Repo sales.OrderRepository
Factory sales.OrderFactory
Now func() time.Time
}
// AddLine: one command, one aggregate instance, one transaction.
func (s Orders) AddLine(ctx context.Context, id sales.OrderID, sku sales.SKU, qty int, price sales.Money) error {
return Retry(ctx, func(ctx context.Context) error {
o, err := s.Repo.Get(ctx, id)
if err != nil {
return err
}
if err := o.AddLine(sku, qty, price); err != nil {
return err // a rule violation is final: never retried
}
return s.Repo.Save(ctx, o)
})
}
// Checkout creates the Order through the factory and places it.
func (s Orders) Checkout(ctx context.Context, customer sales.CustomerID, currency string, items []sales.CartItem) (sales.OrderID, error) {
o, err := s.Factory.FromCart(customer, currency, items)
if err != nil {
return "", err
}
if err := o.Place(s.Now()); err != nil {
return "", err
}
return o.ID(), s.Repo.Save(ctx, o)
}
// MarkPaid handles Billing's PaymentCaptured message (eventual consistency
// between Billing and Sales). Redelivery is harmless: an order that is
// already paid is left alone.
func (s Orders) MarkPaid(ctx context.Context, id sales.OrderID, paymentRef string) error {
return Retry(ctx, func(ctx context.Context) error {
o, err := s.Repo.Get(ctx, id)
if err != nil {
return err
}
if o.Status() == sales.Paid {
return nil // idempotent
}
if err := o.MarkPaid(paymentRef, s.Now()); err != nil {
return err
}
return s.Repo.Save(ctx, o)
})
}Fulfilment's Shipment: created only from a paid order
// Package fulfilment is the Fulfilment bounded context. Shipment is its own
// aggregate; it knows the order only as an identity copied from an event.
package fulfilment
import (
"errors"
"time"
)
type (
// ShipmentID is the identity of the Shipment aggregate.
ShipmentID string
// OrderRef is Fulfilment's reference to a Sales order: an id, not an object.
OrderRef string
)
// ShipmentStatus is the Shipment state machine.
type ShipmentStatus string
const (
AwaitingPick ShipmentStatus = "awaiting_pick"
Packed ShipmentStatus = "packed"
Dispatched ShipmentStatus = "dispatched"
)
var (
ErrNotPaid = errors.New("a shipment can only be created for a paid order")
ErrNothingToShip = errors.New("a shipment needs at least one parcel line")
ErrNotPacked = errors.New("only a packed shipment can be dispatched")
)
// OrderPaidMessage is Fulfilment's own translation of sales.order.paid.v1
// (an anticorruption layer keeps the Sales model out of this package).
type OrderPaidMessage struct {
OrderID string
Paid bool
Lines []PickLine
Postcode string
}
// PickLine is a value object: what to pick, how many.
type PickLine struct {
SKU string
Quantity int
}
// Shipment is the aggregate root.
type Shipment struct {
id ShipmentID
order OrderRef
lines []PickLine
status ShipmentStatus
trackingNo string
events []any
}
// ParcelDispatched tells Sales (and the customer) that the parcel left.
type ParcelDispatched struct {
ShipmentID ShipmentID
OrderRef OrderRef
TrackingNo string
At time.Time
}
// NewShipmentForPaidOrder is the factory. The cross-aggregate rule "an order
// cannot be dispatched unpaid" is enforced here by construction: the only way to get a
// Shipment is from a paid-order message.
func NewShipmentForPaidOrder(id ShipmentID, msg OrderPaidMessage) (*Shipment, error) {
if !msg.Paid {
return nil, ErrNotPaid
}
if len(msg.Lines) == 0 {
return nil, ErrNothingToShip
}
return &Shipment{
id: id, order: OrderRef(msg.OrderID),
lines: append([]PickLine(nil), msg.Lines...), status: AwaitingPick,
}, nil
}
// MarkPacked records that the warehouse packed every line.
func (s *Shipment) MarkPacked() { s.status = Packed }
// Dispatch hands the parcel to a carrier and records the event.
func (s *Shipment) Dispatch(trackingNo string, now time.Time) error {
if s.status != Packed {
return ErrNotPacked
}
s.status, s.trackingNo = Dispatched, trackingNo
s.events = append(s.events, ParcelDispatched{ShipmentID: s.id, OrderRef: s.order, TrackingNo: trackingNo, At: now})
return nil
}
// Status returns the state.
func (s *Shipment) Status() ShipmentStatus { return s.status }
// Order returns the referenced order id.
func (s *Shipment) Order() OrderRef { return s.order }
// PendingEvents returns a copy of recorded events.
func (s *Shipment) PendingEvents() []any { return append([]any(nil), s.events...) }Tests
Invariants, copies, state machine, events, factory, factory method and reconstitution:
package sales_test
import (
"errors"
"fmt"
"testing"
"time"
"academy/aggregates-factories/sales"
)
var now = time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
func eur(minor int64) sales.Money { return sales.Money{Minor: minor, Currency: "EUR"} }
type seqIDs struct{ n int }
func (s *seqIDs) NextOrderID() sales.OrderID { s.n++; return sales.OrderID(fmt.Sprintf("o-%d", s.n)) }
type prices map[sales.SKU]int64
func (p prices) PriceOf(sku sales.SKU, cur string) (sales.Money, bool) {
v, ok := p[sku]
return sales.Money{Minor: v, Currency: cur}, ok
}
func draft(t *testing.T) *sales.Order {
t.Helper()
o, err := sales.NewDraft("o-1", "c-1", "EUR")
if err != nil {
t.Fatal(err)
}
return o
}
func TestTotalIsDerivedFromLines(t *testing.T) {
o := draft(t)
_ = o.AddLine("mug", 2, eur(1250))
_ = o.AddLine("mug", 1, eur(1250)) // merged, not a second line
_ = o.AddLine("tea", 1, eur(800))
if got := o.Total().Minor; got != 4550 {
t.Fatalf("total = %d, want 4550", got)
}
if n := len(o.Lines()); n != 2 {
t.Fatalf("lines = %d, want 2", n)
}
}
func TestInvariantsRejectBeforeChangingState(t *testing.T) {
o := draft(t)
for i := 0; i < sales.MaxLines; i++ {
if err := o.AddLine(sales.SKU(fmt.Sprint("sku-", i)), 1, eur(100)); err != nil {
t.Fatal(err)
}
}
cases := []struct {
name string
err error
run func() error
}{
{"21st line", sales.ErrTooManyLines, func() error { return o.AddLine("extra", 1, eur(100)) }},
{"zero quantity", sales.ErrBadQuantity, func() error { return o.AddLine("sku-0", 0, eur(100)) }},
{"over max per line", sales.ErrBadQuantity, func() error { return o.AddLine("sku-0", sales.MaxQuantityPerLine, eur(100)) }},
{"other currency", sales.ErrCurrencyMismatch, func() error { return o.AddLine("x", 1, sales.Money{Minor: 1, Currency: "USD"}) }},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if err := c.run(); !errors.Is(err, c.err) {
t.Fatalf("err = %v, want %v", err, c.err)
}
if n := len(o.Lines()); n != sales.MaxLines {
t.Fatalf("state changed: %d lines", n)
}
})
}
}
func TestLinesReturnsACopy(t *testing.T) {
o := draft(t)
_ = o.AddLine("mug", 1, eur(1250))
o.Lines()[0].Quantity = 999 // mutating the copy...
if o.Lines()[0].Quantity != 1 { // ...does not reach inside the boundary
t.Fatal("internal line was modified from outside the root")
}
}
func TestStateMachineAndEvents(t *testing.T) {
o := draft(t)
if err := o.Place(now); !errors.Is(err, sales.ErrEmptyOrder) {
t.Fatalf("empty place: %v", err)
}
_ = o.AddLine("mug", 1, eur(1250))
if err := o.MarkPaid("pay-1", now); !errors.Is(err, sales.ErrBadTransition) {
t.Fatalf("pay a draft: %v", err)
}
if err := o.Place(now); err != nil {
t.Fatal(err)
}
if err := o.AddLine("tea", 1, eur(800)); !errors.Is(err, sales.ErrNotEditable) {
t.Fatalf("edit after place: %v", err)
}
if err := o.MarkDispatched(now); !errors.Is(err, sales.ErrBadTransition) {
t.Fatalf("dispatch unpaid: %v", err)
}
_ = o.MarkPaid("pay-1", now)
_ = o.MarkDispatched(now)
if err := o.Cancel("changed mind", now); !errors.Is(err, sales.ErrAlreadyDispatched) {
t.Fatalf("cancel dispatched: %v", err)
}
ev := o.PendingEvents()
if len(ev) != 2 || ev[0].EventName() != "OrderPlaced" || ev[1].EventName() != "OrderPaid" {
t.Fatalf("events = %v", ev)
}
}
func TestFactoryBuildsAWholeValidAggregate(t *testing.T) {
f := sales.OrderFactory{IDs: &seqIDs{}, Prices: prices{"mug": 1250, "tea": 800}}
o, err := f.FromCart("c-1", "EUR", []sales.CartItem{{SKU: "mug", Quantity: 2}, {SKU: "tea", Quantity: 1}})
if err != nil {
t.Fatal(err)
}
if o.ID() != "o-1" || o.Status() != sales.Draft || o.Total().Minor != 3300 {
t.Fatalf("got %s %s %d", o.ID(), o.Status(), o.Total().Minor)
}
if _, err := f.FromCart("c-1", "EUR", []sales.CartItem{{SKU: "ghost", Quantity: 1}}); !errors.Is(err, sales.ErrUnknownSKU) {
t.Fatalf("unknown sku: %v", err)
}
if _, err := f.FromCart("c-1", "EUR", []sales.CartItem{{SKU: "mug", Quantity: 0}}); !errors.Is(err, sales.ErrBadQuantity) {
t.Fatalf("factory must not bypass invariants: %v", err)
}
}
func TestReorderIsAFactoryMethodOnTheRoot(t *testing.T) {
old := draft(t)
_ = old.AddLine("mug", 2, eur(1000))
_ = old.AddLine("retired", 1, eur(500))
n, err := old.Reorder("o-2", prices{"mug": 1250})
if err != nil {
t.Fatal(err)
}
if n.ID() != "o-2" || len(n.Lines()) != 1 || n.Total().Minor != 2500 {
t.Fatalf("reorder = %s, %d lines, %d", n.ID(), len(n.Lines()), n.Total().Minor)
}
if old.Total().Minor != 2500 { // the source aggregate is untouched
t.Fatal("reorder modified the old order")
}
}
func TestReconstituteRecordsNoEvents(t *testing.T) {
o := sales.Reconstitute(sales.Snapshot{ID: "o-9", Customer: "c-1", Currency: "EUR", Status: sales.Placed, Version: 7,
Lines: []sales.LineView{{SKU: "mug", Quantity: 1, UnitPrice: eur(1250)}}})
if len(o.PendingEvents()) != 0 || o.Version() != 7 || o.Status() != sales.Placed {
t.Fatalf("reconstitute: events=%d version=%d status=%s", len(o.PendingEvents()), o.Version(), o.Status())
}
}Concurrency: a stale save is rejected; the max-lines invariant survives a race; a conflict is retried on fresh state; events land in the outbox with the aggregate:
package app_test
import (
"context"
"errors"
"fmt"
"testing"
"time"
"academy/aggregates-factories/app"
"academy/aggregates-factories/memory"
"academy/aggregates-factories/sales"
)
func eur(minor int64) sales.Money { return sales.Money{Minor: minor, Currency: "EUR"} }
// seed stores a draft with n lines at version 1.
func seed(t *testing.T, repo *memory.Repository, n int) {
t.Helper()
o, _ := sales.NewDraft("o-1", "c-1", "EUR")
for i := 0; i < n; i++ {
_ = o.AddLine(sales.SKU(fmt.Sprint("sku-", i)), 1, eur(100))
}
if err := repo.Save(context.Background(), o); err != nil {
t.Fatal(err)
}
}
// Two clients load version 1; the first save wins, the second gets a conflict.
func TestStaleSaveIsRejected(t *testing.T) {
ctx := context.Background()
repo := memory.New()
seed(t, repo, 1)
a, _ := repo.Get(ctx, "o-1")
b, _ := repo.Get(ctx, "o-1")
_ = a.AddLine("tea", 1, eur(800))
_ = b.AddLine("cake", 1, eur(450))
if err := repo.Save(ctx, a); err != nil {
t.Fatal(err)
}
if err := repo.Save(ctx, b); !errors.Is(err, sales.ErrConcurrencyConflict) {
t.Fatalf("second save: %v, want conflict", err)
}
}
// The MaxLines invariant survives a race: 19 lines, two concurrent adds.
// One commits (20 lines); the other retries on fresh state and is refused.
func TestInvariantHoldsUnderConcurrency(t *testing.T) {
ctx := context.Background()
repo := memory.New()
seed(t, repo, sales.MaxLines-1)
stale, _ := repo.Get(ctx, "o-1") // client B loaded before A committed
svc := app.Orders{Repo: repo, Now: time.Now}
if err := svc.AddLine(ctx, "o-1", "tea", 1, eur(800)); err != nil { // client A
t.Fatal(err)
}
_ = stale.AddLine("cake", 1, eur(450)) // passes on B's stale copy (19 lines)
if err := repo.Save(ctx, stale); !errors.Is(err, sales.ErrConcurrencyConflict) {
t.Fatalf("stale save: %v", err)
}
// B retries the COMMAND through the service: reload, re-check, refuse.
if err := svc.AddLine(ctx, "o-1", "cake", 1, eur(450)); !errors.Is(err, sales.ErrTooManyLines) {
t.Fatalf("retry: %v, want ErrTooManyLines", err)
}
o, _ := repo.Get(ctx, "o-1")
if len(o.Lines()) != sales.MaxLines {
t.Fatalf("lines = %d", len(o.Lines()))
}
}
// conflictOnce makes the first Save fail, as if another writer slipped in.
type conflictOnce struct {
*memory.Repository
fired bool
}
func (c *conflictOnce) Save(ctx context.Context, o *sales.Order) error {
if !c.fired {
c.fired = true
return sales.ErrConcurrencyConflict
}
return c.Repository.Save(ctx, o)
}
func TestRetryReloadsAndSucceeds(t *testing.T) {
ctx := context.Background()
repo := memory.New()
seed(t, repo, 1)
svc := app.Orders{Repo: &conflictOnce{Repository: repo}, Now: time.Now}
if err := svc.AddLine(ctx, "o-1", "tea", 1, eur(800)); err != nil {
t.Fatalf("retry should succeed: %v", err)
}
o, _ := repo.Get(ctx, "o-1")
if o.Version() != 2 || len(o.Lines()) != 2 {
t.Fatalf("version=%d lines=%d", o.Version(), len(o.Lines()))
}
}
type ids struct{}
func (ids) NextOrderID() sales.OrderID { return "o-42" }
type book struct{}
func (book) PriceOf(sales.SKU, string) (sales.Money, bool) { return eur(1250), true }
func TestCheckoutWritesEventsWithTheAggregate(t *testing.T) {
ctx := context.Background()
repo := memory.New()
svc := app.Orders{Repo: repo, Factory: sales.OrderFactory{IDs: ids{}, Prices: book{}}, Now: time.Now}
id, err := svc.Checkout(ctx, "c-1", "EUR", []sales.CartItem{{SKU: "mug", Quantity: 1}})
if err != nil {
t.Fatal(err)
}
if err := svc.MarkPaid(ctx, id, "pay-1"); err != nil {
t.Fatal(err)
}
if err := svc.MarkPaid(ctx, id, "pay-1"); err != nil { // redelivered message
t.Fatalf("redelivery: %v", err)
}
if len(repo.Outbox) != 2 {
t.Fatalf("outbox = %d events, want placed + paid", len(repo.Outbox))
}
}package fulfilment_test
import (
"errors"
"testing"
"time"
"academy/aggregates-factories/fulfilment"
)
func TestShipmentOnlyFromPaidOrder(t *testing.T) {
lines := []fulfilment.PickLine{{SKU: "mug", Quantity: 2}}
if _, err := fulfilment.NewShipmentForPaidOrder("s-1", fulfilment.OrderPaidMessage{OrderID: "o-1", Lines: lines}); !errors.Is(err, fulfilment.ErrNotPaid) {
t.Fatalf("unpaid: %v", err)
}
s, err := fulfilment.NewShipmentForPaidOrder("s-1", fulfilment.OrderPaidMessage{OrderID: "o-1", Paid: true, Lines: lines})
if err != nil {
t.Fatal(err)
}
if err := s.Dispatch("TRK1", time.Now()); !errors.Is(err, fulfilment.ErrNotPacked) {
t.Fatalf("dispatch before pack: %v", err)
}
s.MarkPacked()
if err := s.Dispatch("TRK1", time.Now()); err != nil {
t.Fatal(err)
}
if s.Order() != "o-1" || len(s.PendingEvents()) != 1 {
t.Fatalf("order=%s events=%d", s.Order(), len(s.PendingEvents()))
}
}Wrong: the giant Customer aggregate
// Package wrong shows the giant-aggregate anti-pattern: one Customer root that
// "owns" everything the customer ever touched. It compiles and it works in a
// demo; under real traffic it fails in the ways listed in the comments.
package wrong
import "time"
// Customer holds orders, their lines, shipments and invoices as one object graph.
// Every field is exported, so any caller can change any part without the root.
type Customer struct {
ID string
Name string
Email string
Orders []*Order // grows forever: loading a customer loads years of history
Shipments []*Shipment
Invoices []*Invoice
Version int // one version for everything: editing an address conflicts with checkout
}
// Order is reachable and mutable from anywhere: no root guards its lines.
type Order struct {
ID string
Lines []*Line
Total int64 // stored, not derived: can disagree with Lines
Status string
Shipment *Shipment // object reference across what should be a boundary
}
// Line is a child entity that has its own repository elsewhere (anti-pattern).
type Line struct {
SKU string
Quantity int
Price int64
}
// Shipment belongs to Fulfilment but lives inside the Customer graph here.
type Shipment struct {
ID string
Dispatched bool
At time.Time
}
// Invoice belongs to Billing but lives inside the Customer graph here.
type Invoice struct {
ID string
Amount int64
Paid bool
}
// PlaceOrder modifies the customer, an order, a shipment and an invoice in one
// transaction. Two browser tabs of the same customer now conflict; the
// warehouse marking a shipment conflicts with Billing marking an invoice paid.
func (c *Customer) PlaceOrder(o *Order) {
c.Orders = append(c.Orders, o)
o.Shipment = &Shipment{ID: "s-" + o.ID}
c.Shipments = append(c.Shipments, o.Shipment)
c.Invoices = append(c.Invoices, &Invoice{ID: "i-" + o.ID, Amount: o.Total})
}The Go angle
| Go feature | Aggregate concern | Notes |
|---|---|---|
| Unexported struct fields and types | Hide internals | line cannot be referenced outside sales; only the root mutates it |
| Returning copies of slices | No aliasing into the boundary | Lines() builds a new slice; a returned internal slice would let callers change lines |
Typed ids (type OrderID string) | Reference by identity | The compiler stops you from passing a CustomerID where an OrderID is expected |
Sentinel errors + errors.Is | Rule violation vs conflict | ErrConcurrencyConflict is retried, ErrTooManyLines is not |
database/sql Tx + RowsAffected | Compare-and-set | 0 rows affected = conflict; defer tx.Rollback() is safe after commit |
pgx.BeginFunc / sqlc WithTx | Transaction per save | Same algorithm with pgx or generated code |
| Interfaces owned by the consumer | Factory collaborators | PriceBook and IDs are declared in Sales, implemented by adapters |
context.Context | Bounded retries | The retry loop stops when the request is cancelled |
Laravel
The same design in a Laravel 13 application (PHP 8.4) structured as modules under App\Modules. The aggregate is a plain PHP class, not an Eloquent model; persistence uses the query builder on the sales connection. PHP is not installed on the authoring machine; the code was reviewed, not run.
The aggregate root, its values and errors
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DateTimeImmutable;
/**
* Order is the aggregate root of Sales. It is a plain PHP object, not an
* Eloquent model: no public setters, no lazy relations, no save().
* Lines live inside the boundary; Customer, Product and Shipment are ids.
*/
final class Order
{
public const int MAX_LINES = 20;
public const int MAX_QUANTITY_PER_LINE = 50;
/** @var array<string, OrderLine> keyed by SKU */
private array $lines = [];
/** @var list<object> domain events recorded since the last commit */
private array $events = [];
private function __construct(
public readonly string $id,
public readonly string $customerId,
public readonly string $currency,
private OrderStatus $status,
private int $version,
) {}
/** Trivial creation: a named constructor is enough, no factory object needed. */
public static function draft(string $id, string $customerId, string $currency): self
{
if ($id === '' || $customerId === '') {
throw new OrderRuleViolated('An order needs an id and a customer.');
}
if (strlen($currency) !== 3) {
throw new OrderRuleViolated('Currency must be an ISO 4217 code.');
}
return new self($id, $customerId, $currency, OrderStatus::Draft, 0);
}
/**
* Reconstitution from storage: no events, no creation-only rules.
*
* @param list<OrderLine> $lines
*/
public static function reconstitute(
string $id, string $customerId, string $currency, OrderStatus $status, int $version, array $lines,
): self {
$order = new self($id, $customerId, $currency, $status, $version);
foreach ($lines as $line) {
$order->lines[$line->sku] = $line;
}
return $order;
}
public function addLine(string $sku, int $quantity, Money $unitPrice): void
{
$this->assertStatus(OrderStatus::Draft, 'Only a draft order can be edited.');
if ($unitPrice->currency !== $this->currency) {
throw new OrderRuleViolated('All lines must use the order currency.');
}
$existing = $this->lines[$sku] ?? null;
$newQuantity = ($existing?->quantity ?? 0) + $quantity;
if ($quantity < 1 || $newQuantity > self::MAX_QUANTITY_PER_LINE) {
throw new OrderRuleViolated('Quantity must be between 1 and '.self::MAX_QUANTITY_PER_LINE.'.');
}
if ($existing === null && count($this->lines) >= self::MAX_LINES) {
throw new OrderRuleViolated('An order holds at most '.self::MAX_LINES.' lines.');
}
$this->lines[$sku] = new OrderLine($sku, $newQuantity, $existing?->unitPrice ?? $unitPrice);
}
public function removeLine(string $sku): void
{
$this->assertStatus(OrderStatus::Draft, 'Only a draft order can be edited.');
if (! isset($this->lines[$sku])) {
throw new OrderRuleViolated("The order has no line for {$sku}.");
}
unset($this->lines[$sku]);
}
/** Stock is reserved by Inventory reacting to OrderPlaced (a saga), not here. */
public function place(DateTimeImmutable $now): void
{
$this->assertStatus(OrderStatus::Draft, 'Only a draft order can be placed.');
if ($this->lines === []) {
throw new OrderRuleViolated('An order needs at least one line.');
}
$this->status = OrderStatus::Placed;
$this->events[] = new OrderPlaced($this->id, $this->customerId, $this->total(), $this->lines(), $now);
}
public function markPaid(string $paymentRef, DateTimeImmutable $now): void
{
if ($this->status === OrderStatus::Paid) {
return; // redelivered PaymentCaptured message: already done
}
$this->assertStatus(OrderStatus::Placed, 'Only a placed order can be paid.');
$this->status = OrderStatus::Paid;
$this->events[] = new OrderPaid($this->id, $paymentRef, $this->total(), $now);
}
public function markDispatched(): void
{
$this->assertStatus(OrderStatus::Paid, 'An order cannot be dispatched unpaid.');
$this->status = OrderStatus::Dispatched;
}
public function cancel(string $reason, DateTimeImmutable $now): void
{
if ($this->status === OrderStatus::Dispatched) {
throw new OrderRuleViolated('The order is already dispatched; request a return instead.');
}
if ($this->status === OrderStatus::Cancelled) {
return;
}
$refundDue = $this->status === OrderStatus::Paid;
$this->status = OrderStatus::Cancelled;
$this->events[] = new OrderCancelled($this->id, $reason, $refundDue, $now);
}
/** Derived, never stored independently of the lines it sums. */
public function total(): Money
{
$total = Money::zero($this->currency);
foreach ($this->lines as $line) {
$total = $total->add($line->subtotal());
}
return $total;
}
/** @return list<OrderLine> immutable value objects, safe to hand out */
public function lines(): array
{
return array_values($this->lines);
}
public function status(): OrderStatus
{
return $this->status;
}
public function version(): int
{
return $this->version;
}
/** @return list<object> */
public function pendingEvents(): array
{
return $this->events;
}
/** Called by the repository only after COMMIT succeeded. */
public function markCommitted(int $newVersion): void
{
$this->events = [];
$this->version = $newVersion;
}
private function assertStatus(OrderStatus $expected, string $message): void
{
if ($this->status !== $expected) {
throw new OrderRuleViolated($message);
}
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
/**
* A line inside the Order boundary. It is immutable: the root replaces it
* instead of letting callers change it, so handing it out is safe.
*/
final readonly class OrderLine
{
public function __construct(
public string $sku,
public int $quantity,
public Money $unitPrice,
) {}
public function subtotal(): Money
{
return $this->unitPrice->times($this->quantity);
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
/** Value object: amount in minor units plus ISO 4217 currency. */
final readonly class Money
{
public function __construct(
public int $minor,
public string $currency,
) {}
public static function zero(string $currency): self
{
return new self(0, $currency);
}
public function add(self $other): self
{
if ($other->currency !== $this->currency) {
throw new OrderRuleViolated('Cannot add different currencies.');
}
return new self($this->minor + $other->minor, $this->currency);
}
public function times(int $n): self
{
return new self($this->minor * $n, $this->currency);
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
enum OrderStatus: string
{
case Draft = 'draft';
case Placed = 'placed';
case Paid = 'paid';
case Dispatched = 'dispatched';
case Cancelled = 'cancelled';
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DomainException;
/** A business rule refused the command. Never retried. */
final class OrderRuleViolated extends DomainException {}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use RuntimeException;
/** The stored version moved after we loaded the aggregate. Reload and retry. */
final class ConcurrencyConflict extends RuntimeException {}Events recorded by the root
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DateTimeImmutable;
final readonly class OrderPlaced
{
/** @param list<OrderLine> $lines */
public function __construct(
public string $orderId,
public string $customerId,
public Money $total,
public array $lines,
public DateTimeImmutable $at,
) {}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DateTimeImmutable;
final readonly class OrderPaid
{
public function __construct(
public string $orderId,
public string $paymentRef,
public Money $total,
public DateTimeImmutable $at,
) {}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DateTimeImmutable;
final readonly class OrderCancelled
{
public function __construct(
public string $orderId,
public string $reason,
public bool $refundDue,
public DateTimeImmutable $at,
) {}
}The DDD factory (not an Eloquent factory)
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
/** What Sales needs from Catalog; implemented by an adapter in Infrastructure. */
interface PriceBook
{
public function priceOf(string $sku, string $currency): ?Money;
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use Illuminate\Support\Str;
/**
* Standalone DDD factory: assembles a whole, valid draft from a cart.
* Every line goes through Order::addLine(), so the factory cannot bypass
* an invariant. Not to be confused with Laravel's Eloquent model factories,
* which build test rows and skip the domain entirely.
*/
final readonly class OrderFactory
{
public function __construct(private PriceBook $prices) {}
/** @param list<array{sku: string, quantity: int}> $items */
public function fromCart(string $customerId, string $currency, array $items): Order
{
if ($items === []) {
throw new OrderRuleViolated('An order needs at least one line.');
}
$order = Order::draft((string) Str::uuid7(), $customerId, $currency);
foreach ($items as $item) {
$price = $this->prices->priceOf($item['sku'], $currency)
?? throw new OrderRuleViolated("The catalog has no price for {$item['sku']}.");
$order->addLine($item['sku'], $item['quantity'], $price);
}
return $order;
}
/** Factory method flavour: a new Order built from an old one, old one untouched. */
public function reorder(Order $previous): Order
{
$order = Order::draft((string) Str::uuid7(), $previous->customerId, $previous->currency);
foreach ($previous->lines() as $line) {
$price = $this->prices->priceOf($line->sku, $previous->currency);
if ($price !== null) {
$order->addLine($line->sku, $line->quantity, $price);
}
}
if ($order->lines() === []) {
throw new OrderRuleViolated('Nothing from this order can be bought again.');
}
return $order;
}
}Repository: conditional UPDATE, lines, outbox, one transaction
Laravel's query builder documents pessimistic locking (sharedLock, lockForUpdate) but no version-column helper, so optimistic locking is a conditional update(); the docs state "The update method returns the number of affected rows." DB::transaction commits or rolls back for us: "If an exception is thrown within the transaction closure, the transaction will automatically be rolled back and the exception is re-thrown."
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
/** One repository per aggregate. There is no OrderLineRepository. */
interface OrderRepository
{
public function get(string $id): Order;
/** Persists root, lines and pending events atomically; throws ConcurrencyConflict. */
public function save(Order $order): void;
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Infrastructure;
use App\Modules\Sales\Domain\ConcurrencyConflict;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderCancelled;
use App\Modules\Sales\Domain\OrderLine;
use App\Modules\Sales\Domain\OrderPaid;
use App\Modules\Sales\Domain\OrderPlaced;
use App\Modules\Sales\Domain\OrderRepository;
use App\Modules\Sales\Domain\OrderRuleViolated;
use App\Modules\Sales\Domain\OrderStatus;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\DB;
/**
* Maps the Order aggregate to orders, order_lines and outbox with the query
* builder. Optimistic locking is a conditional UPDATE on the root's version:
* update() returns the number of affected rows, and 0 means someone else won.
*/
final readonly class DbOrderRepository implements OrderRepository
{
/** Domain event class => dotted, versioned type of the published language. */
private const array INTEGRATION_TYPES = [
OrderPlaced::class => 'sales.order.placed.v1',
OrderPaid::class => 'sales.order.paid.v1',
OrderCancelled::class => 'sales.order.cancelled.v1',
];
private ConnectionInterface $db;
public function __construct()
{
$this->db = DB::connection('sales'); // Sales' own connection and DB user
}
public function get(string $id): Order
{
$row = $this->db->table('orders')->where('id', $id)->first()
?? throw new OrderRuleViolated("Order {$id} not found.");
$lines = $this->db->table('order_lines')
->where('order_id', $id)
->orderBy('position')
->get()
->map(fn (object $l) => new OrderLine($l->sku, (int) $l->quantity, new Money((int) $l->unit_price_minor, $row->currency)))
->all();
return Order::reconstitute($row->id, $row->customer_id, $row->currency, OrderStatus::from($row->status), (int) $row->version, $lines);
}
public function save(Order $order): void
{
$newVersion = $order->version() + 1;
$this->db->transaction(function () use ($order, $newVersion): void {
if ($order->version() === 0) {
$this->db->table('orders')->insert([
'id' => $order->id,
'customer_id' => $order->customerId,
'currency' => $order->currency,
'status' => $order->status()->value,
'total_minor' => $order->total()->minor,
'version' => 1,
]);
} else {
// Always touch the root, even if only a line changed.
$affected = $this->db->table('orders')
->where('id', $order->id)
->where('version', $order->version())
->update([
'status' => $order->status()->value,
'total_minor' => $order->total()->minor,
'version' => $newVersion,
'updated_at' => now(),
]);
if ($affected === 0) {
throw new ConcurrencyConflict("Order {$order->id} changed since version {$order->version()}.");
}
}
$this->db->table('order_lines')->where('order_id', $order->id)->delete();
foreach ($order->lines() as $position => $line) {
$this->db->table('order_lines')->insert([
'order_id' => $order->id,
'position' => $position,
'sku' => $line->sku,
'quantity' => $line->quantity,
'unit_price_minor' => $line->unitPrice->minor,
]);
}
// Domain events -> outbox, same transaction (see the Outbox chapter).
foreach ($order->pendingEvents() as $event) {
$this->db->table('outbox')->insert([
'aggregate_type' => 'order',
'aggregate_id' => $order->id,
'aggregate_version' => $newVersion,
'event_type' => self::INTEGRATION_TYPES[$event::class],
'payload' => json_encode($event, JSON_THROW_ON_ERROR),
]);
}
});
$order->markCommitted($newVersion); // only after COMMIT
}
}<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
protected $connection = 'sales';
public function up(): void
{
Schema::create('orders', function (Blueprint $table) {
$table->string('id', 36)->primary(); // UUIDv7 in production
$table->string('customer_id', 36)->index(); // id reference to Identity: no foreign key
$table->char('currency', 3);
$table->string('status', 16);
$table->bigInteger('total_minor');
$table->unsignedInteger('version'); // optimistic concurrency token of the root
$table->timestamps();
});
Schema::create('order_lines', function (Blueprint $table) {
$table->string('order_id', 36);
$table->foreign('order_id')->references('id')->on('orders')->cascadeOnDelete(); // inside the boundary
$table->unsignedSmallInteger('position');
$table->string('sku', 64); // id reference to Catalog: no foreign key
$table->unsignedSmallInteger('quantity');
$table->bigInteger('unit_price_minor');
$table->primary(['order_id', 'position']);
});
Schema::create('outbox', function (Blueprint $table) {
$table->id();
$table->string('aggregate_type', 32);
$table->string('aggregate_id', 36);
$table->unsignedInteger('aggregate_version');
$table->string('event_type', 64);
$table->json('payload');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('published_at')->nullable()->index();
});
}
public function down(): void
{
Schema::dropIfExists('outbox');
Schema::dropIfExists('order_lines');
Schema::dropIfExists('orders');
}
};Application service with its own retry loop
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application;
use App\Modules\Sales\Domain\ConcurrencyConflict;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\OrderFactory;
use App\Modules\Sales\Domain\OrderRepository;
use Closure;
use DateTimeImmutable;
/**
* Application service: load one aggregate, call one command, save it.
* DB::transaction(..., attempts: n) retries deadlocks only; an optimistic
* conflict is our own exception, so the retry loop is ours too.
*/
final readonly class OrderService
{
private const int MAX_ATTEMPTS = 3;
public function __construct(
private OrderRepository $orders,
private OrderFactory $factory,
) {}
public function addLine(string $orderId, string $sku, int $quantity, Money $unitPrice): void
{
$this->retryOnConflict(function () use ($orderId, $sku, $quantity, $unitPrice): void {
$order = $this->orders->get($orderId); // fresh state every attempt
$order->addLine($sku, $quantity, $unitPrice); // OrderRuleViolated is final
$this->orders->save($order);
});
}
/** @param list<array{sku: string, quantity: int}> $items */
public function checkout(string $customerId, string $currency, array $items): string
{
$order = $this->factory->fromCart($customerId, $currency, $items);
$order->place(new DateTimeImmutable());
$this->orders->save($order);
return $order->id;
}
/** Handles Billing's PaymentCaptured message: eventual consistency between aggregates. */
public function markPaid(string $orderId, string $paymentRef): void
{
$this->retryOnConflict(function () use ($orderId, $paymentRef): void {
$order = $this->orders->get($orderId);
$order->markPaid($paymentRef, new DateTimeImmutable());
$this->orders->save($order);
});
}
private function retryOnConflict(Closure $command): void
{
for ($attempt = 1; ; $attempt++) {
try {
$command();
return;
} catch (ConcurrencyConflict $e) {
if ($attempt >= self::MAX_ATTEMPTS) {
throw $e;
}
usleep($attempt * $attempt * 5_000);
}
}
}
}Fulfilment: Shipment and the handler that creates it from OrderPaid
<?php
declare(strict_types=1);
namespace App\Modules\Fulfilment\Domain;
use DateTimeImmutable;
use DomainException;
/**
* Shipment is Fulfilment's aggregate. It knows the order only by id.
* The only way to create one is the factory below, which demands a paid
* order: "an order cannot be dispatched unpaid" holds by construction.
*/
final class Shipment
{
/** @var list<object> */
private array $events = [];
/** @param list<array{sku: string, quantity: int}> $lines */
private function __construct(
public readonly string $id,
public readonly string $orderId,
private readonly array $lines,
private string $status,
private ?string $trackingNo = null,
) {}
/** @param list<array{sku: string, quantity: int}> $lines */
public static function forPaidOrder(string $id, string $orderId, bool $paid, array $lines): self
{
if (! $paid) {
throw new DomainException('A shipment can only be created for a paid order.');
}
if ($lines === []) {
throw new DomainException('A shipment needs at least one parcel line.');
}
return new self($id, $orderId, $lines, 'awaiting_pick');
}
public function markPacked(): void
{
$this->status = 'packed';
}
public function dispatch(string $trackingNo, DateTimeImmutable $now): void
{
if ($this->status !== 'packed') {
throw new DomainException('Only a packed shipment can be dispatched.');
}
$this->status = 'dispatched';
$this->trackingNo = $trackingNo;
$this->events[] = new ParcelDispatched($this->id, $this->orderId, $trackingNo, $now);
}
public function status(): string
{
return $this->status;
}
/** @return list<object> */
public function pendingEvents(): array
{
return $this->events;
}
}<?php
declare(strict_types=1);
namespace App\Modules\Fulfilment\Domain;
use DateTimeImmutable;
final readonly class ParcelDispatched
{
public function __construct(
public string $shipmentId,
public string $orderId,
public string $trackingNo,
public DateTimeImmutable $at,
) {}
}<?php
declare(strict_types=1);
namespace App\Modules\Fulfilment\Application;
use App\Modules\Fulfilment\Domain\Shipment;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Consumes sales.order.paid.v1 (relayed from the Sales outbox). One message,
* one new Shipment aggregate, one Fulfilment transaction. The inbox row makes
* a redelivered message a no-op.
*
* @param array{event_id: string, order_id: string, lines: list<array{sku: string, quantity: int}>} $payload
*/
final class CreateShipmentWhenOrderPaid implements ShouldQueue
{
use Queueable;
public int $tries = 5;
public function __construct(public array $payload) {}
public function handle(): void
{
DB::connection('fulfilment')->transaction(function (): void {
$db = DB::connection('fulfilment');
if ($db->table('inbox')->insertOrIgnore(['event_id' => $this->payload['event_id']]) === 0) {
return; // already processed
}
$shipment = Shipment::forPaidOrder(
(string) Str::uuid7(),
$this->payload['order_id'],
paid: true, // the event type itself is the proof of payment
lines: $this->payload['lines'],
);
$db->table('shipments')->insert([
'id' => $shipment->id,
'order_id' => $shipment->orderId, // an id, never a foreign key into Sales
'status' => $shipment->status(),
'version' => 1,
]);
});
}
/** @return list<int> */
public function backoff(): array
{
return [1, 5, 30];
}
}Pest tests
<?php
declare(strict_types=1);
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderFactory;
use App\Modules\Sales\Domain\OrderPaid;
use App\Modules\Sales\Domain\OrderPlaced;
use App\Modules\Sales\Domain\OrderRuleViolated;
use App\Modules\Sales\Domain\OrderStatus;
use App\Modules\Sales\Domain\PriceBook;
function eur(int $minor): Money
{
return new Money($minor, 'EUR');
}
function priceBook(array $prices): PriceBook
{
return new class($prices) implements PriceBook
{
public function __construct(private array $prices) {}
public function priceOf(string $sku, string $currency): ?Money
{
return isset($this->prices[$sku]) ? new Money($this->prices[$sku], $currency) : null;
}
};
}
it('derives the total from its lines and merges the same SKU', function () {
$order = Order::draft('o-1', 'c-1', 'EUR');
$order->addLine('mug', 2, eur(1250));
$order->addLine('mug', 1, eur(1250));
$order->addLine('tea', 1, eur(800));
expect($order->total()->minor)->toBe(4550)
->and($order->lines())->toHaveCount(2);
});
it('refuses the 21st line and leaves state unchanged', function () {
$order = Order::draft('o-1', 'c-1', 'EUR');
foreach (range(1, Order::MAX_LINES) as $i) {
$order->addLine("sku-{$i}", 1, eur(100));
}
expect(fn () => $order->addLine('extra', 1, eur(100)))->toThrow(OrderRuleViolated::class)
->and($order->lines())->toHaveCount(Order::MAX_LINES);
});
it('walks the state machine and records events', function () {
$order = Order::draft('o-1', 'c-1', 'EUR');
$order->addLine('mug', 1, eur(1250));
expect(fn () => $order->markDispatched())->toThrow(OrderRuleViolated::class, 'An order cannot be dispatched unpaid.');
$order->place(new DateTimeImmutable());
expect(fn () => $order->addLine('tea', 1, eur(800)))->toThrow(OrderRuleViolated::class);
$order->markPaid('pay-1', new DateTimeImmutable());
$order->markPaid('pay-1', new DateTimeImmutable()); // redelivery: no second event
expect($order->status())->toBe(OrderStatus::Paid)
->and(array_map(fn (object $e) => $e::class, $order->pendingEvents()))
->toBe([OrderPlaced::class, OrderPaid::class]);
});
it('builds a whole valid order in the factory and cannot bypass invariants', function () {
$factory = new OrderFactory(priceBook(['mug' => 1250, 'tea' => 800]));
$order = $factory->fromCart('c-1', 'EUR', [['sku' => 'mug', 'quantity' => 2], ['sku' => 'tea', 'quantity' => 1]]);
expect($order->total()->minor)->toBe(3300)
->and($order->status())->toBe(OrderStatus::Draft);
expect(fn () => $factory->fromCart('c-1', 'EUR', [['sku' => 'ghost', 'quantity' => 1]]))
->toThrow(OrderRuleViolated::class);
expect(fn () => $factory->fromCart('c-1', 'EUR', [['sku' => 'mug', 'quantity' => 0]]))
->toThrow(OrderRuleViolated::class);
});
it('reconstitutes without recording events', function () {
$order = Order::reconstitute('o-9', 'c-1', 'EUR', OrderStatus::Placed, 7, []);
expect($order->pendingEvents())->toBe([])
->and($order->version())->toBe(7);
});<?php
declare(strict_types=1);
use App\Modules\Sales\Domain\ConcurrencyConflict;
use App\Modules\Sales\Domain\Money;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Infrastructure\DbOrderRepository;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
uses(RefreshDatabase::class);
it('rejects a save based on a stale version', function () {
$repo = new DbOrderRepository();
$order = Order::draft('o-1', 'c-1', 'EUR');
$order->addLine('mug', 1, new Money(1250, 'EUR'));
$repo->save($order); // version 1
$a = $repo->get('o-1');
$b = $repo->get('o-1');
$a->addLine('tea', 1, new Money(800, 'EUR'));
$b->addLine('cake', 1, new Money(450, 'EUR'));
$repo->save($a); // version 2
expect(fn () => $repo->save($b))->toThrow(ConcurrencyConflict::class);
expect(DB::connection('sales')->table('orders')->where('id', 'o-1')->value('version'))->toBe(2)
->and(DB::connection('sales')->table('order_lines')->where('order_id', 'o-1')->count())->toBe(2);
});
it('writes pending events to the outbox in the same transaction', function () {
$repo = new DbOrderRepository();
$order = Order::draft('o-2', 'c-1', 'EUR');
$order->addLine('mug', 1, new Money(1250, 'EUR'));
$order->place(new DateTimeImmutable());
$repo->save($order);
expect(DB::connection('sales')->table('outbox')->where('aggregate_id', 'o-2')->pluck('event_type')->all())
->toBe(['sales.order.placed.v1'])
->and($order->pendingEvents())->toBe([]);
});Wrong: the aggregate as an Eloquent graph
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Anti-pattern: "the aggregate is the table". Customer is treated as the root
* of orders, lines, shipments and invoices. Public attributes and relations
* let any controller change any part; nothing guards an invariant.
*/
final class Customer extends Model
{
protected $guarded = []; // every column writable from any request
public function orders(): HasMany
{
return $this->hasMany(Order::class); // lazy-loaded graph across three contexts
}
}
// Typical controller code this design invites:
//
// $customer = Customer::find($id);
// $order = $customer->orders->last(); // lazy loads every order the customer ever made
// $order->lines[0]->quantity = 500; // bypasses "max 50 per line"
// $order->total = 0; // stored total now disagrees with lines
// $order->shipment->status = 'dispatched'; // ships an unpaid order
// $customer->push(); // saves the whole graph: one transaction, four contexts
//
// Order::where('status', 'placed')->update(['status' => 'paid']);
// Mass update: Laravel does not fire saving/updating model events here, so any
// "invariant" placed in an observer is skipped as well.An Eloquent factory is still useful, for tests that need rows quickly. Keep it clearly labelled as test data, and remember it skips every rule in Order:
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Persistence;
use Database\Factories\OrderRecordFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence-only Eloquent model for the orders table. It exists for tests,
* seeders and reporting queries; it is NOT the Order aggregate and has no rules.
*/
final class OrderRecord extends Model
{
/** @use HasFactory<OrderRecordFactory> */
use HasFactory;
protected $connection = 'sales';
protected $table = 'orders';
protected $keyType = 'string';
public $incrementing = false;
protected static function newFactory(): OrderRecordFactory
{
return OrderRecordFactory::new();
}
}<?php
declare(strict_types=1);
namespace Database\Factories;
use App\Modules\Sales\Persistence\OrderRecord;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* TEST DATA ONLY. An Eloquent model factory writes rows with fake values and
* bypasses every rule of the Order aggregate. It is not a DDD factory.
*
* @extends Factory<OrderRecord>
*/
final class OrderRecordFactory extends Factory
{
protected $model = OrderRecord::class;
public function definition(): array
{
return [
'id' => (string) Str::uuid7(),
'customer_id' => (string) Str::uuid7(),
'currency' => 'EUR',
'status' => 'placed',
'total_minor' => fake()->numberBetween(100, 50_000), // may disagree with lines: fine for a fixture, wrong for a domain
'version' => 1,
];
}
public function paid(): static
{
return $this->state(fn (array $attributes) => ['status' => 'paid']);
}
}The Laravel angle
| Laravel feature | Aggregate concern | Notes |
|---|---|---|
| Plain PHP classes for the domain, query builder for persistence | Root guards its parts | Eloquent models with $guarded = [] and public relations cannot guard invariants |
DB::connection('sales')->transaction() | One aggregate per transaction | Rolls back on exception; attempts: retries deadlocks only |
update() returns affected rows | Optimistic locking | where('version', $v)->update([... 'version' => $v + 1]); 0 = conflict |
lockForUpdate() | Pessimistic locking on the root | For hot aggregates with short commands (Locks) |
Model::preventLazyLoading() | Reference by identity | Throws LazyLoadingViolationException instead of silently crossing aggregates |
push() | Anti-pattern detector | "save your model and all of its associated relationships": saving a graph across aggregates |
Mass updates (Order::where(...)->update()) | Bypass of model events | The docs: "the models are never actually retrieved when issuing a mass update", so observers never run |
ShouldDispatchAfterCommit | Event after commit, in-process | Not durable; use the outbox for anything another aggregate depends on |
Queued job with insertOrIgnore on an inbox | Idempotent cross-aggregate handler | Redelivered OrderPaid creates no second shipment |
Str::uuid7() | Identity before persistence | Time-ordered ids generated by the factory |
Eloquent model factories (HasFactory, state()) | Test data | Not DDD factories; they bypass the domain |
Solving the classic problems
One giant Customer aggregate
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Split by true invariants | Customer (profile), Order, Shipment, Invoice as separate aggregates with ids | No unrelated conflicts; bounded loads | Screens need a read model |
| Move other contexts' parts out | Shipments to Fulfilment, invoices to Billing | Each context owns its aggregates | Events between contexts |
| Keep a summary, not a collection | Customer.lifetimeValue updated from OrderPaid events | Customer stays small | Eventually consistent number |
The aggregate is a table (Active Record everywhere)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Domain class + persistence mapping | Plain Order class, repository maps to orders and order_lines | Rules in one place; storage free to change | Mapping code |
| Eloquent as persistence model only | OrderRecord model used inside the repository | Keeps Eloquent conveniences for SQL | Two classes per aggregate |
| Pragmatic middle | Eloquent model with no public setters, guarded relations, behaviour methods | Less code | Easy to erode; enforce with Pest arch() tests |
Public setters and anemic roots
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Replace setters with commands | setStatus('paid') becomes markPaid($ref) | Rules and events live in one method | Rename callers (Ubiquitous Language) |
| Immutable inner values | OrderLine as final readonly, root replaces it | Handing out lines is safe | Allocation per change (negligible) |
| Move logic from services to the root | Service shrinks to load, call, save | One home for each rule (Anemic vs Rich) | Refactoring effort |
Repositories for child entities
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Delete the child repository | Route writes through OrderRepository | Invariants and version always applied | Load the whole aggregate (small anyway) |
| Promote the child | If it really changes alone, make it its own aggregate with its own rules | Honest model | Cross-aggregate rules become events |
Business logic in application services instead of roots
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Push rules into root methods | if ($order->lines()->count() >= 20) moves into addLine | Every caller gets the rule | None worth naming |
| Domain service for multi-aggregate decisions | Reads several aggregates, decides, changes one | Clear home for policy that fits no root | Must still modify one aggregate per tx (Services) |
A rule that spans aggregates
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Creation by construction | Only one factory can create the dependent aggregate, from the right event | Rule cannot be broken | Needs the event flow |
| Saga with compensation | Steps across aggregates; undo on failure | Handles failures and timeouts | Complexity (Saga) |
| Merge (new concept) | Discover a missing aggregate that owns both parts | Atomic | Bigger aggregate; verify size |
Choosing
| Situation | Recommended boundary | Extra technique | Reason |
|---|---|---|---|
| Order with lines, totals, status | One Order aggregate | Version on root; derived total | True invariants across lines |
| Customer profile and their orders | Separate aggregates | customerId on order; read model for history | No invariant spans them; history unbounded |
| Stock levels and orders | Separate (Inventory vs Sales) | Saga: reserve after OrderPlaced, compensate | Different owners and lifecycles |
| Seat map of one performance | One aggregate per performance | FOR UPDATE on root; short commands | Hot, contended, invariant "no double booking" |
| Blog post and comments | Separate aggregates | Comment count via events | Comments grow without bound |
| Bank account and its ledger entries | Account root with balance; entries appended | Optimistic or FOR UPDATE; snapshot balance | "balance never below zero" is a true invariant |
| Shopping cart | One Cart aggregate per shopper | Factory method cart.checkout() → Order | Creation from the previous state |
| Product price change and open orders | Separate | Price snapshot copied into lines at order time | Orders must not change when the catalog does |
Decision flow for one candidate boundary:
1 List the rules. For each: must it hold at every commit? no -> outside (eventual)
2 Whose job is it to make it true? The acting user? no -> outside (eventual)
3 Do the objects in the rule fit in memory for every command? no -> split; summary values on the root
4 Will two users edit different parts at the same time, often? yes -> split along those parts
5 Can the inside be mostly value objects? yes -> do it
6 Root, version, factory, one repository; events for the restIn architecture: from a single process to a distributed system
The aggregate is the unit that survives every architecture change. What changes is the price of crossing its boundary.
Monolith: one process, one database
How it shows up: classes and tables; it is tempting to save Order and Customer in one DB::transaction because nothing stops you.
Simplest correct usage: the same rules anyway: one aggregate per transaction, ids between aggregates, a version column, domain events dispatched after commit. The cost of doing it right in a monolith is small, and it is what makes the later steps possible.
Example (simple): a small shop: Order aggregate as a plain class, DbOrderRepository, OrderPlaced handled by an in-process listener that sends an email after commit.
Example (production-shaped): a 20-developer monolith with a Customer model that has 30 relations; conflicts on customers.updated_at at peak; the fix is the giant aggregate split, done inside the monolith with a read model for the account page.
Modular monolith and multiple databases
How it shows up: each module (Sales, Fulfilment, Billing) owns its aggregates and tables (schema + role per module, see Modular Monolith); an aggregate never spans modules; modules talk through events from the outbox and through ids.
Example: the code on this page in one Laravel app: OrderService saves to the sales connection with the outbox; a relay dispatches CreateShipmentWhenOrderPaid on the queue; the handler writes only to the fulfilment connection.
One deployable, two modules, two schemas
1 Sales: BEGIN (sales) -> UPDATE orders v3->v4, INSERT outbox(order_paid) -> COMMIT
2 Relay: SELECT unpublished outbox rows -> dispatch CreateShipmentWhenOrderPaid
3 Fulfilment: BEGIN (fulfilment) -> INSERT inbox(event_id), INSERT shipments -> COMMIT
4 No transaction touches both schemas; a crash between 1 and 3 is recovered by the relayMicroservices: one aggregate never spans services
What survives: the aggregate, its version, its factory, its events. The outbox relay publishes to a broker instead of a local queue. Each aggregate type belongs to exactly one service (its context), as data ownership requires (Data Ownership).
What breaks: any cross-aggregate transaction that slipped through in the monolith now needs a saga; any object reference across contexts now needs an API call or a local copy; any "check the other aggregate first" becomes a stale read.
sales-svc, billing-svc, fulfilment-svc; separate databases
1 sales-svc Order.place() -> outbox -> topic sales.order.placed.v1
2 billing-svc Payment.capture() -> billing.payment.captured.v1
3 sales-svc Order.markPaid() -> sales.order.paid.v1 (consumer is idempotent)
4 fulfilment-svc Shipment::forPaidOrder() -> shipments table (inbox dedup on event_id)
5 fulfilment-svc Shipment.dispatch() -> fulfilment.parcel.dispatched.v1 -> sales-svc Order.markDispatched()
Failure: payment captured but sales-svc down -> event waits in the broker; order shows "payment pending"Distributed data: shards, replicas, caches and read models
| Where it is tested | What breaks | Design response |
|---|---|---|
| Sharding / partitioning | A transaction across two shards | Shard key = aggregate id: one aggregate always lives on one shard (Evans: "Keep an aggregate together on one server.") |
| Read replicas | Load from a replica, save to primary: stale version | Always load the aggregate for a command from the primary; replicas serve read models only (Replication) |
| Cache of aggregates | Cached copy with an old version saved back | Cache read models, not aggregates; or cache with the version and let the save check it |
| Read models (CQRS) | Screens need data from many aggregates | Project events into query tables; never query across aggregates through repositories (Data Patterns) |
| Large aggregates over time | Load cost grows | Load only what the command needs (a summary on the root), snapshots for event-sourced aggregates, archive old instances |
| Multi-region | Two regions edit the same aggregate | Single home region per aggregate (by id), or conflict-free design; the version check needs one writer |
Helland's paper is the theory behind this table: entities (our aggregates) are the unit that can be moved between machines, and "Atomic Transactions Cannot Span Entities".
Performance: load only what the command needs
| Technique | How | When | Caveat |
|---|---|---|---|
| Keep the boundary small | Root plus values; collections only for true invariants | Always first | Measure conflicts and load time per aggregate type |
| Summary values on the root | lineCount, totalMinor kept by the root, children loaded only for commands that need them | Large child collections that are rarely edited | The root must keep summaries exact (they are invariants too) |
| Lazy part with a measured reason | Vernon's Part III: a rarely used large text moved out or lazily loaded | One heavy attribute | Read-only by convention; do not modify through it |
| Snapshots | Event-sourced aggregates store state every N events and replay only the tail | Long event streams | Snapshot schema must be versioned (Event Sourcing) |
| Read models (CQRS) | Lists, search, dashboards read projections, not aggregates | Any screen showing many aggregates | Eventually consistent; show freshness |
| Archive finished aggregates | Move dispatched/cancelled orders older than N years to cold storage | Tables growing for years | Retention rules; reports read the archive |
Scaling path: 1×, 10×, 100×
| Scale | Aggregates | Practices |
|---|---|---|
| 1× (one team, one database) | Small aggregates, ids between them, version column | Unit tests per root; events after commit |
| 10× (modules, several teams) | Aggregates owned per module; outbox between modules | Conflict-rate and load-time metrics per aggregate type; inbox dedup; read models for screens |
| 100× (services, shards) | Aggregate id as shard and partition key; one service per context | Sagas for cross-aggregate flows, snapshots, per-aggregate ordering of events (Ordering) |
Lab: break and protect an invariant
Everything runs offline with Go installed; step 5 needs Docker for PostgreSQL.
Setup.
cd docs/snippets/ddd/aggregates-factories/go
go test ./...
# ok academy/aggregates-factories/app
# ok academy/aggregates-factories/fulfilment
# ok academy/aggregates-factories/sales- Invariants reject before mutating. Run
go test ./sales -run TestInvariantsRejectBeforeChangingState -v. Every sub-test passes and the line count stays at 20. Now, inAddLine, append first and check afterwards (o.lines = append(...), thenif len(o.lines) > MaxLines { return ErrTooManyLines }) and rerun. The command still returns the right error, but--- FAIL: .../21st_linereportsstate changed: 21 lines: the refusal came after the mutation. Revert. - Concurrent adds cannot pass the limit. Run
go test ./app -run TestInvariantHoldsUnderConcurrency -v. Client B's stale save getsErrConcurrencyConflict; its retry reloads 20 lines and getsErrTooManyLines. - The version must cover children. In
memory/repository.go, change the conflict check so it only compares versions wheno.Status()differs from the stored status (simulating "only bump the root when root columns change"). Rungo test ./app:TestStaleSaveIsRejectedfails withsecond save: <nil>, want conflictandTestInvariantHoldsUnderConcurrencywithstale save: <nil>. The stale save silently replaced A's line with B's (a lost update); with row-per-line storage that only inserts the new line, the same mistake ends with 21 lines. Revert. - Re-saving a stale object never helps. In
TestStaleSaveIsRejected, addt.Logf("re-save stale b: %v", repo.Save(ctx, b))after the conflict check and run with-v: it logsre-save stale b: order was modified concurrently, becausebstill carries version 1 while storage holds 2. Only reloading (asapp.Retrycallers do) makes progress. - The real database. Start PostgreSQL (
docker run --rm -e POSTGRES_PASSWORD=pw -p 5432:5432 postgres:16-alpine), run only the threeCREATE TABLEstatements and the index from the schema (not theBEGINblocks), seed one order withINSERT INTO orders (id, customer_id, currency, status, total_minor, version) VALUES ('o-1', 'c-1', 'EUR', 'draft', 0, 7);, and in twopsqlsessions run (we ran this on PostgreSQL 16; session 2 blocks until session 1 commits, then printsUPDATE 0):
-- session 1 -- session 2
BEGIN; BEGIN;
UPDATE orders SET version = version + 1
WHERE id = 'o-1' AND version = 7; -- UPDATE 1
UPDATE orders SET version = version + 1
WHERE id = 'o-1' AND version = 7; -- waits for session 1
COMMIT;
-- UPDATE 0 (row re-checked after session 1 committed: version is 8)
ROLLBACK; -- the application raises ConcurrencyConflict- Factory versus Eloquent factory. In a Laravel app with the snippets, run the Pest unit test "builds a whole valid order in the factory", then insert a row with
OrderRecord::factory()->create(['total_minor' => 1])(the test-data factory in Laravel) and load it throughDbOrderRepository::get(). The domain object accepts the stored data, because reconstitution trusts storage. That is why fixtures built with Eloquent factories must never be used to test domain rules.
Common misconceptions
| Belief | Reality |
|---|---|
| An aggregate is a big object graph | It is a consistency boundary; most are a root plus value objects |
| Every entity is an aggregate root | Inner entities have local identity and are reached only through their root |
| One aggregate per table | An aggregate often spans tables; a table never spans aggregates |
| All rules belong in one transaction | Only true invariants; the rest is eventual, by events |
| Object references to other roots are fine | They make multi-aggregate writes and huge loads easy; use ids |
| The version only matters when root columns change | It must change on every save of the boundary, or child edits race |
| On conflict, save again | Reload and re-run the command; the stale object is wrong |
DB::transaction(..., attempts: 5) handles optimistic conflicts | It retries deadlocks; your conflict exception needs its own loop |
| Laravel model factories are DDD factories | They create test rows and bypass every rule |
| Reconstitution should validate and emit events like creation | It restores trusted state silently; creation rules and events happened once |
| Use cases map one to one to transactions | "A user goal should not be viewed as synonymous with transaction." |
| Eventual consistency means "maybe never" | It means within an agreed delay, with retries, idempotency and monitoring |
| Deleting an aggregate is normal | Most lifecycles end in a business status (cancelled, closed) |
| Small aggregates mean no inner entities | Inner entities are fine when a true invariant needs them |
Cheat sheet
| Topic | Remember |
|---|---|
| Definition | Cluster of entities + values, one root, one boundary, one transaction |
| Root | Only entry point; enforces invariants; exposes behaviour; hides internals; owns version and events |
| Rule 1 | Model true invariants in consistency boundaries |
| Rule 2 | Design small aggregates: root + values; entities only when a rule needs them |
| Rule 3 | Reference other aggregates by identity |
| Rule 4 | Eventual consistency outside the boundary, after asking "whose job is it?" |
| Transactions | One aggregate instance per transaction; four documented exceptions |
| Concurrency | Version on the root, bumped on every save; 0 rows = conflict; reload and retry; rule errors never retried |
| Pessimistic | FOR UPDATE on the root row for short commands on hot aggregates |
| Events | Root records; repository writes outbox in the same tx; clear after commit |
| Repositories | One per aggregate type; none for inner entities |
| Factories | Whole and valid or nothing; standalone, factory method, named constructor; reconstitution is separate |
| Eloquent | Plain classes for roots; preventLazyLoading; no push() across aggregates; model factories = test data |
| Distribution | Aggregate id = shard key; one aggregate never spans services or shards |
| Sizing smell | Many conflicts or slow loads = too big; rules in sagas = too small |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What three things does one aggregate define at once? Must-know
Answer
Answer: A cluster of objects with one root (the only entry point), a set of invariants that hold after every transaction, and the unit of loading, saving and locking (one transaction, one version). See Aggregate and root.
2 — Name Vernon's four rules in his words. Important
Answer
Answer: Model True Invariants In Consistency Boundaries; Design Small Aggregates; Reference Other Aggregates By Identity; Use Eventual Consistency Outside the Boundary (after asking whose job it is). See the rule table.
3 — Why did Joe's commit fail in Vernon's Product example, and what is the lesson? Important
Answer
Answer: Product contained backlog items, releases and sprints under one version; Bill's backlog item bumped it, so Joe's release scheduling, based on the old version, failed. The large aggregate was built on false invariants. Split by true invariants. See Invariants.
4 — "An order cannot be dispatched unpaid." Transactional or eventual, and how is it enforced in our design? Must-know
Answer
Answer: Eventual: it is the system's job (Billing and Fulfilment), not the shopper's. Fulfilment creates a Shipment only through the factory that takes an OrderPaid message, so an unpaid order has no shipment to dispatch; Order.markDispatched() also refuses unless paid. See Eventual consistency.
5 — Two clients add a line to an order with 19 lines at the same time. What makes sure the order does not end with 21? Must-know
Answer
Answer: The repository always updates the root row with WHERE version = ?, even when only lines changed. The second save affects 0 rows, raises a conflict, the service reloads (20 lines) and addLine refuses with "too many lines". See Concurrency.
6 — Why must the retry loop reload the aggregate instead of saving again? Important
Answer
Answer: The stale object was validated against old state and carries the old version; saving it again conflicts forever or, without a version, overwrites the other client's change. Re-running the command on fresh state re-checks the invariants.
7 — Give two of the four reasons Vernon accepts for modifying several aggregates in one transaction. Good to know
Answer
Answer: User interface convenience (batch creation of independent aggregates), lack of technical mechanisms (no messaging or background processing), global transactions mandated by policy, and query performance (a direct reference for a measured need). See One aggregate per transaction.
8 — What is the difference between OrderFactory::fromCart() and OrderRecord::factory()? Important
Answer
Answer: The first is a DDD factory in production code: it generates an id, looks up prices, and builds a whole valid aggregate through the root's methods. The second is a Laravel Eloquent model factory for tests and seeders that writes rows with fake data and bypasses all domain rules. See Factories.
9 — Why must reconstitute() not record OrderPlaced? Important
Answer
Answer: Loading is not a business event. Recording on load would publish duplicates every time an order is read; creation rules (price lookup, "starts as draft") belong to the moment of creation only.
10 — Your Customer aggregate conflicts constantly at peak and takes 800 ms to load. What do you do? Important
Answer
Answer: Split it: Customer profile, Order, Shipment, Invoice as separate aggregates referenced by id; keep summary values (lifetime value) on the customer updated by events; build a read model for the account page. See Giant Customer.
11 — In a sharded database, what should the shard key of the orders and order_lines tables be, and why? Good to know
Answer
Answer: The order id (the aggregate id) for both, so that one aggregate always lives on one shard and one save is one local transaction. See Distributed data.
Glossary
| Term | Meaning |
|---|---|
| Aggregate | Cluster of entities and value objects treated as one unit for consistency, loading and saving |
| Aggregate root | The single entity through which the aggregate is accessed; enforces its invariants |
| Inner (local) entity | Entity inside an aggregate with identity only within it (an order line) |
| Value object | Immutable object defined by its values (Money); see Entities & Value Objects |
| Invariant | Business rule that must hold after every transaction |
| True invariant / false invariant | A real business rule vs a structural constraint invented by developers |
| Consistency boundary | The line inside which invariants hold immediately (transactional consistency) |
| Transactional consistency | Immediate, atomic consistency within one transaction |
| Eventual consistency | Consistency reached later, through events and separate transactions |
| Reference by identity | Holding another aggregate's id instead of an object reference |
| Disconnected domain model | Using a repository from inside an aggregate to navigate; a form of lazy loading Vernon advises against |
| Whose job is it? | Test: if the acting user must make it consistent, transactional; otherwise eventual |
| User-aggregate affinity | Only one user works on a set of aggregates at a time; makes multi-aggregate transactions safer |
| Optimistic concurrency | Read without locks, check a version at save, retry on conflict |
| Version column | Integer on the root incremented on every save; the concurrency token |
| Pessimistic locking | Locking the root row on load (SELECT ... FOR UPDATE, lockForUpdate()) |
| Contention | Many transactions competing for the same aggregate, causing conflicts or waits |
| Compare-and-set | Update only if the current value equals the expected value |
| Retry with reload | On conflict, load fresh state and re-run the command |
| Domain event | Record of something that happened that domain experts care about |
| Outbox | Table written in the aggregate's transaction from which events are relayed |
| Inbox | Table of processed event ids that makes a consumer idempotent |
| Saga | Sequence of local transactions with compensations across aggregates or services |
| Compensation | Action that semantically undoes an earlier step (release stock, refund) |
| Repository | Collection-like access to whole aggregates of one type |
| Unit of work | Mechanism tracking changes and writing them in one transaction (Hibernate, Doctrine) |
| Persistence by reachability | ORM saves new objects added to a persistent root's collection (Dahan) |
| Factory | Object or method that creates a whole, valid aggregate |
| Standalone factory | Separate domain object for complex creation (OrderFactory) |
| Factory method | Method on an existing aggregate that creates a new one (reorder, planBacklogItem) |
| Named constructor | Static creation method on the root for simple cases (Order::draft) |
| Reconstitution | Rebuilding an aggregate from storage without creation rules or events |
| Eloquent model factory | Laravel test/seed helper that builds model rows with fake data |
| Lazy loading | Loading a relation on first access; hides cross-aggregate reads |
preventLazyLoading | Laravel switch that throws LazyLoadingViolationException on lazy loads |
push() | Eloquent method that saves a model and all loaded relations |
| Snapshot (aggregate) | Persistence shape of an aggregate; in event sourcing, a cached state to shorten replay |
| Read model / CQRS | Query-side tables built from events for screens spanning aggregates |
| Shard key | Column that decides which shard stores a row; the aggregate id for aggregates |
| UUIDv7 | Time-ordered UUID suitable for ids generated before persistence |
| SQLSTATE 40001 / 40P01 / 23505 | PostgreSQL serialization failure / deadlock detected / unique violation |
| Two-phase commit (2PC) | Atomic commit across resources; one of Vernon's reasons to break the rule |
References
- Eric Evans, Domain-Driven Design Reference, 2015 (Aggregates, Factories, Repositories, Domain Events)
- Vaughn Vernon, Effective Aggregate Design, Part I: Modeling a Single Aggregate, Part II: Making Aggregates Work Together, Part III: Gaining Insight Through Discovery, 2011 (the basis of Implementing Domain-Driven Design, 2013, chapter on Aggregates; the book itself was not read for this page)
- Martin Fowler, "DDD_Aggregate", 23 April 2013
- Udi Dahan, "Don't Create Aggregate Roots", 29 June 2009; "Don't Delete – Just Don't", 2009
- Pat Helland, "Life beyond Distributed Transactions: an Apostate's Opinion", CIDR 2007
- Laravel 13 docs: Database: transactions, Query builder: updates and pessimistic locking, Eloquent, Eloquent relationships: preventing lazy loading, push, Events: ShouldDispatchAfterCommit, Eloquent factories, Strings: Str::uuid7
- sqlc, "Using transactions"; pgx,
tx.go(BeginFunc) - MongoDB manual, "Atomicity and Transactions"; Amazon DynamoDB, "Condition expression CLI example"; PostgreSQL, Error codes appendix
- Chris Richardson, microservices.io, Pattern: Aggregate
- Redis, "Transactions" (WATCH as check-and-set); Amazon DynamoDB, TransactWriteItems; PostgreSQL, System columns (xmin); Doctrine ORM, Transactions and Concurrency; Marten, Appending events