Aggregate Design
The aggregate boundary decides what changes in one transaction, what gets locked, and whether the system survives concurrent use. The chapter builds on Vernon's Effective Aggregate Design trilogy, shows the mapping in Doctrine ORM, and works through the harder cases: large collections, hot aggregates, snapshots in Event Sourcing, partitioning, and references between aggregates.
In this chapter
The aggregate is the most demanding tactical pattern in DDD, because its boundary is a compromise between consistency, performance, and scalability. Eric Evans described it in the sixth chapter of his 2003 book [1]. Vaughn Vernon devoted a three-part essay to it (2011) [2] and the whole tenth chapter of Implementing Domain-Driven Design (2013) [3]. In Learning Domain-Driven Design (2021), Vlad Khononov sums up the practical guidance from another decade of production experience [4]. The chapter builds on DDD Building Blocks and prepares the ground for CQRS, Event Sourcing, and Sagas and Process Managers.
07.01 Why aggregates exist#
An aggregate is a group of domain objects that the outside world treats as one indivisible unit of consistency. Eric Evans introduced it as an answer to two questions that an object-oriented model does not answer on its own. First: who is responsible for enforcing invariants. Second: what gets saved in one transaction. The entry point into an aggregate is the aggregate root; the other objects inside the boundary must not be directly accessible to the rest of the application.
Without an explicit boundary, a domain model degrades in one of two directions. Either the object graph grows into a single transactional context spanning the whole domain (typically through bidirectional OneToMany relations in Doctrine) and brings locks and deadlocks with it. Or the model falls apart into anemic, thin objects where nobody enforces invariants, and the logic ends up in services. The aggregate picks a compromise between the two extremes: a small consistent unit plus a clear rule for how it changes.
The boundary does more than define a transaction, though. In the DDD Reference (2015) [8], Evans also ties it to distribution: an aggregate stays together on one server, while different aggregates may be spread across nodes. The aggregate boundary therefore also predetermines a later shard or service boundary.
07.02 Vaughn Vernon's four rules of thumb#
Vaughn Vernon summarized the most common traps of aggregate design in a series of three essays, Effective Aggregate Design, in 2011 [2]. The recommendations come from real projects where aggregates that were too large slowed performance and aggregates that were too small violated invariants. Vernon calls them rules in the text, but he also describes them as rules of thumb. The difference matters: in the second part he lists situations in which they are broken deliberately. In the third part he condenses them into four points:
- Model true invariants in consistency boundaries. If a rule must hold at every moment (for example, “the sum of the invoice lines equals the total price”), it belongs inside one aggregate. If a rule may be violated for a few seconds (for example, “a user who signs the contract receives a welcome email”), eventual consistency is enough.
- Design small aggregates. The default choice is an aggregate with a single root object and a few value objects. A larger aggregate needs a concrete justification by an invariant, not ORM convenience or the mental inertia of layered CRUD. Vernon backs this up in the very first part with Niclas Hedhman's experience on a project for financial derivatives: roughly 70% of the aggregates consisted of the root alone with a few value objects, and the remaining 30% had two to three entities in total. Vernon explicitly does not treat this as a universal ratio.
- Reference other aggregates by identity. Instead of an object reference,
the aggregate holds an
OrderIdor aCustomerId. A Doctrine association between aggregates is a signal that a boundary is missing somewhere or that eventual consistency is waiting to be introduced. - Use eventual consistency outside the boundary, after asking whose job it is. A change in several aggregates is handled by a domain event and a separate transaction. “When X happens in aggregate A, a saga updates aggregate B.” Vernon discusses the question “whose job is it” already in the second part, and added it to the wording of the rule only in the third. The section Invariants as the starting point of design covers it in more detail.
Vernon states a fifth principle directly in the first part, though without a number: a well-designed
Bounded Context modifies only one aggregate instance per transaction in all cases. In
Learning DDD (2021), Khononov makes it a rule of its own – one database transaction
modifies exactly one aggregate – and reads the need to commit changes in several aggregates as a
signal of a badly drawn boundary. If one command handler contains two save() calls
on different repositories, review the boundary. Either there should
be two commands, or this is a saga – a multi-step process with its own transaction for
each step.
07.03 Invariants as the starting point of design#
An aggregate boundary cannot be derived from the database schema, an ER diagram, or existing code. It starts from invariants, that is, from rules whose violation would put the model into an inconsistent state. The notion of an invariant as a predicate comes from Design by Contract: in Object-Oriented Software Construction (1997) [9], Bertrand Meyer defines it as a condition that holds before and after every public operation of an object. Vernon reads it more narrowly, in domain terms: an invariant is a business rule that always holds, and for an aggregate the consistency in question is transactional. Typical sources:
- Summation rules. The sum of the lines matches the total price. The number of reserved seats does not exceed capacity. The balance of debits and credits is zero.
- State transitions. An invoice in the
PAIDstate cannot go back toDRAFT. An order pastSHIPPEDcannot be cancelled without a compensating operation. - Existence rules. An invoice must have at least one line. A team must have at least one administrator.
- Quantitative limits. The maximum number of members in a team. A discount limit as a percentage of the order price. The maximum loan amount for a given credit rating.
- Field interdependencies. If
type = SUBSCRIPTION,renewalDatemust not be null. IfshippingMethod = PICKUP,addressmay be null.
For each invariant, one question decides: must a violation be impossible at every moment, or is it enough to reconcile it with a delay? The first category defines the aggregate boundary. The second belongs outside it and is handled by a saga or a Process Manager (see the chapter Sagas and Process Managers).
As long as the question is asked in technical terms, the answer is hard to find. Vernon therefore borrows from Evans a rule of thumb aimed at the user: whose job is it to keep this data consistent? If the job falls to the user who runs the use case, the rule belongs in one transaction and therefore in one aggregate. If it falls to another user or to the system itself, eventual consistency is enough. The question uncovers the real invariants of the domain and separates them from rules that look like invariants only because of the shape of the database schema. Every rule from the list above goes through it before the first sketch of the boundaries exists.
07.04 Aggregate size and its consequences#
A large aggregate looks safe: “better more in one transaction than the risk of inconsistency.” In practice the opposite holds, for three reasons:
- Concurrency. An optimistic lock guards the version of the root. Doctrine does not bump it
on its own when a child changes (see What Doctrine does not enforce), so the domain method
has to touch a field on the root with every change to a child as well. With the version maintained this way, a larger
aggregate means more conflicts. If
Projectholds all itsTasks, two parallel edits of unrelated tasks bump the same version, and one of them ends with anOptimisticLockException. Without deliberately bumping the version, no conflict arises at all – the invariant is then violated silently (see Anti-Patterns and Common Mistakes). In an online store context, a customer typically has one order in progress, soOrderas an aggregate with dozens ofOrderItems is fine. AProjectwith a thousandTasks, by contrast, gives every team member a chance of conflicting with every other one. - Memory and IO. Loading an aggregate hydrates the whole boundary.
A
Projectwith a thousand tasks means a thousand rows in every operation, even when only a single task changes. In Doctrine, lazy-loaded associations make it worse by generating N+1 queries. - Composite invariants. A large aggregate contains rules that have nothing to do with each other. Every change has to pass validation of all of them at once, and the overhead grows with the number of protected invariants.
A practical heuristic: without a concrete invariant that forces two entities to be present together in one transaction, there are two aggregates. The “convenience” of a Doctrine association is not a domain reason.
07.05 Transactional consistency: one aggregate per transaction#
The rule of thumb “one aggregate per transaction” is among the strictest in DDD, and Symfony projects often break it. It rests on these reasons:
- The transaction boundary is a contract. If two aggregates change state together in one transaction, they effectively become one aggregate that happens to be split into two classes.
- Atomically modifying several aggregates makes a later split into microservices or into another Bounded Context harder. The aggregate boundary is the scaling boundary.
- An optimistic lock (
#[ORM\Version]in Doctrine) guards one aggregate instance, and only for changes that touch a field on the root (see the section Mapping in Symfony 8 and Doctrine ORM 3). An attempt to cover two aggregates with it at once ends with a pessimistic lock, which lowers throughput and raises the risk of deadlock. - In Life Beyond Distributed Transactions [5], Helland shows that distributed transactions (XA, two-phase commit) do not work sustainably in practice. His entity is a collection of data that can be changed atomically inside, but never across boundaries. He described the same boundary four years before Vernon's essay, independently of DDD.
In Symfony 8 this means: EntityManager::flush() inside a command handler should
save the changes of one aggregate. A change in another aggregate belongs in a separate
handler, triggered through Messenger after the domain event is published.
1<?php2 3declare(strict_types=1);4 5namespace App\Banking\Application;6 7use App\Banking\Domain\Account\AccountRepository;8use Doctrine\ORM\EntityManagerInterface;9 10// ANTI-PATTERN: a transaction across two aggregates11final class TransferMoneyHandler12{13 public function __construct(14 private readonly AccountRepository $accounts,15 private readonly EntityManagerInterface $em,16 ) {}17 18 public function __invoke(TransferMoney $cmd): void19 {20 $this->em->wrapInTransaction(function () use ($cmd): void {21 $source = $this->accounts->get($cmd->sourceId);22 $target = $this->accounts->get($cmd->targetId);23 24 $source->withdraw($cmd->amount); // change to aggregate A25 $target->deposit($cmd->amount); // change to aggregate B26 27 // wrapInTransaction() flushes and commits both atomically.28 // It looks safe, but in reality:29 // 1) a lock across two aggregates limits scaling,30 // 2) deadlock on concurrent transfers (A→B vs. B→A),31 // 3) this class cannot be split into microservices,32 // 4) there is no audit trail of the transfer attempt (failure = nothing happened).33 });34 }35}
1<?php2 3declare(strict_types=1);4 5namespace App\Banking\Application;6 7use App\Banking\Domain\Account\AccountRepository;8use App\Banking\Domain\Transfer\TransferId;9 10// CORRECT: one aggregate per transaction, a saga via a domain event11final class InitiateTransferHandler12{13 public function __construct(14 private readonly AccountRepository $accounts,15 ) {}16 17 public function __invoke(InitiateTransfer $cmd): void18 {19 $source = $this->accounts->get($cmd->sourceId);20 21 // withdraw() records the event MoneyWithdrawn(transferId, sourceId, targetId, amount).22 // A second handler (TransferSaga) reacts and performs the deposit on the target23 // account in a separate transaction, or a compensation (refund) on failure.24 $source->withdraw($cmd->amount, $cmd->targetId, $cmd->transferId);25 26 $this->accounts->save($source);27 // The optimistic lock on $source prevents concurrent withdrawals.28 // If another InitiateTransfer arrived in parallel, the second one gets29 // an OptimisticLockException and the whole operation can be retried.30 }31}
When to break the rule
Vernon added a section, Reasons to Break the Rules, with four situations in which an experienced team breaks a rule of thumb deliberately – always aware of the price. The first three concern committing several aggregates at once, the fourth concerns reference by identity.
- User interface convenience. A form creates a batch of instances at once. If creating the batch is semantically the same as creating them one at a time, the violation has no consequences.
- Lack of technical mechanisms. The project has no messaging, scheduler, or threads, so eventual consistency has nothing to deliver it.
- Global transactions. The enterprise environment mandates 2PC, and the decision lies outside the team.
- Query performance. Sometimes it pays to hold a direct reference to another aggregate, because looking it up through a repository would make the query more expensive.
Vernon introduces the term user-aggregate affinity for this: what counts is how many users touch the same set of instances at the same moment. If a single user works on them, the risk of conflict is low and the violation is cheap. If a whole team shares them, the price of every such concession grows.
Khononov's diagnosis from 07.02 still applies: the boundary is reviewed before anyone decides that the case really is one of the exceptions. Vernon closes the second part of the series with a remark that you should not go looking for excuses to break the rules.
07.06 Eventual consistency between aggregates#
Eventual consistency worries teams coming from a monolithic CRUD application. Four steps replace a transaction across several aggregates:
- The root of aggregate A performs an operation and publishes a domain event (e.g.,
OrderPlaced). - The Outbox Pattern (see the chapter Outbox Pattern) ensures that the event reliably reaches the message broker, even when another component fails.
- A handler or a saga receives the event and modifies aggregate B in a separate transaction.
- When step 3 fails, the saga performs a compensation or a retry; the domain expects temporary inconsistency.
What decides is how long the inconsistency may last. The answer belongs not to the developer but to the domain expert, and it tends to be more generous than expected. Vernon notes that experts routinely accept a generous number of seconds, minutes, or hours, sometimes even days. Issuing an invoice after an order is completed can tolerate minutes; so can propagating an address change to secondary contexts. Only processes for which the expert accepts no delay at all are candidates for one aggregate rather than a saga.
E-commerce checkout is a typical example. Instead of “save the order, decrease stock,
and send an email in one transaction,” the process splits into three steps. The handler saves
the order and publishes OrderPlaced, which the Order aggregate recorded. The InventoryReservationSaga decreases
the stock in the InventoryItem aggregate in its own transaction. The confirmation email is then sent by
OrderConfirmationEmailSaga, again in a separate transaction. If the stock reservation fails
(the goods sold out in the meantime), the OrderCancelledDueToOutOfStock event triggers a compensation,
and the order is cancelled.
07.07 References by identity, not by object#
Under Vernon's third rule of thumb, aggregates refer to each other by identifier (a value object
such as OrderId or CustomerId), not by object reference. The reasons:
- An object reference invites chained modification such as “
$order->getCustomer()->changeAddress(...)”. Two aggregates then change in a single transaction, and the developer often does not even know it. - In theory, Doctrine lazy loading separates the loading; in practice, it hides that the
second aggregate is being loaded into memory. A hidden coupling arises: whatever changes through the proxy is saved by
the next
flush()together with the aggregate itself. - An identifier reference works the same way in a monolith, a modular monolith, and microservices.
Migrating between these deployment shapes requires no refactoring of the domain model, only replacing
CustomerRepository::get()with an HTTP call. - An identifier is serializable. A domain event that carries it travels through a message broker without loss of information.
Vernon himself allows an exception. In the second part of the series, he lists a direct reference to another aggregate among the reasons to break the rules when it makes queries cheaper. In the third part, the team then considers moving the bulky story text into a separate aggregate and referring to it through a direct, lazily loaded reference, so it does not get loaded every time someone works with a backlog item. A single condition separates an exception from a mistake: such a reference is used for reading. As soon as a domain method of the other aggregate is called through it, the transaction has spread across the boundary and the benefit is gone. In the same spirit, Evans allows passing a reference to an inner member of an aggregate to the outside, but only transiently, for a single operation; the caller must not hold on to it.
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\ValueObject;6 7use Symfony\Component\Uid\Uuid;8 9final readonly class OrderId10{11 public function __construct(12 public string $value,13 ) {14 if (!Uuid::isValid($value)) {15 throw new \InvalidArgumentException('OrderId must be a valid UUID');16 }17 }18 19 public static function generate(): self20 {21 return new self((string) Uuid::v7());22 }23 24 public static function fromString(string $value): self25 {26 return new self($value);27 }28 29 public function __toString(): string30 {31 return $this->value;32 }33 34 public function equals(self $other): bool35 {36 return $this->value === $other->value;37 }38}
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Model;6 7use App\Ordering\Domain\Event\OrderPlaced;8use App\Ordering\Domain\Event\OrderShipped;9use App\Ordering\Domain\Event\OrderCancelled;10use App\Ordering\Domain\Event\OrderConfirmed;11use App\Ordering\Domain\Event\OrderItemAdded;12use App\Ordering\Domain\Event\OrderPaid;13// Later chapters list the exceptions: the first two Implementation in Symfony 814// (10.12), OrderLockedBySagaException the chapter on sagas (14.06).15use App\Ordering\Domain\Exception\EmptyOrderException;16use App\Ordering\Domain\Exception\OrderLockedBySagaException;17use App\Ordering\Domain\Exception\InvalidOrderStateTransitionException;18use App\Ordering\Domain\ValueObject\CustomerId;19use App\Ordering\Domain\ValueObject\OrderId;20use App\Ordering\Domain\ValueObject\OrderStatus;21use App\Ordering\Domain\ValueObject\ProductId;22// ShipmentId belongs to another context – only identity crosses the boundary,23// the same shape as OrderId (a final readonly class with a validated UUID).24use App\Shipping\Domain\ValueObject\ShipmentId;25use App\SharedKernel\Domain\AggregateRoot;26use Doctrine\Common\Collections\ArrayCollection;27use Doctrine\Common\Collections\Collection;28use App\SharedKernel\Domain\Money;29 30final class Order extends AggregateRoot31{32 /** @var Collection<int, OrderItem> */33 private Collection $items;34 35 // Asymmetric visibility: anyone can read, only code inside the class can write.36 // No getter is needed, and state transitions stay the only code that writes it.37 public private(set) OrderStatus $status;38 39 // The aggregate holds the confirmation time because a domain rule depends on it:40 // the cancellation window in the chapter on authorization. A value readable only from the event41 // would force the aggregate to dig into its own history.42 public private(set) ?\DateTimeImmutable $placedAt = null;43 44 // Semantic lock: while a process runs on the order, the user must not45 // touch it. More in the chapter on sagas, section on saga isolation.46 private bool $sagaInProgress = false;47 48 private function __construct(49 public readonly OrderId $id,50 public readonly CustomerId $customerId, // NOTE: an ID, not a Customer object51 ) {52 $this->status = OrderStatus::Draft;53 $this->items = new ArrayCollection();54 }55 56 // The book's canonical factory: identity and owner, nothing more. Ten57 // other chapters call it, so it must not disappear from here.58 public static function place(OrderId $id, CustomerId $customerId): self59 {60 $order = new self($id, $customerId);61 $order->record(new OrderPlaced($id, $customerId));62 63 return $order;64 }65 66 // The invariant “an order has at least one item” is enforced by the signature:67 // without a first item, the order does not come into existence. Next to place(), this is a second68 // factory, not its replacement.69 public static function placeWithFirstItem(70 CustomerId $customerId,71 ProductId $productId,72 int $quantity,73 Money $unitPrice,74 ?\DateTimeImmutable $at = null,75 ): self {76 $order = self::place(OrderId::generate(), $customerId);77 $order->addItem($productId, $quantity, $unitPrice);78 // The order arrived complete, so it leaves Draft right away.79 // Draft is the state of a cart in progress, not of a submitted order.80 $order->confirm($at);81 82 return $order;83 }84 85 public function addItem(ProductId $productId, int $quantity, Money $unitPrice): void86 {87 if ($this->status !== OrderStatus::Draft) {88 throw InvalidOrderStateTransitionException::notAllowedInState(89 'addItem',90 $this->status->value,91 );92 }93 94 // INVARIANT: one item per product – we add up the quantity, we do not duplicate95 foreach ($this->items as $existing) {96 if ($existing->productId->equals($productId)) {97 $existing->increaseQuantity($quantity);98 $this->record(new OrderItemAdded($this->id, $productId, $quantity));99 100 return;101 }102 }103 104 // The item gets a reference to the root – it holds the ManyToOne side105 // of the collection. It has no domain ID of its own, see the mapping below.106 $this->items->add(new OrderItem($this, $productId, $quantity, $unitPrice));107 $this->record(new OrderItemAdded($this->id, $productId, $quantity));108 }109 110 // The time can be passed in from outside for the same reason as in cancel(): the scenario111 // “confirmed at 10:00, cancelled at 12:00” could otherwise112 // be tested only through reflection.113 public function confirm(?\DateTimeImmutable $at = null): void114 {115 if ($this->status !== OrderStatus::Draft) {116 throw InvalidOrderStateTransitionException::cannotTransition(117 $this->status->value,118 OrderStatus::Confirmed->value,119 );120 }121 122 if ($this->items->isEmpty()) {123 throw EmptyOrderException::cannotConfirm();124 }125 126 $this->status = OrderStatus::Confirmed;127 $this->placedAt = $at ?? new \DateTimeImmutable();128 $this->record(new OrderConfirmed($this->id, $this->customerId, $this->placedAt));129 }130 131 // Without this transition, ship() is unreachable: the order has no other way132 // to get into the Paid state.133 public function markPaid(): void134 {135 // The command travels over an asynchronous transport with an at-least-once guarantee,136 // so a repeated delivery is not the caller's error.137 if ($this->status === OrderStatus::Paid) {138 return;139 }140 141 if ($this->status !== OrderStatus::Confirmed) {142 throw InvalidOrderStateTransitionException::cannotTransition(143 $this->status->value,144 OrderStatus::Paid->value,145 );146 }147 148 $this->status = OrderStatus::Paid;149 $this->record(new OrderPaid($this->id, new \DateTimeImmutable()));150 }151 152 public function ship(ShipmentId $shipmentId): void153 {154 if ($this->status === OrderStatus::Shipped) {155 return;156 }157 158 if ($this->status !== OrderStatus::Paid) {159 throw InvalidOrderStateTransitionException::cannotTransition(160 $this->status->value,161 OrderStatus::Shipped->value,162 );163 }164 165 $this->status = OrderStatus::Shipped;166 $this->record(new OrderShipped($this->id, $shipmentId, new \DateTimeImmutable()));167 }168 169 public function lockForSaga(): void170 {171 $this->sagaInProgress = true;172 }173 174 public function releaseSagaLock(): void175 {176 $this->sagaInProgress = false;177 }178 179 // The time comes in as a parameter, not as new \DateTimeImmutable() inside: the chapter180 // on authorization builds the cancellation window on it, and tests need to supply their own.181 public function cancel(string $reason, \DateTimeImmutable $when): void182 {183 // The lock is held by a process, not by a user. Without this condition, a cancellation184 // would go through in the middle of a saga, which would then still capture the payment and create185 // a shipment for an order that no longer exists.186 if ($this->sagaInProgress) {187 throw new OrderLockedBySagaException($this->id);188 }189 190 // Cancellation is an edge of the graph like any other: it cannot bring back a shipped191 // or delivered parcel; that is where compensation in the saga takes over.192 // The list matches the OrderStatus transition table from the chapter Implementation in Symfony 8.193 if (in_array($this->status, [OrderStatus::Shipped, OrderStatus::Delivered], true)) {194 throw InvalidOrderStateTransitionException::cannotTransition(195 $this->status->value,196 OrderStatus::Cancelled->value,197 );198 }199 200 // A repeated cancellation is not the caller's error; there is nothing left to do.201 // Without this branch, a saga retry would crash the handler.202 if ($this->status === OrderStatus::Cancelled) {203 return;204 }205 206 $this->status = OrderStatus::Cancelled;207 $this->record(new OrderCancelled(208 $this->id,209 $this->customerId,210 $reason,211 $when,212 ));213 }214 215 // Ownership belongs to the aggregate, not to a Voter. The chapter on authorization216 // builds its entire access decision on it.217 public function isOwnedBy(CustomerId $customerId): bool218 {219 return $this->customerId->equals($customerId);220 }221 222 public function totalAmount(): Money223 {224 // The guard is necessary: the canonical place() lets an empty order through.225 // Without it, the sum would silently return zero in a hard-coded currency.226 if ($this->items->isEmpty()) {227 throw EmptyOrderException::hasNoItems();228 }229 230 $items = $this->items->toArray();231 $total = $items[0]->subtotal(); // the first item determines the currency232 233 foreach (array_slice($items, 1) as $item) {234 $total = $total->add($item->subtotal());235 }236 237 return $total;238 }239}
The constructor is private: static factories control how the aggregate comes into existence. With
placeWithFirstItem(), the signature itself enforces the invariant “an order must have at least one item.”
Without a first item, the order does not come into existence. The canonical
place(OrderId, CustomerId) from DDD Building Blocks
does not give this guarantee, so totalAmount() and confirm() check it at runtime.
customerId is a value object, not a reference to an entity.
The state transitions confirm(), markPaid(), ship(), and cancel() are the only way to
change status; there is no setter from the outside. The example deliberately relaxes the rule about the root version from section
07.04: addItem() does not change any field on the root, so
it does not bump the version. The justification is user-aggregate affinity – items change only in the
Draft state, when a single customer works with the order. Where several people edit items
at the same time, the domain method has to touch the root as well (see What Doctrine does not enforce). The record() call stores
the event in the internal queue of the AggregateRoot base class; collecting it through
releaseEvents() after the flush is described in the
lifecycle section in DDD Building Blocks.
Since PHP 8.4, the language itself supports encapsulating state through asymmetric visibility:
1final class Order extends AggregateRoot2{3 public private(set) OrderStatus $status;4 5 public function ship(ShipmentId $shipmentId): void6 {7 // ... state check ...8 $this->status = OrderStatus::Shipped; // writing only inside the class9 }10}
Anyone can read a public private(set) property without a getter ($order->status),
but only code inside the class may write it.
The state transitions form a closed graph that has to be modeled in full. Each transition
corresponds to an edge of the graph. Paths missing from the graph are not “not implemented yet”
but forbidden. The diagram shows the lifecycle of the Order aggregate:
The events recorded by the transitions share one shape: the aggregate identity as a value
object and the time of occurrence. Projections and the outbox both rely on occurredAt, so every event carries the field,
and it has the same name everywhere.
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Event;6 7use App\Ordering\Domain\ValueObject\CustomerId;8use App\Ordering\Domain\ValueObject\OrderId;9use App\Ordering\Domain\ValueObject\ProductId;10use App\Shipping\Domain\ValueObject\ShipmentId;11 12final readonly class OrderItemAdded13{14 public \DateTimeImmutable $occurredAt;15 16 public function __construct(17 public OrderId $orderId,18 public ProductId $productId,19 public int $quantity,20 ) {21 $this->occurredAt = new \DateTimeImmutable();22 }23}24 25final readonly class OrderConfirmed26{27 public function __construct(28 public OrderId $orderId,29 public CustomerId $customerId,30 public \DateTimeImmutable $occurredAt,31 ) {}32}33 34final readonly class OrderPaid35{36 public function __construct(37 public OrderId $orderId,38 public \DateTimeImmutable $occurredAt,39 ) {}40}41 42final readonly class OrderShipped43{44 public function __construct(45 public OrderId $orderId,46 public ShipmentId $shipmentId,47 public \DateTimeImmutable $occurredAt,48 ) {}49}50 51final readonly class OrderCancelled52{53 public function __construct(54 public OrderId $orderId,55 public CustomerId $customerId,56 public string $reason,57 public \DateTimeImmutable $occurredAt,58 ) {}59}
Every domain operation records an event: addItem() as well as all the transitions confirm(),
markPaid(), ship(), and cancel(). If any of them stayed silent, projections and sagas would not
know about the change – and the tests in the chapter Testing DDD
expect the events.
OrderPaid carries only the identity and the time. The saga learns who paid and how from the payment context's event; the Order
aggregate does not care.
Later chapters list the three exceptions the aggregate throws. InvalidOrderStateTransitionException
and EmptyOrderException are defined in the chapter
Implementation in Symfony 8,
OrderLockedBySagaException in the chapter
Sagas and Process Managers. All of them extend
\DomainException. The first two have named factories that the listing above calls;
OrderLockedBySagaException is created through its constructor with an OrderId.
ShipmentId lives in the Shipping context and has the same structure as OrderId:
1<?php2 3declare(strict_types=1);4 5namespace App\Shipping\Domain\ValueObject;6 7use Symfony\Component\Uid\Uuid;8 9final readonly class ShipmentId10{11 // The constructor is public, just like in OrderId. Otherwise the Messenger serializer12 // cannot build the value object, and the event cannot be restored from the queue.13 public function __construct(14 public string $value,15 ) {16 if (!Uuid::isValid($value)) {17 throw new \InvalidArgumentException('ShipmentId must be a valid UUID');18 }19 }20 21 public static function generate(): self22 {23 return new self((string) Uuid::v7());24 }25 26 public static function fromString(string $value): self27 {28 return new self($value);29 }30 31 public function __toString(): string32 {33 return $this->value;34 }35}
07.08 Mapping in Symfony 8 and Doctrine ORM 3#
Doctrine ORM is the default choice in Symfony projects, and its configuration often decides whether the aggregate model stays clean or adapts to the database. Vernon covers the aggregate in ch. 10 of IDDD and its persistence in ch. 12, “Repositories.” Six rules apply to Doctrine ORM 3; a list of what Doctrine does not enforce for you follows them:
- Associations only inside the aggregate.
OneToManyandManyToOneconnect only entities within the boundary of the same aggregate. A reference to another aggregate is a property of typeCustomerId, mapped as a custom Doctrine type. - One repository per aggregate. The repository returns only the root, never the inner entities.
get(),save(), perhaps a few specialized methods, not the genericfindByfromEntityRepository. - Optimistic lock on the root. A
#[ORM\Version]column on the root of the aggregate. A concurrent change to the root ends with anOptimisticLockException, which the application layer translates into a retry or a user-facing error. On its own, though, it does not cover changes to inner entities (see the paragraph on versioning below). - Events go out through the outbox. Whatever is meant to leave the context is saved in the same transaction into an outbox table as an integration event. A separate worker then sends it to a Messenger transport (see the chapter Outbox Pattern).
- No cascading across the boundary.
cascade: ['persist', 'remove']between aggregates is a hidden transaction. Cascading is fine only inside an aggregate, for its own entities. - Embedded value objects. Value objects with several fields (Money, Address)
are mapped through
#[ORM\Embedded], not into separate tables.
1<?php2 3declare(strict_types=1);4 5// The type belongs to the context whose identity it converts. In the SharedKernel it6// would make the shared kernel depend on a Bounded Context.7namespace App\Ordering\Infrastructure\Doctrine\Type;8 9use App\Ordering\Domain\ValueObject\OrderId;10use Doctrine\DBAL\Platforms\AbstractPlatform;11use Doctrine\DBAL\Types\Exception\InvalidType;12use Doctrine\DBAL\Types\Type;13 14// CustomerIdType and ProductIdType look the same, only with a different VO and type name.15final class OrderIdType extends Type16{17 public function getSQLDeclaration(array $column, AbstractPlatform $platform): string18 {19 // 36 characters = the RFC 4122 UUID notation returned by OrderId::generate()20 return $platform->getStringTypeDeclarationSQL(['length' => 36, 'fixed' => true]);21 }22 23 public function convertToPHPValue(mixed $value, AbstractPlatform $platform): ?OrderId24 {25 return $value === null ? null : OrderId::fromString((string) $value);26 }27 28 public function convertToDatabaseValue(mixed $value, AbstractPlatform $platform): ?string29 {30 if ($value === null || $value instanceof OrderId) {31 return $value?->value;32 }33 34 // Without this branch, a string would end up as NULL and the query would silently35 // find nothing – the worst kind of bug, because nothing ever fails.36 throw InvalidType::new($value, self::class, ['null', OrderId::class]);37 }38}
The class deliberately has no getName() method, because DBAL 4 removed it. The type name
(order_id) is determined solely by the key in the doctrine.dbal.types configuration below,
and the #[ORM\Column(type: 'order_id')] attribute refers to the type under the same name.
Along with getName(), the requiresSQLCommentHint() method disappeared too, so DBAL no longer
leaves a comment in the schema for a custom type. This does not affect schema comparison:
AbstractPlatform::columnsEqual() compares the generated SQL declaration, not the
PHP type, and the CHAR(36) from OrderIdType matches the introspected column. No empty
migrations result from it. You pay for the missing comment elsewhere: the schema diff can no longer tell apart two custom
types over the same SQL declaration, so a migration will not reveal that order_id was swapped
for customer_id in the mapping.
CustomerIdType and ProductIdType, which doctrine.yaml registers below, have
the same structure. They differ only in the type name and the value object they convert;
the book therefore does not list them.
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Domain\Model;6 7use App\Ordering\Domain\ValueObject\CustomerId;8use App\Ordering\Domain\ValueObject\OrderId;9use App\Ordering\Domain\ValueObject\OrderStatus;10use App\SharedKernel\Domain\AggregateRoot;11use Doctrine\Common\Collections\ArrayCollection;12use Doctrine\Common\Collections\Collection;13use Doctrine\ORM\Mapping as ORM;14 15#[ORM\Entity]16#[ORM\Table(name: 'orders')]17final class Order extends AggregateRoot18{19 #[ORM\Column(enumType: OrderStatus::class)]20 public private(set) OrderStatus $status;21 22 #[ORM\Column(type: 'datetime_immutable', nullable: true)]23 public private(set) ?\DateTimeImmutable $placedAt = null;24 25 #[ORM\Column(type: 'boolean')]26 private bool $sagaInProgress = false;27 28 // The mapping changes the collection type: instead of the list<OrderItem> array29 // from the pure domain variant, Doctrine requires a Collection.30 /** @var Collection<int, OrderItem> */31 #[ORM\OneToMany(32 mappedBy: 'order',33 targetEntity: OrderItem::class,34 cascade: ['persist', 'remove'], // OK: cascading inside the aggregate35 orphanRemoval: true,36 )]37 private Collection $items;38 39 // NOTE: no ManyToOne to Customer – only CustomerId.40 // No ManyToOne to Product – only ProductId in OrderItem.41 42 #[ORM\Version]43 #[ORM\Column(type: 'integer')]44 private int $version = 1;45 46 private function __construct(47 #[ORM\Id]48 #[ORM\Column(type: 'order_id')]49 public readonly OrderId $id,50 51 #[ORM\Column(type: 'customer_id')]52 public readonly CustomerId $customerId, // an ID, not a ManyToOne to Customer53 ) {54 $this->status = OrderStatus::Draft;55 $this->items = new ArrayCollection();56 }57 58 // ... factory methods, domain operations ...59}
This listing replaces the property declarations from 07.07; it is not added to them. Anyone who
pastes both blocks one after the other gets Cannot redeclare Order::$status, and the same for $placedAt
and $items. The identity and the owner stay promoted in the constructor; the Doctrine attributes
sit directly on the parameters, so they too have one declaration, not two. The methods
and factories, on the other hand, come from 07.07; the listing leaves them out only for length.
The mapping above refers to two classes that do not work without attributes of their own.
Money is an embeddable value object; OrderItem is a full entity inside the
aggregate boundary and needs its own identity and a back reference, otherwise
mappedBy: 'order' has no counterpart and the mapping fails. The third class in the listing,
ShippingAddress, shows an embeddable with several fields and its own validation. The canonical Order
does not carry it as a property – just like the version from
DDD Building Blocks and the rest of the book with the two-parameter
place(). An order extended with shippingAddress appears only in the specifications
in the chapter Supporting Tactical Patterns:
1<?php2 3declare(strict_types=1);4 5namespace App\SharedKernel\Domain;6 7use Doctrine\ORM\Mapping as ORM;8 9// Money is embeddable, otherwise #[ORM\Embedded] in OrderItem fails.10// The domain definition from DDD Building Blocks stays; only the attributes are added.11#[ORM\Embeddable]12final readonly class Money13{14 public function __construct(15 #[ORM\Column]16 public int $amountInCents,17 #[ORM\Column(enumType: Currency::class)]18 public Currency $currency,19 ) {20 if ($amountInCents < 0) {21 throw new \InvalidArgumentException('Money cannot be negative');22 }23 }24 25 // add(), subtract(), multiply(), percentage(), equals() – see 06.0426}27 28// --- src/Ordering/Domain/ValueObject/ShippingAddress.php ---29namespace App\Ordering\Domain\ValueObject;30 31use Doctrine\ORM\Mapping as ORM;32 33#[ORM\Embeddable]34final readonly class ShippingAddress35{36 public function __construct(37 #[ORM\Column]38 public string $street,39 #[ORM\Column]40 public string $city,41 #[ORM\Column(length: 16)]42 public string $postalCode,43 #[ORM\Column(length: 2)]44 public string $countryCode,45 ) {46 if (strlen($countryCode) !== 2) {47 throw new \InvalidArgumentException('Country code must be ISO 3166-1 alpha-2');48 }49 }50}51 52// --- src/Ordering/Domain/Model/OrderItem.php ---53namespace App\Ordering\Domain\Model;54 55use App\Ordering\Domain\ValueObject\ProductId;56use App\SharedKernel\Domain\Money;57use Doctrine\ORM\Mapping as ORM;58 59#[ORM\Entity]60#[ORM\Table(name: 'order_items')]61final class OrderItem62{63 // A surrogate identity. The item has no domain ID – nothing outside64 // refers to it, and it is accessed exclusively through the root.65 #[ORM\Id]66 #[ORM\GeneratedValue]67 #[ORM\Column]68 private ?int $id = null;69 70 public function __construct(71 #[ORM\ManyToOne(inversedBy: 'items')]72 #[ORM\JoinColumn(nullable: false)]73 private Order $order,74 #[ORM\Column(type: 'product_id')]75 public readonly ProductId $productId,76 // private(set): readable from outside, only the item itself may change it.77 // readonly would not work – increaseQuantity() changes the value.78 #[ORM\Column]79 public private(set) int $quantity,80 #[ORM\Embedded(class: Money::class)]81 public readonly Money $unitPrice,82 ) {}83 84 public function increaseQuantity(int $by): void85 {86 if ($by < 1) {87 throw new \InvalidArgumentException('Quantity increment must be positive');88 }89 90 $this->quantity += $by;91 }92 93 public function subtotal(): Money94 {95 return $this->unitPrice->multiply($this->quantity);96 }97}
An embeddable must not be nullable. #[ORM\Embedded] over ?ShippingAddress looks
innocent, but Doctrine never returns null when loading. It returns a half-built instance
on which $address->street ends with Error: Typed property must not be accessed before initialization. The check if ($address !== null) is always true, so it does not catch the error.
A value that may not exist therefore belongs either in a separate entity or in scalar
nullable columns, not in an embeddable. That is exactly why Order above does not hold the address: delivery
details come into being only at checkout and belong to it, not to the creation of the order.
The surrogate int identity is a deliberate decision, not negligence. OrderItem has no domain
identity, because nobody outside the aggregate refers to the item. A UUID would only take up
space here. If something did refer to it, that would be a signal that the item belongs in an aggregate of its own.
1<?php2 3declare(strict_types=1);4 5namespace App\Ordering\Infrastructure\Repository;6 7use App\Ordering\Domain\Model\Order;8use App\Ordering\Domain\ValueObject\OrderId;9// Implementation in Symfony 8 (10.12) lists the exception's definition.10use App\Ordering\Domain\Exception\OrderNotFoundException;11use App\Ordering\Domain\Repository\OrderRepository;12use Doctrine\ORM\EntityManagerInterface;13 14final class DoctrineOrderRepository implements OrderRepository15{16 public function __construct(17 private readonly EntityManagerInterface $em,18 ) {}19 20 public function get(OrderId $id): Order21 {22 $order = $this->em->find(Order::class, $id);23 24 if ($order === null) {25 throw OrderNotFoundException::withId($id);26 }27 28 return $order;29 }30 31 public function save(Order $order): void32 {33 $this->em->persist($order);34 // Flush and commit are handled by the command bus doctrine_transaction middleware.35 // On flush, the root + inner entities (OrderItem) are saved thanks to36 // cascade: ['persist']; Doctrine throws an OptimisticLockException37 // if #[ORM\Version] has changed in the meantime.38 }39 40 // NO findAll(), findBy(), no methods for reading inner entities.41 // Read models are separate (see the CQRS chapter).42}
1# config/packages/doctrine.yaml2doctrine:3 dbal:4 url: '%env(resolve:DATABASE_URL)%'5 types:6 order_id: App\Ordering\Infrastructure\Doctrine\Type\OrderIdType7 customer_id: App\Ordering\Infrastructure\Doctrine\Type\CustomerIdType8 product_id: App\Ordering\Infrastructure\Doctrine\Type\ProductIdType9 # The types for User (UserId, Email) are added in the chapter Implementation10 # in Symfony 8; without them, its mapping fails.11 email_vo: App\UserManagement\Infrastructure\Doctrine\Type\EmailType12 user_id: App\UserManagement\Infrastructure\Doctrine\Type\UserIdType13 # Money is not added here – it is mapped through #[ORM\Embedded] according to14 # the rule above. A single-column custom type would rule out SUM() and ORDER BY.15 16 orm:17 # Without the underscore strategy, you get columns like occurredAt, createdAt…18 # and they diverge from the indexes and raw SQL the book writes in snake_case.19 naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware20 identity_generation_preferences:21 Doctrine\DBAL\Platforms\PostgreSQLPlatform: identity22 mappings:23 Ordering:24 type: attribute25 dir: '%kernel.project_dir%/src/Ordering/Domain'26 prefix: 'App\Ordering\Domain'27 is_bundle: false28 # Embeddable value objects of the shared kernel (Money) must be29 # in the mapping chain too, otherwise Doctrine reports30 # “class … was not found in the chain configured namespaces”.31 SharedKernel:32 type: attribute33 dir: '%kernel.project_dir%/src/SharedKernel/Domain'34 prefix: 'App\SharedKernel\Domain'35 is_bundle: false36 # Entities outside the domain folders need a block of their own. Without it,37 # Doctrine stays silent on schema:update (“Nothing to update”) and the table38 # is never created – which is why we list them here instead of only mentioning them.39 #40 # NOTE: the following blocks map directories that come into being only41 # in later chapters (sagas 14, outbox and inbox 15, identity 11).42 # If you read in order, add them along with the corresponding chapter; otherwise43 # the container fails with “Specified non-existing directory … as44 # Doctrine mapping source”.45 OrderingSaga:46 type: attribute47 dir: '%kernel.project_dir%/src/Ordering/Application/Saga'48 prefix: 'App\Ordering\Application\Saga'49 is_bundle: false50 Outbox:51 type: attribute52 dir: '%kernel.project_dir%/src/Outbox/Domain'53 prefix: 'App\Outbox\Domain'54 is_bundle: false55 Inbox:56 type: attribute57 dir: '%kernel.project_dir%/src/Inbox/Domain'58 prefix: 'App\Inbox\Domain'59 is_bundle: false60 UserManagement:61 type: attribute62 dir: '%kernel.project_dir%/src/UserManagement/Domain'63 prefix: 'App\UserManagement\Domain'64 is_bundle: false65 # SecurityUser from the chapter on authorization sits in the infrastructure,66 # not in the domain – without its own block, the table would not be created67 # and the firewall would have nowhere to load users from.68 Identity:69 type: attribute70 dir: '%kernel.project_dir%/src/Identity/Infrastructure'71 prefix: 'App\Identity\Infrastructure'72 is_bundle: false
What Doctrine does not enforce
The six rules above look like configuration, but in reality they are conventions nobody checks. Matthias Noback wrote up a detailed list of the friction points between Doctrine and the aggregate [12]. Two of the rules break silently in production.
The first is versioning. #[ORM\Version] increments the version only when a field on the root has changed.
A change to an inner entity, typically an OrderItem, is not reflected in the version of the Order. Evans's example
from DDD (2003), which Vernon quotes in the first part of the essay, shows this: an order has an
approved limit, and the sum of its items must not exceed it. Two requests each increase the quantity
of a different item in the same order. Each checks the limit only against its own snapshot, and both succeed.
The sum then exceeds the cap without anyone getting an OptimisticLockException.
Doctrine has no equivalent of the JPA constant OPTIMISTIC_FORCE_INCREMENT; the request for it
has been open since 2013 [10]. There are two
ways around it. The root's domain method touches one of its own fields with every change to a child
(a stored recalculated total price or updatedAt); such a change often has domain meaning too, and it bumps
the version. The second way is a pessimistic lock, LockMode::PESSIMISTIC_WRITE, at the cost of
throughput. Calling $em->lock($order, LockMode::OPTIMISTIC, $expectedVersion) with the version
the client holds is not enough on its own: it detects a stale form, but it does not bump the version, so two
concurrent requests on the same version both go through.
The second gap is the transaction boundary. EntityManager::flush() writes all changed
entities in its Unit of Work, not only the aggregate the handler loaded. The repository from the example above
therefore does not enforce the rule “one aggregate per transaction.” If a handler touches another
aggregate along the way and merely changes one of its properties, Doctrine saves it at the same time – without warning. Only
discipline, code review, and an architecture test enforce it (see the chapter
Testing DDD). If you want to separate the domain model
from the persistence model completely, reach for the Persisted Object Pattern
(Implementation in Symfony 8). The domain
class stays free of ORM attributes, and a separate persistence class with a mapper handles the mapping.
The cost is an extra layer; the benefit is that Doctrine stops shaping the aggregate.
07.09 Advanced topics: large collections, hot aggregates, and snapshots#
The large-collection problem
A typical anti-pattern: a Project aggregate holds a OneToMany collection of tasks.
With dozens of tasks it works; with thousands it does not. Every load of the aggregate hydrates
the whole collection, and every flush then goes through the changes of all loaded tasks. Three
ways out are available, ordered from the cleanest to the one with the most compromises:
- Split the aggregate.
ProjectandTaskbecome separate aggregates, andTaskcarries only aProjectIdas a reference. The invariant “a task belongs to an existing project” is then enforced not by a Doctrine association but by the command handler through aProjectExistsSpecification, which verifies that the project exists before the task is created. - Doctrine extra-lazy collection.
fetch: 'EXTRA_LAZY'allows$project->getTasks()->count()without loading the collection, or$project->getTasks()->matching($criteria). Usable when the aggregate really needs the collection for its invariants (e.g., a limit on the number of tasks per project). One trap: an uninitialized collection translates the criteria into SQL, while a loaded one evaluates them in memory over already hydrated objects. With a backed enum in the criteria, both paths give the same result; with a raw database value ('open'instead ofTaskStatus::Open), they do not. Over a loaded collection, the comparison with the enum fails, and the result is empty. The criteria take the enum, not the string. - The aggregate as a service boundary. A service working with the aggregate replaces the collection and verifies the invariant with a repository query. It works, but it signals a wrong boundary.
Hot aggregate
A hot aggregate is an aggregate that many users touch concurrently (a shopping cart during
Black Friday, a sports score, a real-time game). Optimistic locking fails here:
most transactions end with an OptimisticLockException, retries take time, and users wait.
There is no absolute threshold in transactions per second. The probability of a conflict is determined by the product of the write frequency per instance and the time a transaction holds the state. An aggregate with ten writes per second and a one-millisecond transaction is calm; the same aggregate with a transaction lasting two hundred milliseconds produces conflicts. So you measure both, and only then make the decision. Approaches:
- Split the aggregate into smaller ones. Instead of a
Stadiumwith a thousand seats, there is aSectionwith dozens. Concurrent transactions spread out. - Switch to Event Sourcing. Writes are append-only, and concurrency is guarded by the expected version of the stream (see the chapter Event Sourcing). A conflict can then be judged by which events were added in the meantime, instead of discarding the whole transaction.
- Single-writer pattern. The aggregate lives in the memory of a single process (actor model, Akka, Orleans). Symfony does not support this natively; the alternative is Messenger with routing by consistent hash and a single consumer per aggregate ID.
- Accept eventual consistency inside. For counters, for example (like count), the exact state does not matter; delayed replication with an inaccuracy on the order of seconds is enough.
Snapshots in Event Sourcing
For event-sourced aggregates, rebuilding the state from events has O(N) complexity. A snapshot stores the serialized state of the aggregate after N events; on load, the state is reconstructed from the latest snapshot, and the remaining tail of the stream is applied on top. The threshold N is measured, not guessed: it depends on the size of the events and on what a replay really costs. A long stream is also more often a symptom of a badly drawn boundary than a real need for a snapshot.
Three things matter for aggregate design. A snapshot is not the authoritative state, only an optimization. When a snapshot cannot be loaded, the state is rebuilt from the beginning of the stream. Its versioning must be compatible with event versioning, so a change to the state schema means invalidating old snapshots. And the snapshot store stays separate from the event store, filled by a background process. A snapshot written directly into the event log always has to be at the latest version, which, for busy aggregates, creates its own loop of conflicts. The chapter Event Sourcing covers the implementation.
Partitioning and multi-tenancy
For aggregate design, multi-tenancy has a single but hard consequence: tenantId is part of the
aggregate's identity, not a filter tacked onto a query. The repository takes the pair
(tenantId, aggregateId), and an operation of one tenant never touches an instance of another.
The choice of database topology does not change this conclusion. A Doctrine SQLFilter
with tenant_id = :current_tenant is the cheapest and can be bypassed with native SQL; a schema per
tenant isolates more at the cost of cross-schema reports; a database per tenant isolates the most
and costs the most to operate. The decision belongs to the infrastructure; the aggregate boundary stays
the same in all three cases.
07.10 Strategies for referencing across aggregates#
Reference by ID is a clear rule, but there are several kinds of IDs, and each affects the schema and performance.
- UUID v4 (random). Random, generatable in a distributed way, unguessable. Drawback: the insertion order is not sorted, and with clustered indexes (MySQL/InnoDB) this worsens the I/O pattern.
- UUID v7. Sorted by creation time and generated in a distributed way
without coordination. The recommended choice for most new projects.
ULID has similar properties and remains an alternative; the
symfony/uidpackage provides bothUuid::v7()and ULID (Symfony\Component\Uid\Ulid). - Sequential integer. Short, human-readable, fast. Drawbacks: it requires a central generator (a DB sequence), reveals the order and count of entities, and is hard to merge from multiple DBs (microservices).
- Composite ID.
(tenantId, naturalId). Suitable for multi-tenancy. Drawback: every table has a two-column PK, and JOIN conditions get more complex. - Natural key. A value from the domain (ISBN, company registration number, email). It works until the domain changes the value – and domains change their “natural keys” more often than it seems. The book does not recommend it.
07.11 Step-by-step design workflow#
Aggregate design is a disciplined process, not drawing classes in an IDE. The book put together the seven-step workflow below; steps 4 and 5 adopt Vernon's estimation method, and the rest comes from practice on Symfony projects:
- Write down the invariants. Pull all the rules out of Event Storming, domain workshops, or conversations with experts. Phrase each one as the sentence “at every moment, it must hold that …”. Set aside the rules that do not pass (“eventually it must hold”). They will be sagas.
- Group the invariants. Rules that share the same entities are candidates for a common aggregate. Whatever is unrelated belongs elsewhere.
- Identify the root. For each group of invariants, choose one entity that serves as the “entry point.” Typically, it is the one with the highest domain authority (“Order” vs. “OrderItem”).
- Estimate the size with pencil and paper. Vernon demonstrates this on a backlog item: a twelve-day sprint, twelve tasks per backlog item, and for each task twelve re-estimation entries, which makes 144 nested objects. With lazy loading, one request holds at most twenty-five objects in memory: the backlog item, twelve tasks, and the entries of only one of them. Vernon considers such an aggregate small. The same calculation for your own domain takes half an hour, an hour at worst, and replaces an impression with an upper estimate of growth.
- Estimate the concurrency. How many writes per second hit one instance of the aggregate at peak, and how long does a transaction hold the state? The product of the two numbers decides whether you have a hot aggregate and whether you reach for one of the techniques from 07.09.
- Define commands and events. For each use case, write a command (input),
a domain method on the aggregate (behavior), and an event (output). Record events explicitly
with the
record()method; the whole record/release cycle is described in the lifecycle section in DDD Building Blocks. - Code review against the checklist. Section 07.13 has a 12-point checklist. As long as the answer to any point is “no,” the design is not finished.
The Case Study shows the same workflow on the Project and Task aggregates
from a nontrivial project management domain.
Aggregate Design Canvas
There is a ready-made template for workshops. The Aggregate Design Canvas from the ddd-crew group [11] has nine fields: name, description, state transitions, enforced invariants, corrective policies, handled commands, created events, throughput, and size. It is distributed under the CC BY 4.0 license, so it can be adapted for your own team.
Two parts of the template have no field of their own in the classic books. Corrective Policies describe what happens when the boundary is deliberately relaxed; compensation thus stops being a consequence of failure and becomes part of the design. Throughput and Size force you to estimate the frequency of commands, the number of concurrent clients, the growth rate, and the lifetime of an instance. This is Vernon's method from steps 4 and 5, promoted to a standard field.
The canvas is filled in directly over the output of Event Storming: commands, events, and policy stickies carry over from it, and hot spots become candidates for invariants.
07.12 Common mistakes#
- A large aggregate for ORM convenience: “Since we already have a
OneToMany, let's put the order in there too.” Associations are a mapping tool, not a guide to the boundary. - A saga where an aggregate should be. A saga cannot maintain an invariant that must hold immediately. The rule “an insurance policy must never be paid without a signed contract” cannot tolerate a few seconds of waiting, and that is why it belongs in an aggregate.
- Domain logic in the read model. Invariants belong in the write model; the projection only reacts.
- A Domain Event as a notification between layers, that is, a mechanism for “when the aggregate changes, clear the cache.” Events are domain facts, not infrastructure signals. Cache invalidation belongs in a projection that consumes the event.
Several other mistakes share a common denominator: bypassing the root.
$order->getItems()->add(...) changes the collection outside the aggregate. From the outside, the collection should remain
immutable, and an item is added exclusively through a method on the root. OrderItemRepository::get(itemId)
demonstrates the same boundary violation: an inner entity is not handed out to be kept
or modified (the exception for a single operation is described in 07.07),
and its “independent” identity belongs in the read model, not in the write model. A related
pattern is the anemic aggregate with public setters. An aggregate with get/set for every property
is a data structure. State transitions should be methods that express domain intent
(confirm(), ship(), cancel()).
A variant of the same thing at a higher level is state shared through a service. A helper “OrderService”
that reaches into two aggregates is a hidden transaction. As soon as the service itself calls
$em->flush(), it is an anti-pattern.
07.13 Aggregate design checklist#
- I have written down the invariants in the Ubiquitous Language (words from the domain, not from the code).
- For each invariant, I know whether it must hold immediately or eventually.
- The aggregate boundary encloses the invariants in the “immediately” category.
- The root has an optimistic lock (
#[ORM\Version]or an equivalent), and every domain method that changes an inner entity also touches a field on the root. - References to other aggregates are by identifier (value object), not by object.
- No Doctrine association crosses the aggregate boundary.
- The repository returns only the root; an inner entity is not handed out to be kept or modified.
- Changes across aggregates are handled by a saga or a Process Manager, not by a shared transaction – and if a shared transaction remains anyway, there is a named reason why.
- The UI accounts for eventual consistency wherever the domain uses it.
- Cascading operations exist only inside the aggregate.
- State transitions are methods that express domain intent, not setters.
- The root identifier is a value object with validation (not a bare
string/int).
07.14 Further reading#
- Eric Evans, Domain-Driven Design: Tackling Complexity in the Heart of Software, ch. 6, “The Life Cycle of a Domain Object” (Aggregates section) (Addison-Wesley, 2003) [1].
- Vaughn Vernon, Effective Aggregate Design, Parts I–III (2011) [2] – the canonical text on the rules of aggregate design, cited by nearly every later DDD book.
- Vaughn Vernon, Implementing Domain-Driven Design, ch. 10, “Aggregates,” and ch. 12, “Repositories” (Addison-Wesley, 2013) [3].
- Vlad Khononov, Learning Domain-Driven Design, ch. 6, “Tackling Complex Business Logic,” and ch. 7, “Modeling the Dimension of Time” (O'Reilly, 2021) [4].
- Pat Helland, Life Beyond Distributed Transactions: an Apostate's Opinion, ACM Queue (2007, reprinted 2016) [5].
- Martin Fowler, DDD_Aggregate (bliki) [6].
- Greg Young, CQRS Documents (2010) [7] – relevant mainly for the chapters on Event Sourcing and snapshots.
- Eric Evans, Domain-Driven Design Reference: Definitions and Pattern Summaries (2015) [8] – a freely available PDF with a condensed definition of the aggregate, including the link between the boundary and distribution.
- Bertrand Meyer, Object-Oriented Software Construction, 2nd edition (Prentice Hall, 1997) [9] – the original formulation of the invariant in Design by Contract.
- doctrine/orm, issue #3620, “OPTIMISTIC_FORCE_INCREMENT” (opened 2013) [10] – evidence that Doctrine does not increment the root version when a child changes.
- ddd-crew, Aggregate Design Canvas (CC BY 4.0) [11] – a nine-field template for modeling workshops.
- Matthias Noback, Doctrine ORM and DDD aggregates (2018) [12] – the most detailed list of friction points between Doctrine and the aggregate boundary in PHP.
- The book continues with CQRS, Event Sourcing, Sagas and Process Managers, Outbox Pattern, and Case Study, where you will see the workflow applied to a concrete domain.
Frequently asked questions
How large should an aggregate be?
Large enough to contain all the invariants that must hold immediately, and no larger. The default choice is an aggregate with one root object and a few value objects, plus optionally a few inner entities. A larger aggregate needs a concrete justification by an invariant, not ORM convenience. Vernon cites a project by Niclas Hedhman where roughly 70% of the aggregates were only a root with value objects and 30% had two to three entities. Size is estimated with pencil and paper: how many children an instance accumulates over its lifetime. A collection whose growth nothing limits belongs outside the aggregate, or at least on EXTRA_LAZY with filtering in the repository. Details in the Aggregate size and its consequences section.
Why can''t two aggregates be changed in one transaction?
Technically they can, and the default answer is “don't.” The aggregate boundary is both the consistency boundary and the scaling boundary: a lock across aggregates lowers throughput, concurrent transactions breed deadlocks, and the code cannot be split later. The need to commit two aggregates at once is above all a diagnosis. Most likely the boundary is drawn wrong. Vernon does, however, name three situations in which such a violation is defensible (batch creation from the UI, missing messaging, and mandated global transactions), plus a fourth, query performance, for references by identity; the When to break the rule section covers them. Details in the Transactional consistency: one aggregate per transaction section, alternative solutions in the Eventual consistency between aggregates section.
What is eventual consistency and when should it be used?
Eventual consistency means that the state of two aggregates becomes consistent with a delay, not immediately. The domain expert decides how long a delay is acceptable. Vernon points out that experts routinely accept seconds, minutes, hours, and even days. It fits wherever an invariant does not have to hold at every moment, for example “after an order is placed, the customer receives an email” or “when the address changes in the Customer aggregate, the delivery address in orders in progress is updated.” Implementation: aggregate A publishes a domain event, and a saga receives it and changes aggregate B in a separate transaction. Rules that must hold immediately (for example, “the balance of debits and credits is zero”) belong in one aggregate. Details in the Eventual consistency between aggregates section.
How do I map a reference to another aggregate in Doctrine ORM 3?
As a simple column with a custom Doctrine type (order_id, customer_id) that converts between the database value and a value object (OrderId, CustomerId). No ManyToOne association between aggregates. Doctrine associations belong only between entities inside the same aggregate (typically OneToMany from the root to inner entities with cascade: ["persist", "remove"] and orphanRemoval: true). Value objects with several fields (Money, Address) are mapped through #[ORM\Embedded]. Details in the Mapping in Symfony 8 and Doctrine ORM 3 section.
What is a hot aggregate and how do I tell that I have one?
A hot aggregate is an aggregate that many transactions touch concurrently (a shopping cart during Black Friday, a sports score, a real-time game, a like counter on a viral post). The symptom in production: most commands fail with OptimisticLockException, retries take seconds, and latency rises. There is no absolute threshold in transactions per second: the risk of conflict is determined by the product of the write frequency per instance and the time a transaction holds the state. That is why both are measured. Details on the symptoms and the decision logic in the Hot aggregate section.
How do I fix a hot aggregate?
Four strategies, depending on the nature of the domain. Splitting into smaller ones – instead of a Stadium with a thousand seats, there is a Section with dozens; concurrent transactions spread out. Event Sourcing – writes are append-only, and concurrency is guarded by the stream version (see the chapter Event Sourcing). Single-writer pattern – the aggregate lives in the memory of a single process; in Symfony, through Messenger with consistent-hash routing. Eventual consistency inside – for non-critical values (like count), periodic replication is enough. The choice depends on the nature of the invariant; guidance in the Hot aggregate section.
Which identifier should I choose for a new aggregate?
For new Symfony projects, the book recommends UUID v7 (Uuid::v7(), the symfony/uid package). Time-ordered generation improves the I/O pattern in MySQL/InnoDB compared with UUID v4, distributed creation removes the need for a central generator, and the format is standardized in RFC 9562. ULID (Symfony\Component\Uid\Ulid) is an alternative with comparable properties and a shorter notation (26 characters vs. 36). A sequential integer makes sense only with a specific reason (a human-readable order number). The book does not recommend natural keys (email, company registration number). Domains change their “natural keys” more often than it seems. A comparison of all five strategies is in the Strategies for referencing across aggregates section.
How do I quickly check that the aggregate boundary is right?
Three quick checks. (1) Invariant test: is there a rule that would be violated if you split the aggregate in two? (2) Size test: can you calculate an upper bound on the number of children an instance accumulates over its lifetime? (3) Reference test: do you refer outside the aggregate only by ID, not by object reference? If you answer “yes” to all three, the boundary is most likely right. The full 12-point checklist is in the Aggregate design checklist section, and the seven-step design workflow in the Step-by-step design workflow section.