Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why a consistency boundary at allWhy aggregates exist
Evans 2003 to Vernon 2011, Helland, Dahan, FowlerWhere it comes from
Cluster, root, entry pointAggregate and root
True vs false invariants, Rule 1Invariants and the consistency boundary
How big, contention, loading cost, Rule 2Design small aggregates
Ids not pointers, Eloquent lazy loading, Rule 3Reference by identity
"Whose job is it?", Rule 4Eventual consistency outside the boundary
The four reasons to break the ruleOne aggregate per transaction
Version column, retry, FOR UPDATEConcurrency on the root
Creation, ids, "don't delete"Lifecycle and identity
Root records events, outboxAggregates and domain events
One repository per aggregateAggregates and repositories
Standalone factory, factory method, reconstitution, Eloquent factoriesFactories
Schema, save algorithm, error codes, per-product behaviourMechanics
Full Order and Shipment with testsGo, Laravel
Giant Customer, aggregate-as-table, public settersSolving the classic problems
Which boundary for which ruleChoosing
Monolith to distributed dataIn architecture
Load only what you need, snapshots, read modelsPerformance
Hands-onLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked in the concept catalogue.

TermIn plain wordsTiny exampleWhat goes wrong without it
AggregateA cluster of objects that is loaded, changed and saved as one unitOrder with its linesRules spread over many objects, nobody guards them
Aggregate rootThe one entity outsiders may touch; it guards the restOrder, not OrderLineCode edits a line directly and breaks "max 20 lines"
InvariantA rule that must be true after every transactiontotal = sum of linesReports and invoices disagree
Consistency boundaryThe line inside which invariants hold immediatelyOrder + lines, not CustomerEither nothing is protected or everything locks together
Reference by identityHolding another aggregate's id, not the objectcustomerId, skuLoading one order loads the whole database
Eventual consistencyOther aggregates catch up later, through eventsShipment created after OrderPaidGiant transactions or lost updates
Version (optimistic lock)A number on the root checked on every saveWHERE id = ? AND version = 7Two clerks silently overwrite each other
FactoryThe code that assembles a whole, valid aggregateOrderFactory::fromCart()Half-built orders, invariants checked "later"
ReconstitutionRebuilding an aggregate from storage, without creation rules or eventsOrder::reconstitute(...)Loading an order re-fires OrderPlaced

Vernon's four rules (each one is a block below):

RulePlain wordsFailure if ignoredWhere
Model true invariants in consistency boundariesPut inside only what must change together atomicallyFalse invariants: unrelated edits conflictInvariants
Design small aggregatesRoot plus a few values; add entities only for a real ruleContention, slow loads, memorySmall
Reference other aggregates by identityKeep ids, look up when neededDeep graphs, accidental multi-aggregate writesBy identity
Use eventual consistency outside the boundaryCross-aggregate rules run later, in their own transactionsGiant transactions, distributed locksEventual

Transactional or eventual? (the test from Vernon and Evans, details in Eventual consistency):

Rule in our shopWhose job is it to make it true?ConsistencyMechanism
An order holds at most 20 linesThe shopper editing the orderTransactional, inside OrderRoot checks; version column
Order total = sum of linesThe shopperTransactional, inside OrderDerived, never stored separately
Stock is reserved for a placed orderThe system (Inventory)EventualOrderPlaced → saga step → compensation
An order cannot be dispatched unpaidThe system (Billing, Fulfilment)EventualShipment created only from OrderPaid
A customer's loyalty points reflect paid ordersThe systemEventualConsumer of OrderPaid
A parcel dispatched marks the order dispatchedThe system (Fulfilment)EventualParcelDispatched → 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 aggregatesMany small aggregates
Every rule can be checked in one transactionOnly true invariants are checked in one transaction
Unrelated edits conflict (one version for everything)Edits to different aggregates never conflict
Loading cost grows with historyLoading cost bounded by design
Easy to write, feels "complete"Needs events, sagas and a UI that accepts "pending"
Cannot be distributed: one unit, one nodeEach aggregate can live on any node or shard
Good for: tiny, single-user toolsGood 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.

Order aggregate = one consistency boundaryOrder (aggregate root)id, customerId, statusversion (optimistic lock)OrderLineentity, localOrderLineentity, localOrderLineentity, localMoney (value)Status (value)Invariants, checked by the root in one transactionlines at most 20; quantity 1..50; one currencytotal = sum(lines); draft-placed-paid-dispatched onlyApplication serviceorder.addLine(...)OrderRepositoryload / save wholeOutside codeline.quantity = 500CustomerIDIdentity ctxSKUCatalog ctxids only, neverobject references

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 ​

  1. "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 Customer that contains every order is the classic failure (Solving).
  2. "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.
  3. "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."

text
     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 page

The 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:

ResponsibilityWhat it means in codeOur Order
Enforce invariantsEvery command checks all rules before changing stateaddLine checks status, currency, quantity, max lines
Expose behaviour, not dataMethods named in the ubiquitous language; no settersplace(), markPaid(), cancel()
Hide internalsInner entities not reachable for mutationline unexported in Go; immutable OrderLine in PHP
Be the only entry pointRepositories, services and other aggregates talk to the rootNo OrderLineRepository
Own the concurrency tokenOne version for the whole boundaryversion column on orders
Record what happenedDomain events collected on the rootOrderPlaced, OrderPaid, OrderCancelled
text
     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 bump

Real 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.

text
     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:

QuestionTrue invariantFalse 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 itDerived from "has" in a sentence
Does one user's action make it true?Usually yesOften another user or the system
What happens if it is enforced later by an event?Visible bugSmall 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.

text
     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 boundary

Real 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.

SymptomLikely causeMove
Many ConcurrencyConflict on one root typeUnrelated edits share a versionSplit along the conflicting use cases
Load time grows with the age of the recordUnbounded collection insideMake the collection items their own aggregates, referenced by id
Command needs two aggregates' state to decideMissing invariant, or wrong splitMerge parts into one aggregate (often with a new name) or use a domain service plus events
Saga compensates a rule that should never be brokenBoundary too smallPull the rule's objects into one aggregate
Root has 40 methods and 15 collectionsSeveral concepts in oneFind 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.

Identity contextCustomeraggregate rootCatalog contextProductaggregate rootSales contextOrdercustomerId: CustomerIDlines[].sku: SKUversionOrderRepository: Order onlyone Save = one transactionno FK to customers or products;ids are values copied inBilling contextPaymentorderId: stringFulfilment contextShipmentorderRef: OrderRefby idby idby idby idobject graph: no

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.

text
     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 saved

Real 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 styleLoadsCan modify both in one tx?DistributionUse when
Object reference, eagerBoth alwaysYes, easilyImpossible across nodesInside one aggregate only
Object reference, lazyOn first touch, hidden queriesYes, accidentallyImpossible across nodesVernon's "Reason Four" exception: a measured query-performance need
Identity (typed id)Only what you ask forOnly if you load both on purposeWorks across shards and servicesDefault between aggregates
Identity + read modelPrebuilt viewNo (read only)Works everywhereScreens 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."

ONE transaction: Ordercheckout: factory + place()lines at most 20, total = sumINSERT orders, order_linesINSERT outbox(OrderPlaced)COMMIT (version 1)user's job: transactionalOutbox relaypublishes OrderPlacedInventory: reserve stocksaga step, may compensateBilling: capture paymentemits PaymentCapturedSales: order.markPaid()new tx, records OrderPaidOutbox relaypublishes OrderPaidFulfilment: new Shipmentonly from OrderPaidSales: order.markDispatched()on ParcelDispatchedDashed arrows = eventual consistency: async message, separate transaction, retried, idempotent"An order cannot be dispatched unpaid" holds because Shipment is only ever created from OrderPaid

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.

text
     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 ruleHowAdvantageCost
Merge into one aggregateBoth parts inside one boundaryAtomic, simpleBigger aggregate, more contention
Domain event + subscriberRoot records, outbox relays, handler updates the other aggregateSmall aggregates, independent scalingDelay, retries, idempotency
Saga / process managerState machine that issues commands and compensationsMulti-step, failure-awareMore code, timeouts (Saga)
Reconciliation jobPeriodic check-and-fixCatches what events missedLong delay; still need events
Two aggregates, one transactionLoad both, save bothImmediateBreaks 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 shopWhy it is acceptableGuard rail
User interface convenienceCreate 30 draft orders from a CSV upload in one requestEach new aggregate keeps its own invariants; batch = one by oneOnly creation of independent aggregates
Lack of technical mechanismsA legacy host with no queue, timer or background workerNothing else can deliver eventual consistencyLook for "user-aggregate affinity": one user per set of aggregates
Global transactionsEnterprise policy mandates two-phase commit (XA)Policy, not designStill modify one aggregate in your own context if you can
Query performanceA direct object reference to a rarely used, large part, lazily loadedMeasured performance needReference is read-only by convention
text
     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 edit

Real 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.

text
     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.

StrategyHowWins whenLoses when
Optimistic, version on rootCompare-and-set on save, retry commandConflicts are rare; aggregates smallHot aggregates: retry storms
Pessimistic, FOR UPDATE on rootLock root row at load, inside the txShort commands on hot aggregates (a seat map)Long user think time; lock waits; deadlocks
Serializable isolation + retryPostgreSQL SSI aborts with SQLSTATE 40001Rules span rows you cannot lock easilyRetries everywhere; needs a retry wrapper
Atomic single statementUPDATE ... SET qty = qty - 1 WHERE qty > 0Counters with one ruleRules that need the whole aggregate
Document store, one document per aggregateMongoDB: "write operations are atomic on the single-document level"Aggregate fits one documentConcurrent edits still need a version field
Conditional writeDynamoDB condition expression on a version attributeKey-value aggregatesError "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."

text
     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.

StageOwnerTypical codeRule
IdentityFactory or id generatorStr::uuid7(), IDs.NextOrderID()Before the first event
CreationFactory / factory methodfromCart, reorder, Shipment::forPaidOrderWhole and valid, or nothing
ChangeRoot methodsaddLine, place, markPaidOne tx, one version bump
ReconstitutionRepositoryreconstitute(...)No events, no creation rules
EndRoot methodcancel, close, archiveA 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.

text
     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 published

Real 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.

ApproachDurable?Same tx as aggregate?Product
Root dispatches directlyNoNoAnti-pattern
Laravel event with ShouldDispatchAfterCommitNo (in-process after commit)Fires after commitLaravel 13: "This interface instructs Laravel to not dispatch the event until the current database transaction is committed."
Outbox table + relayYesYesAny SQL database; Debezium for CDC relays (CDC)
Event-sourced store (events are the state)YesThe append is the transactionMarten 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.

text
     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 questionAnswer 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.

KindWhere it livesUse whenOur example
Named constructorStatic method on the rootCreation is simple: a few checksOrder::draft($id, $customerId, $currency)
Standalone factoryDomain service-like objectNeeds collaborators (price book, id generator), many stepsOrderFactory::fromCart()
Factory method on another aggregateMethod on the "previous state"The business says X creates YVernon: Product.planBacklogItem() returns a new BacklogItem
Factory method on the rootMethod on the same typeA new instance derived from an old oneorder.reorder() creates a new Order
Factory in another contextMessage handler + constructorCreation triggered by an eventShipment::forPaidOrder() from OrderPaid
ReconstitutionRepository + reconstitute()Loading from storageNo events, version restored
Eloquent model factorydatabase/factoriesTests and seeders onlyBuilds orders rows, not aggregates
text
     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 factoryConstructorFactory
Collaborators (price book, clock, ids)Awkward: passed in by every callerInjected once
Many steps, each validatedLong parameter listsReadable assembly
Callers depend on concrete classesYesInterface can hide them (Evans: "does not require the client to reference the concrete classes")
Invariants on the resultMust still holdMust still hold: the factory calls the root's methods
Good forSimple roots and value objectsComplex 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 ​

sql
-- 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 ​

text
     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 commit

Replacing 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 ​

WhereSignalMeaningRetry?
Our repository (any SQL database)UPDATE ... WHERE version = ? affects 0 rowsConcurrent modification of this aggregateYes: reload and re-run the command
PostgreSQLSQLSTATE 40001 serialization_failureREPEATABLE READ / SERIALIZABLE conflict (Isolation Levels)Yes, whole transaction
PostgreSQLSQLSTATE 40P01 deadlock_detectedTwo transactions locking in different orders (Deadlocks)Yes
PostgreSQLSQLSTATE 23505 unique_violationSame aggregate id inserted twice (or inbox dedup)No; treat as "already exists"
MySQL / InnoDBError 1213 (deadlock), 1205 (lock wait timeout), 1062 (duplicate entry)Same three cases in MySQL's numbering1213 yes, 1205 maybe, 1062 no
LaravelDB::transaction(..., attempts: 5)"the number of times a transaction should be retried when a deadlock occurs" (Laravel 13 docs): deadlocks onlyOur ConcurrencyConflict needs our own loop
LaravelIlluminate\Database\LazyLoadingViolationExceptionA relation was lazily loaded after preventLazyLoading()No: fix the code
DynamoDB"The conditional request failed"Condition expression (for example the version) was falseYes, reload
Our domainOrderRuleViolated, ErrTooManyLines, ErrBadTransitionA business rule refused the commandNever

Per-product behaviour ​

StoreNatural aggregate unitAtomicityConcurrency tokenNote
PostgreSQLRoot row + child rowsAny number of rows in one transactionversion column, or xmin system columnAggregate boundary is a design choice, not enforced by the engine
MySQL / InnoDBSame as PostgreSQLTransactionalversion columnDefault REPEATABLE READ does not raise serialization errors; rely on the version check
MongoDBOne 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 updateOneMulti-document transactions exist but signal a boundary smell
DynamoDBOne item, or one partition key with several itemsSingle-item writes; TransactWriteItems for severalCondition expression on a version attributePartition key = aggregate id spreads load
Event store (Marten on PostgreSQL)One stream per aggregateAppend to one streamExpected version on append: Append(streamId, expectedVersion, events)Snapshots bound replay cost (Event Sourcing)
RedisOne hash or JSON key per aggregateMULTI/EXEC with WATCHWATCH on the keyUse 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:

go
// 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 ​

go
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:

go
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 ​

go
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.

go
// 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 ​

go
// 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 ​

go
// 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 ​

go
// 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:

go
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:

go
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))
	}
}
go
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 ​

go
// 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 featureAggregate concernNotes
Unexported struct fields and typesHide internalsline cannot be referenced outside sales; only the root mutates it
Returning copies of slicesNo aliasing into the boundaryLines() builds a new slice; a returned internal slice would let callers change lines
Typed ids (type OrderID string)Reference by identityThe compiler stops you from passing a CustomerID where an OrderID is expected
Sentinel errors + errors.IsRule violation vs conflictErrConcurrencyConflict is retried, ErrTooManyLines is not
database/sql Tx + RowsAffectedCompare-and-set0 rows affected = conflict; defer tx.Rollback() is safe after commit
pgx.BeginFunc / sqlc WithTxTransaction per saveSame algorithm with pgx or generated code
Interfaces owned by the consumerFactory collaboratorsPriceBook and IDs are declared in Sales, implemented by adapters
context.ContextBounded retriesThe 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 featureAggregate concernNotes
Plain PHP classes for the domain, query builder for persistenceRoot guards its partsEloquent models with $guarded = [] and public relations cannot guard invariants
DB::connection('sales')->transaction()One aggregate per transactionRolls back on exception; attempts: retries deadlocks only
update() returns affected rowsOptimistic lockingwhere('version', $v)->update([... 'version' => $v + 1]); 0 = conflict
lockForUpdate()Pessimistic locking on the rootFor hot aggregates with short commands (Locks)
Model::preventLazyLoading()Reference by identityThrows 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 eventsThe docs: "the models are never actually retrieved when issuing a mass update", so observers never run
ShouldDispatchAfterCommitEvent after commit, in-processNot durable; use the outbox for anything another aggregate depends on
Queued job with insertOrIgnore on an inboxIdempotent cross-aggregate handlerRedelivered OrderPaid creates no second shipment
Str::uuid7()Identity before persistenceTime-ordered ids generated by the factory
Eloquent model factories (HasFactory, state())Test dataNot DDD factories; they bypass the domain

Solving the classic problems ​

One giant Customer aggregate ​

SolutionHowAdvantageCost / limitation
Split by true invariantsCustomer (profile), Order, Shipment, Invoice as separate aggregates with idsNo unrelated conflicts; bounded loadsScreens need a read model
Move other contexts' parts outShipments to Fulfilment, invoices to BillingEach context owns its aggregatesEvents between contexts
Keep a summary, not a collectionCustomer.lifetimeValue updated from OrderPaid eventsCustomer stays smallEventually consistent number

The aggregate is a table (Active Record everywhere) ​

SolutionHowAdvantageCost / limitation
Domain class + persistence mappingPlain Order class, repository maps to orders and order_linesRules in one place; storage free to changeMapping code
Eloquent as persistence model onlyOrderRecord model used inside the repositoryKeeps Eloquent conveniences for SQLTwo classes per aggregate
Pragmatic middleEloquent model with no public setters, guarded relations, behaviour methodsLess codeEasy to erode; enforce with Pest arch() tests

Public setters and anemic roots ​

SolutionHowAdvantageCost / limitation
Replace setters with commandssetStatus('paid') becomes markPaid($ref)Rules and events live in one methodRename callers (Ubiquitous Language)
Immutable inner valuesOrderLine as final readonly, root replaces itHanding out lines is safeAllocation per change (negligible)
Move logic from services to the rootService shrinks to load, call, saveOne home for each rule (Anemic vs Rich)Refactoring effort

Repositories for child entities ​

SolutionHowAdvantageCost / limitation
Delete the child repositoryRoute writes through OrderRepositoryInvariants and version always appliedLoad the whole aggregate (small anyway)
Promote the childIf it really changes alone, make it its own aggregate with its own rulesHonest modelCross-aggregate rules become events

Business logic in application services instead of roots ​

SolutionHowAdvantageCost / limitation
Push rules into root methodsif ($order->lines()->count() >= 20) moves into addLineEvery caller gets the ruleNone worth naming
Domain service for multi-aggregate decisionsReads several aggregates, decides, changes oneClear home for policy that fits no rootMust still modify one aggregate per tx (Services)

A rule that spans aggregates ​

SolutionHowAdvantageCost / limitation
Creation by constructionOnly one factory can create the dependent aggregate, from the right eventRule cannot be brokenNeeds the event flow
Saga with compensationSteps across aggregates; undo on failureHandles failures and timeoutsComplexity (Saga)
Merge (new concept)Discover a missing aggregate that owns both partsAtomicBigger aggregate; verify size

Choosing ​

SituationRecommended boundaryExtra techniqueReason
Order with lines, totals, statusOne Order aggregateVersion on root; derived totalTrue invariants across lines
Customer profile and their ordersSeparate aggregatescustomerId on order; read model for historyNo invariant spans them; history unbounded
Stock levels and ordersSeparate (Inventory vs Sales)Saga: reserve after OrderPlaced, compensateDifferent owners and lifecycles
Seat map of one performanceOne aggregate per performanceFOR UPDATE on root; short commandsHot, contended, invariant "no double booking"
Blog post and commentsSeparate aggregatesComment count via eventsComments grow without bound
Bank account and its ledger entriesAccount root with balance; entries appendedOptimistic or FOR UPDATE; snapshot balance"balance never below zero" is a true invariant
Shopping cartOne Cart aggregate per shopperFactory method cart.checkout() → OrderCreation from the previous state
Product price change and open ordersSeparatePrice snapshot copied into lines at order timeOrders must not change when the catalog does

Decision flow for one candidate boundary:

text
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 rest

In 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.

text
     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 relay

Microservices: 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.

text
     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 testedWhat breaksDesign response
Sharding / partitioningA transaction across two shardsShard key = aggregate id: one aggregate always lives on one shard (Evans: "Keep an aggregate together on one server.")
Read replicasLoad from a replica, save to primary: stale versionAlways load the aggregate for a command from the primary; replicas serve read models only (Replication)
Cache of aggregatesCached copy with an old version saved backCache read models, not aggregates; or cache with the version and let the save check it
Read models (CQRS)Screens need data from many aggregatesProject events into query tables; never query across aggregates through repositories (Data Patterns)
Large aggregates over timeLoad cost growsLoad only what the command needs (a summary on the root), snapshots for event-sourced aggregates, archive old instances
Multi-regionTwo regions edit the same aggregateSingle 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 ​

TechniqueHowWhenCaveat
Keep the boundary smallRoot plus values; collections only for true invariantsAlways firstMeasure conflicts and load time per aggregate type
Summary values on the rootlineCount, totalMinor kept by the root, children loaded only for commands that need themLarge child collections that are rarely editedThe root must keep summaries exact (they are invariants too)
Lazy part with a measured reasonVernon's Part III: a rarely used large text moved out or lazily loadedOne heavy attributeRead-only by convention; do not modify through it
SnapshotsEvent-sourced aggregates store state every N events and replay only the tailLong event streamsSnapshot schema must be versioned (Event Sourcing)
Read models (CQRS)Lists, search, dashboards read projections, not aggregatesAny screen showing many aggregatesEventually consistent; show freshness
Archive finished aggregatesMove dispatched/cancelled orders older than N years to cold storageTables growing for yearsRetention rules; reports read the archive

Scaling path: 1×, 10×, 100× ​

ScaleAggregatesPractices
1× (one team, one database)Small aggregates, ids between them, version columnUnit tests per root; events after commit
10× (modules, several teams)Aggregates owned per module; outbox between modulesConflict-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 contextSagas 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.

bash
cd docs/snippets/ddd/aggregates-factories/go
go test ./...
# ok  academy/aggregates-factories/app
# ok  academy/aggregates-factories/fulfilment
# ok  academy/aggregates-factories/sales
  1. Invariants reject before mutating. Run go test ./sales -run TestInvariantsRejectBeforeChangingState -v. Every sub-test passes and the line count stays at 20. Now, in AddLine, append first and check afterwards (o.lines = append(...), then if len(o.lines) > MaxLines { return ErrTooManyLines }) and rerun. The command still returns the right error, but --- FAIL: .../21st_line reports state changed: 21 lines: the refusal came after the mutation. Revert.
  2. Concurrent adds cannot pass the limit. Run go test ./app -run TestInvariantHoldsUnderConcurrency -v. Client B's stale save gets ErrConcurrencyConflict; its retry reloads 20 lines and gets ErrTooManyLines.
  3. The version must cover children. In memory/repository.go, change the conflict check so it only compares versions when o.Status() differs from the stored status (simulating "only bump the root when root columns change"). Run go test ./app: TestStaleSaveIsRejected fails with second save: <nil>, want conflict and TestInvariantHoldsUnderConcurrency with stale 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.
  4. Re-saving a stale object never helps. In TestStaleSaveIsRejected, add t.Logf("re-save stale b: %v", repo.Save(ctx, b)) after the conflict check and run with -v: it logs re-save stale b: order was modified concurrently, because b still carries version 1 while storage holds 2. Only reloading (as app.Retry callers do) makes progress.
  5. The real database. Start PostgreSQL (docker run --rm -e POSTGRES_PASSWORD=pw -p 5432:5432 postgres:16-alpine), run only the three CREATE TABLE statements and the index from the schema (not the BEGIN blocks), seed one order with INSERT INTO orders (id, customer_id, currency, status, total_minor, version) VALUES ('o-1', 'c-1', 'EUR', 'draft', 0, 7);, and in two psql sessions run (we ran this on PostgreSQL 16; session 2 blocks until session 1 commits, then prints UPDATE 0):
sql
-- 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
  1. 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 through DbOrderRepository::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 ​

BeliefReality
An aggregate is a big object graphIt is a consistency boundary; most are a root plus value objects
Every entity is an aggregate rootInner entities have local identity and are reached only through their root
One aggregate per tableAn aggregate often spans tables; a table never spans aggregates
All rules belong in one transactionOnly true invariants; the rest is eventual, by events
Object references to other roots are fineThey make multi-aggregate writes and huge loads easy; use ids
The version only matters when root columns changeIt must change on every save of the boundary, or child edits race
On conflict, save againReload and re-run the command; the stale object is wrong
DB::transaction(..., attempts: 5) handles optimistic conflictsIt retries deadlocks; your conflict exception needs its own loop
Laravel model factories are DDD factoriesThey create test rows and bypass every rule
Reconstitution should validate and emit events like creationIt 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 normalMost lifecycles end in a business status (cancelled, closed)
Small aggregates mean no inner entitiesInner entities are fine when a true invariant needs them

Cheat sheet ​

TopicRemember
DefinitionCluster of entities + values, one root, one boundary, one transaction
RootOnly entry point; enforces invariants; exposes behaviour; hides internals; owns version and events
Rule 1Model true invariants in consistency boundaries
Rule 2Design small aggregates: root + values; entities only when a rule needs them
Rule 3Reference other aggregates by identity
Rule 4Eventual consistency outside the boundary, after asking "whose job is it?"
TransactionsOne aggregate instance per transaction; four documented exceptions
ConcurrencyVersion on the root, bumped on every save; 0 rows = conflict; reload and retry; rule errors never retried
PessimisticFOR UPDATE on the root row for short commands on hot aggregates
EventsRoot records; repository writes outbox in the same tx; clear after commit
RepositoriesOne per aggregate type; none for inner entities
FactoriesWhole and valid or nothing; standalone, factory method, named constructor; reconstitution is separate
EloquentPlain classes for roots; preventLazyLoading; no push() across aggregates; model factories = test data
DistributionAggregate id = shard key; one aggregate never spans services or shards
Sizing smellMany conflicts or slow loads = too big; rules in sagas = too small

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
AggregateCluster of entities and value objects treated as one unit for consistency, loading and saving
Aggregate rootThe single entity through which the aggregate is accessed; enforces its invariants
Inner (local) entityEntity inside an aggregate with identity only within it (an order line)
Value objectImmutable object defined by its values (Money); see Entities & Value Objects
InvariantBusiness rule that must hold after every transaction
True invariant / false invariantA real business rule vs a structural constraint invented by developers
Consistency boundaryThe line inside which invariants hold immediately (transactional consistency)
Transactional consistencyImmediate, atomic consistency within one transaction
Eventual consistencyConsistency reached later, through events and separate transactions
Reference by identityHolding another aggregate's id instead of an object reference
Disconnected domain modelUsing 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 affinityOnly one user works on a set of aggregates at a time; makes multi-aggregate transactions safer
Optimistic concurrencyRead without locks, check a version at save, retry on conflict
Version columnInteger on the root incremented on every save; the concurrency token
Pessimistic lockingLocking the root row on load (SELECT ... FOR UPDATE, lockForUpdate())
ContentionMany transactions competing for the same aggregate, causing conflicts or waits
Compare-and-setUpdate only if the current value equals the expected value
Retry with reloadOn conflict, load fresh state and re-run the command
Domain eventRecord of something that happened that domain experts care about
OutboxTable written in the aggregate's transaction from which events are relayed
InboxTable of processed event ids that makes a consumer idempotent
SagaSequence of local transactions with compensations across aggregates or services
CompensationAction that semantically undoes an earlier step (release stock, refund)
RepositoryCollection-like access to whole aggregates of one type
Unit of workMechanism tracking changes and writing them in one transaction (Hibernate, Doctrine)
Persistence by reachabilityORM saves new objects added to a persistent root's collection (Dahan)
FactoryObject or method that creates a whole, valid aggregate
Standalone factorySeparate domain object for complex creation (OrderFactory)
Factory methodMethod on an existing aggregate that creates a new one (reorder, planBacklogItem)
Named constructorStatic creation method on the root for simple cases (Order::draft)
ReconstitutionRebuilding an aggregate from storage without creation rules or events
Eloquent model factoryLaravel test/seed helper that builds model rows with fake data
Lazy loadingLoading a relation on first access; hides cross-aggregate reads
preventLazyLoadingLaravel 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 / CQRSQuery-side tables built from events for screens spanning aggregates
Shard keyColumn that decides which shard stores a row; the aggregate id for aggregates
UUIDv7Time-ordered UUID suitable for ids generated before persistence
SQLSTATE 40001 / 40P01 / 23505PostgreSQL serialization failure / deadlock detected / unique violation
Two-phase commit (2PC)Atomic commit across resources; one of Vernon's reasons to break the rule

References ​

Built by Morteza Negahi