Skip to content

The Aggregate as a Consistency Boundary

An aggregate is neither an ORM entity nor a table but a consistency and transaction boundary: a cluster of objects that an Aggregate Root protects as a unit. Why a transaction changes exactly one aggregate and other aggregates are referenced only by ID.

≈ 12 min readSoftwareArchitecture
@Entity()
class Order {
  @PrimaryGeneratedColumn() id: number;
  @ManyToOne(() => Customer) customer: Customer;
  @OneToMany(() => LineItem, (li) => li.order) lineItems: LineItem[];
  @Column() status: string;
}

This class carries four annotations and not a single rule. Nothing stops code anywhere from calling order.lineItems.push(...) even though status has long been set to 'CONFIRMED'. And through order.customer.updateAddress(...), the same caller changes a second model on the side, in the same transaction. What you see here is an object graph: data classes with getters and setters, connected by foreign keys. And yet exactly this kind of class is regularly called an aggregate.

An aggregate comes into being earlier. It starts with the question of which rules have to hold at the same instant, and only after that does it become classes and tables. If you read the term this way, you make different decisions: about transactions, about references between objects, about the size of your models and about where eventual consistency begins. This continues a line of thought I have pursued elsewhere – that CQRS is a domain boundary and not a framework. The aggregate is the next, smaller boundary in the same conceptual building.

What an aggregate really is#

Martin Fowler puts it concisely: an aggregate is “a cluster of domain objects that can be treated as a single unit”. The classic example is an Order with its LineItems. These are separate objects, but they are never loaded, changed or saved individually. They come out of the repository as a whole and go back as a whole. The aggregate is the basic unit of storage transfer.

Within this cluster there is exactly one distinguished component: the Aggregate Root. It is the only entity that may be referenced from outside. Nobody outside the aggregate ever holds a LineItem directly – you always go through the Order. That sounds like an annoying encapsulation rule, but it has a deep reason: only if all access goes through the root can the root guarantee that the state of the entire aggregate is correct.

And that brings us to the core. Eric Evans, Vaughn Vernon and Fowler all mean the same thing when they talk about the aggregate: it is the consistency boundary. The invariants – the business rules that must always hold – are satisfied after every completed change. Not “eventually”, not “after the next batch run”, but immediately, transactionally. Vernon aptly calls this “must always be transactionally consistent”. An invariant might be: “After confirmation, no more line items may be added.” Or: “The sum of the line items equals the order total.” Such rules don’t belong in a service somewhere further up; they belong in the root itself.

This is the decisive change of perspective: the shape of an aggregate is determined by the invariants that have to be protected together. Which objects belong together in the domain follows from that – not the other way around.

The root protects its invariants#

Let’s look at this in code. The following example is illustrative – I care about the structure, not about a runnable system. What matters is what’s missing: public setters. The lineItems list is private, and the only way to change it is through methods that know the invariants.

type OrderStatus = 'DRAFT' | 'CONFIRMED';

class Order {
  private status: OrderStatus = 'DRAFT';
  private readonly lineItems: LineItem[] = [];

  constructor(
    readonly id: OrderId,
    private readonly customerId: CustomerId,
  ) {}

  addLineItem(product: ProductId, quantity: number): void {
    if (this.status === 'CONFIRMED') {
      throw new Error('Cannot modify a confirmed order');
    }
    if (quantity <= 0) {
      throw new Error('Quantity must be positive');
    }
    this.lineItems.push(new LineItem(product, quantity));
  }

  confirm(): void {
    if (this.lineItems.length === 0) {
      throw new Error('Cannot confirm an order without line items');
    }
    this.status = 'CONFIRMED';
  }
}

Two invariants are expressed here: a confirmed order no longer accepts line items, and an empty order cannot be confirmed. Both are enforced in exactly one place, the root. There is no way to sneak a LineItem into the list past this check – because nobody outside the Order can get at the list. That is exactly what “the root ensures the integrity of the entire aggregate” means. The state can’t become invalid in the first place.

Compare this with the annotated data class from the beginning, whose lineItems and status are wide open. There, any code anywhere can manipulate the list or set the status. The rule “no line items after confirmation” then exists at best as a convention, scattered across the codebase, and will be violated sooner or later. The aggregate moves it to a single place that cannot be bypassed.

One transaction changes exactly one aggregate#

The transaction boundary follows directly from the consistency boundary. Evans and Vernon are clear here: transactions must not cross aggregate boundaries. The rule of thumb is that one transaction changes exactly one aggregate instance. Anything beyond that is not done in the same atomic commit but in separate transactions, connected through eventual consistency.

This rule reliably meets resistance, and the objection always sounds similar: “When an order is confirmed, the stock has to be reserved too – that belongs in one transaction.” It doesn’t. Order and Inventory are two aggregates, each with its own invariants. Forcing them into a shared commit couples them technically, creates lock contention and makes the system harder to scale. Instead, transaction T1 confirms the order and writes an OrderConfirmed event. A separate transaction T2 processes this event and reserves the stock in Inventory.

graph LR
  subgraph T1["Transaction T1"]
    O["Order<br/>confirm()"]
  end
  subgraph T2["Transaction T2"]
    I["Inventory<br/>reserve()"]
  end
  O -- "OrderConfirmed (event)" --> I

Important, to counter a widespread misunderstanding: eventual consistency does not mean “no consistency”. Within an aggregate, everything is strictly and transactionally consistent – after T1, the Order is in a valid state no matter what. Between aggregates it is eventual: a short but finite amount of time passes until Inventory has caught up. Setting this boundary deliberately is a domain decision. The question is always: does this rule have to hold at the same instant, or may it hold a few milliseconds later? Only if the answer is “at the same instant” does the data belong in the same aggregate.

If you want to keep this separation of write intentions and the resulting facts clean, you quickly end up with the question of how to separate commands, events and queries anyway. The event between T1 and T2 is exactly such a fact: something that happened and lets other aggregates react.

Reference other aggregates by identity only#

For the transaction boundary to hold at all, a second rule is needed, and it is the one most often violated: an aggregate references another aggregate only through its identity, its ID, never through a direct object pointer. Vernon states this as a design rule of its own: “Reference Other Aggregates by Identity”.

You can already see this in the Order above. The root holds customerId: CustomerId, not customer: Customer. The difference is no small matter.

// Wrong: the customer is pulled inside the order
class Order {
  private customer: Customer; // pulls another aggregate inside the boundary
}

// Right: only the identity crosses the boundary
class Order {
  private readonly customerId: CustomerId; // reference by identity
}

As soon as Order holds a real Customer object, the boundary blurs. The developer who sees the Customer reference will use it sooner or later – order.customer.updateAddress(...) – and suddenly two aggregates are changed in one transaction. Referencing by ID prevents this structurally: you can’t accidentally mutate a CustomerId. If you really need the customer aggregate, you load it beforehand through its own repository and pass in exactly what’s needed – so the ID reference forces a deliberate decision.

The side effect is valuable too: aggregates stay small. There is no eager loading of entire object graphs, no “loading the order pulls in the customer, which pulls in their addresses, which pull in their countries”. What lies within the boundary gets loaded, and nothing else.

To keep the rules together in one picture, here is the consistency boundary as a diagram. Inside the framed block is the Order aggregate with its root and inner objects; Customer lies outside, as an aggregate of its own, and is connected only through its identity.

graph TB
  ext["Client code"]
  subgraph agg["Aggregate: Order (consistency boundary)"]
    root["Order (Aggregate Root)"]
    li["LineItem"]
    money["Money (Value Object)"]
    root --> li
    li --> money
  end
  cust["Customer<br/>(separate aggregate)"]
  ext -->|"references the root only"| root
  root -. "customerId (by identity)" .-> cust

Note the arrows: external access points exclusively at the root, never at LineItem or Money. And the connection to Customer is dashed and labeled customerId – a reference, not containment.

Keep aggregates small#

This leads to what may be Vernon’s most practical rule: “Design Small Aggregates”. The temptation to let aggregates grow is enormous, and it even has a name – “object graph greed”. Out of convenience, you include everything you’d like to have at hand while navigating. A Customer that holds all its Orders as a list is the standard example. In domain terms that sounds plausible; technically it’s a problem: every change to a single order would have to load and lock the entire customer aggregate including all orders. For a customer with a thousand orders, every small operation becomes expensive, and concurrent accesses block each other.

The heuristic against this is simple: model along real invariants, not along navigation wishes. The question is not “do I want to be able to navigate from A to B” but “does A have to become invalid when B changes, and immediately so”. Only if there is a real, instantaneous consistency rule between two objects do they belong in the same aggregate. For everything else there are references by ID and, if you want to navigate for reading, a read model. The aggregate is a write model; if you’re looking for navigation convenience for display, build a projection for it instead of bloating the aggregate.

Let’s sum up the rules I use to check an aggregate during design:

  • All access from outside goes through the Aggregate Root; inner objects are encapsulated.
  • The root enforces the invariants, transactionally consistent after every change.
  • One transaction changes exactly one aggregate instance; everything else runs through eventual consistency and domain events.
  • Other aggregates are referenced only by their identity, never as an embedded object.
  • Aggregates stay small and are cut along real invariants, not along navigation wishes.

The three pitfalls#

Three confusions come up again and again, and it’s worth naming them.

The first and most common: equating the aggregate with a database table or an ORM entity. That is wrong. The aggregate is a modeling and consistency concept; how it is mapped to tables is an entirely separate question. An aggregate can be persisted across several tables, and one table can contain several value objects. Persistence is orthogonal to the model. A class annotated with @Entity and full of getters and setters is far from being an aggregate – it lacks the crucial part, the enforced invariant.

The second: misunderstanding the Aggregate Root as a “God Object”. Because the root is the only entry point, inexperienced teams tend to put everything into it. That is the opposite of the intent. The root is small and driven by invariants. It holds exactly what it needs to enforce its rules – no more. A root that holds everything is usually a sign that several aggregates have mistakenly been merged into one.

The third: direct object references between aggregates, the mistake from the beginning. It is so insidious because it feels harmless and because ORMs practically invite it – a @ManyToOne relationship is quickly annotated. But every such reference is an invitation to change several aggregates in one transaction and soften the boundary. The discipline is: reference by ID, and if you really need the other aggregate, load it beforehand through its repository – before calling the aggregate method, not in the middle of it.

A brief distinction#

Because people constantly mix up what belongs together in the DDD world and what doesn’t, a brief clarification on the side. CQRS and Event Sourcing are not the same thing, and neither of them is the aggregate. CQRS separates the write model from the read model, command from query. Event Sourcing persists state as a sequence of events instead of a current snapshot. Both can be used independently of each other – you can use either one without the other, as Fowler and Greg Young emphasize. The aggregate, in turn, is a building block that appears in all of these worlds: it is the consistency boundary against which a command is validated and from which events arise. If you keep these terms cleanly apart, you save yourself many fruitless architecture discussions.

And one more subtle but important distinction: the consistency boundary is not the transaction boundary of the database. It’s the other way around. The aggregate defines the logical boundary within which everything has to be consistent – and the database transaction has to respect it. It is not the available transaction mechanisms that determine how models are cut; the domain invariants determine how far a transaction may reach. If you turn this around and align your aggregates with the technical capabilities of the ORM, you have drawn the boundary at the wrong end.

Conclusion#

The aggregate deserves its central place in DDD because it answers one of the hardest questions in software development: where does consistency end and where does coordination begin? It is neither a data container nor a persistence artifact, but a deliberately drawn consistency and transaction boundary with a root that relentlessly enforces its invariants. Almost everything else follows from this one idea: one transaction per aggregate, references between aggregates only through identity, small models along real rules, and eventual consistency wherever instantaneous consistency is neither necessary nor affordable.

So the first question before a domain model is not “which objects belong together” but “which rules have to hold at the same instant”. The answer cuts the aggregates – and with them half the architecture.

Further reading#

  • Slide deck on this topic: https://slides.mikebild.dev/introduction-cqrs-event-sourcing.en.html
  • Martin Fowler: DDD_Aggregate – the compact definition of aggregate and Aggregate Root.
  • Vaughn Vernon: Effective Aggregate Design (2011), parts I–III – the rules “Design Small Aggregates” and “Reference Other Aggregates by Identity”.
  • Eric Evans: Domain-Driven Design (2003), chapter 6 – the primary source for aggregates and Aggregate Roots.
  • Greg Young / Martin Fowler on distinguishing CQRS and Event Sourcing – useful for cleanly separating the aggregate from both.
  • From my own talk material: the deck “CQRS + Event Sourcing” (SlideShare), in which I play through this boundary-drawing with concrete examples.

Revised and translated from German with the help of AI.