Software Architecture

Domain-Driven Design: Aggregates—boundaries for protecting rules and consistency

Design an Order Aggregate with a root that controls its lines and protects shared rules. With TypeScript and executable tests, learn to choose consistency boundaries, avoid partial changes, and distinguish model guarantees from those requiring transactional persistence.

Updated on October 29, 2026

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

An order contains two books and two notebooks. Its total is within the authorized budget. One screen allows a line's quantity to be increased directly; another allows its price to be changed. Each line seems valid on its own, but the order ends up exceeding the budget.

Adding validations to OrderItem is not enough to check a condition that depends on every line. Recalculating the total after saving is not enough either: by then, you may already have accepted a state the business rejects.

An Aggregate lets you define which objects must maintain certain rules together and who controls their modifications. The important decision is not how many classes hang off Order, but which conditions must be preserved as a unit.

Aggregate and Aggregate Root are not the same

An Aggregate is a group of Entities and Value Objects treated as a unit to maintain consistency. Its Aggregate Root is the Entity that controls access to and modifications of the group. Evans presents this boundary and the root's role in the Aggregates section of his DDD reference.

In our example, the Aggregate includes Order, its OrderItem objects, and the monetary values used. Order is the root, not the name of the whole pattern:

Order Aggregate
  Order [Aggregate Root]
    OrderItem: book
      Money: agreed price
    OrderItem: notebook
      Money: agreed price

External references:
  customerId -> Customer
  productId  -> Product

Customer and Product do not automatically become part of the Aggregate because the order mentions them. Nor should a line's agreed price silently change when the catalog changes.

A Module organizes model concepts. An Aggregate establishes a consistency boundary. A Module can contain different Aggregate types; sharing a folder does not imply sharing a transaction.

Invariants are the starting point

An Invariant is a condition that must hold in the model's valid states. It may affect a single object or relate components of the Aggregate.

For this order, we will agree on the following:

  • Every line has a positive integer quantity.
  • Line identifiers and products are not duplicated within the order.
  • The sum of quantities does not exceed ten units.
  • The total amount does not exceed the budget authorized when creating the order.
  • Confirmation requires at least one line and fixes the order's composition.

These are rules chosen for this case. Confirming means accepting that composition, not proving that payment has been collected or stock has been reserved.

OrderItem can check that the quantity is positive. The total units and budget require considering the whole group. The root must coordinate those changes and reject an operation before leaving the state partially modified.

Vaughn Vernon explains why true Invariants should guide boundaries, rather than grouping objects solely for convenient navigation, in Effective Aggregate Design: Modeling a Single Aggregate.

Before: exposing components allows rules to be bypassed

This partial snippet shows a problematic representation; it is not a complete implementation:

type MutableOrder = {
  budgetMinorUnits: number;
  items: { quantity: number; unitPriceMinorUnits: number }[];
};

function changeQuantity(order: MutableOrder, index: number, quantity: number): void {
  order.items[index].quantity = quantity;
}

The function can assign zero, exceed ten units, or break the budget. Even if it validated all those conditions, another consumer could modify the array directly.

The alternative will be to offer order.changeQuantity(itemId, quantity). The root will construct a candidate change, check the whole group, and only then accept it. Consumers will be able to read descriptions of the lines, but will not receive mutable references to internal components.

Complete example: Order controls its OrderItem objects

Scope and execution

The following program is self-contained. Save it as order-aggregate.test.ts and run it with:

node --test order-aggregate.test.ts

It uses Node.js 24.21.0 and its included modules, without external packages. Direct execution removes TypeScript annotations through type stripping, but does not perform static type checking.

Amounts are nonnegative integer minor units of EUR. The minimal Money contains only the necessary operations; it does not introduce conversion, taxes, or rounding. Received prices are considered authorized by the process that builds the order: numeric validation does not prove that they are commercially correct prices.

The example works in memory and includes neither persistence nor reconstruction from stored data. Line identifiers are provided explicitly and only need to be distinct within the order.

import assert from 'node:assert/strict';
import test from 'node:test';

function requireId(value: string): string {
  if (typeof value !== 'string' || !value.trim()) throw new Error('Identificador vacío');
  return value.trim();
}

class Money {
  readonly minorUnits: number;

  private constructor(minorUnits: number) {
    if (!Number.isSafeInteger(minorUnits) || minorUnits < 0) {
      throw new Error('Importe EUR inválido');
    }
    this.minorUnits = minorUnits;
    Object.freeze(this);
  }

  static eur(minorUnits: number): Money { return new Money(minorUnits); }
  add(other: Money): Money { return Money.eur(this.minorUnits + other.minorUnits); }
  times(quantity: number): Money { return Money.eur(this.minorUnits * quantity); }
}

class OrderItem {
  #id: string;
  #productId: string;
  #quantity: number;
  #unitPrice: Money;

  constructor(id: string, productId: string, quantity: number, unitPrice: Money) {
    if (!Number.isSafeInteger(quantity) || quantity <= 0) {
      throw new Error('La cantidad debe ser un entero positivo');
    }
    this.#id = requireId(id);
    this.#productId = requireId(productId);
    this.#quantity = quantity;
    this.#unitPrice = unitPrice;
  }

  get id(): string { return this.#id; }
  get productId(): string { return this.#productId; }
  get quantity(): number { return this.#quantity; }
  total(): Money { return this.#unitPrice.times(this.#quantity); }

  withQuantity(quantity: number): OrderItem {
    return new OrderItem(this.#id, this.#productId, quantity, this.#unitPrice);
  }

  describe() {
    return {
      id: this.#id, productId: this.#productId, quantity: this.#quantity,
      unitPriceMinorUnits: this.#unitPrice.minorUnits,
    };
  }
}

class Order {
  #id: string;
  #customerId: string;
  #budget: Money;
  #status: 'draft' | 'confirmed' = 'draft';
  #items = new Map<string, OrderItem>();

  constructor(id: string, customerId: string, budget: Money) {
    this.#id = requireId(id);
    this.#customerId = requireId(customerId);
    this.#budget = budget;
  }

  addItem(id: string, productId: string, quantity: number, unitPrice: Money): void {
    this.#requireDraft();
    const candidate = new OrderItem(id, productId, quantity, unitPrice);
    if (this.#items.has(candidate.id)) throw new Error('Línea duplicada');
    if ([...this.#items.values()].some(item => item.productId === candidate.productId)) {
      throw new Error('Producto duplicado');
    }
    const next = new Map(this.#items);
    next.set(candidate.id, candidate);
    this.#accept(next);
  }

  changeQuantity(itemId: string, quantity: number): void {
    this.#requireDraft();
    const current = this.#items.get(itemId);
    if (!current) throw new Error('Línea inexistente');
    const next = new Map(this.#items);
    next.set(itemId, current.withQuantity(quantity));
    this.#accept(next);
  }

  removeItem(itemId: string): void {
    this.#requireDraft();
    const next = new Map(this.#items);
    if (!next.delete(itemId)) throw new Error('Línea inexistente');
    this.#accept(next);
  }

  confirm(): void {
    this.#requireDraft();
    if (this.#items.size === 0) throw new Error('Un pedido vacío no puede confirmarse');
    this.#status = 'confirmed';
  }

  #total(items: Map<string, OrderItem>): Money {
    let total = Money.eur(0);
    for (const item of items.values()) total = total.add(item.total());
    return total;
  }

  #accept(next: Map<string, OrderItem>): void {
    const units = [...next.values()].reduce((sum, item) => sum + item.quantity, 0);
    if (units > 10) throw new Error('El pedido supera diez unidades');
    if (this.#total(next).minorUnits > this.#budget.minorUnits) {
      throw new Error('El pedido supera el presupuesto');
    }
    // El estado interno solo cambia después de validar el candidato completo.
    this.#items = next;
  }

  #requireDraft(): void {
    if (this.#status !== 'draft') throw new Error('El pedido ya está confirmado');
  }

  snapshot() {
    return {
      id: this.#id, customerId: this.#customerId, status: this.#status,
      items: [...this.#items.values()].map(item => item.describe()),
      totalMinorUnits: this.#total(this.#items).minorUnits,
    };
  }
}

function exampleOrder(): Order {
  const order = new Order('order-1', 'customer-7', Money.eur(5000));
  order.addItem('line-1', 'book', 2, Money.eur(1200));
  order.addItem('line-2', 'notebook', 2, Money.eur(300));
  return order;
}

test('la raíz rechaza cambios que romperían reglas del conjunto', () => {
  const order = exampleOrder();
  const before = order.snapshot();
  assert.equal(before.totalMinorUnits, 3000);
  assert.throws(() => order.changeQuantity('line-1', 4), /presupuesto/);
  assert.deepEqual(order.snapshot(), before);
  assert.throws(() => order.changeQuantity('line-2', 9), /diez unidades/);
  assert.deepEqual(order.snapshot(), before);
  assert.throws(() => order.changeQuantity('line-1', 0), /entero positivo/);
  assert.deepEqual(order.snapshot(), before);
});

test('no se duplican líneas ni productos y una lectura no modifica el Aggregate', () => {
  const order = exampleOrder();
  assert.throws(() => order.addItem('line-1', 'pen', 1, Money.eur(10)), /Línea duplicada/);
  assert.throws(() => order.addItem('line-3', 'book', 1, Money.eur(1200)), /Producto duplicado/);
  const view = order.snapshot();
  view.items[0].quantity = 100;
  view.items.pop();
  assert.equal(order.snapshot().items.length, 2);
  assert.equal(order.snapshot().totalMinorUnits, 3000);
});

test('confirmar deja fija la composición y eliminar recalcula el total', () => {
  const order = exampleOrder();
  order.removeItem('line-2');
  assert.equal(order.snapshot().totalMinorUnits, 2400);
  order.changeQuantity('line-1', 3);
  assert.equal(order.snapshot().totalMinorUnits, 3600);
  order.confirm();
  assert.equal(order.snapshot().status, 'confirmed');
  assert.throws(() => order.changeQuantity('line-1', 1), /confirmado/);
  assert.throws(() => order.removeItem('line-1'), /confirmado/);
  assert.throws(() => order.addItem('line-3', 'pen', 1, Money.eur(10)), /confirmado/);
});

test('un presupuesto exacto y diez unidades son válidos; confirmar vacío no', () => {
  const order = new Order('order-limit', 'customer-7', Money.eur(1000));
  assert.throws(() => order.confirm(), /vacío/);
  order.addItem('line-1', 'pen', 10, Money.eur(100));
  order.confirm();
  assert.equal(order.snapshot().totalMinorUnits, 1000);
});

What changes between input and result

The input contains two books at EUR 12 and two notebooks at EUR 3: a total of EUR 30. Changing the books to four would raise the total to EUR 54, above the EUR 50 budget.

changeQuantity() does not first change the existing line. It constructs another representation with the same internal identity, places it in a candidate collection, and validates the whole group. Rejection preserves the EUR 30 total and the original quantities.

OrderItem still has a responsibility: it does not accept invalid quantities. Order adds the checks that require several lines and controls when they can be modified. The total is calculated from the contents; there is no other mutable field that can become out of sync.

The four tests were run and passed with Node.js 24.21.0. They check the in-memory model's operations; no static TypeScript analysis was performed and no database adapter was verified.

Reads return new objects with primitive fields. That is why changing a quantity in snapshot() does not change the Aggregate. Merely hiding the array while returning its mutable instances would not have protected that boundary.

A Domain Service could propose a discount allocation or a product selection. The root would still decide whether the change is valid; the service should not modify lines through an alternative entry point.

The object boundary must hold when saving

In memory, we have protected operations, not demonstrated transactional persistence. An Aggregate is not a database transaction simply because it is implemented as a class.

If you save Order and OrderItem in different tables, the relevant changes to the group must commit or be rejected as a unit. You should not save a quantity and leave another necessary piece of data half updated because of a failure.

A Repository, the component that offers retrieval and saving of the Aggregate without exposing storage to the consumer, normally works through the root for these modifications. That does not prohibit specific read queries over lines: reading a projection is not equivalent to modifying a component while bypassing the rules.

Two valid instances can compete

Imagine two processes loading the same order version. One increases the books and the other increases the notebooks. Each instance can accept a valid change separately. If storage combines writes without detecting the conflict, the combined result can exceed the budget.

With Optimistic Concurrency Control, saving is conditional on the stored version still being the one you loaded. The version check and writes to the root and its components must be part of the same local transaction. If the version does not match, reject the save and roll back its changes.

A retry requires loading a consistent state and evaluating the rules again, not blindly repeating an old write. Another strategy may use appropriate locking. Choosing and testing that mechanism belongs to the real persistence design, which the program above does not implement.

Immediate consistency here means that internal Invariants hold at the end of each accepted operation and when committing the transactional unit. It does not mean that every user or system instantly sees the latest version.

How to decide what belongs inside

Ask which elements must be checked together to accept an operation and what separating them would cost. Do not use ORM navigation or table relationships to define the boundary.

In our case, line quantities and prices participate in the order's budget. That justifies controlling the whole group. The customer's complete profile, previous orders, and entire catalog do not need to be included to validate that rule.

Referencing other Aggregates by identity helps avoid navigation paths that end up modifying several groups without recognizing their boundaries. Vernon develops this recommendation and collaboration between Aggregates in Making Aggregates Work Together.

Do not reduce the boundary to an “always one Entity” convention. Separating every order line without resolving how to protect the budget would move the problem rather than eliminate it. Nor should you expand the order to include everything related to a sale.

Education: protecting capacity without including the whole academy

A workshop admits twenty people. If each independent enrollment only checks its own student, none protects “never occupy more than twenty places” by itself.

One option for a small group is an Aggregate of reservations for the workshop offering that controls its places and enrolled identities. Two requests for the last place must compete through that unit's concurrency mechanism.

That does not require including each person's histories, assessments, or certificates. The relationship between that data and the offering does not make it necessary for protecting capacity.

If the collection grows very large or receives too many writes, you may need another capacity allocation model. Splitting enrollments and allowing the counter to update later is not enough if the business requires preventing overselling. This case teaches the distinction between a hard constraint and data that can catch up later.

Logistics: two Aggregates can progress at different times

Orders and shipments often have different lifecycles. Confirming an order's composition does not guarantee that the carrier has already accepted the package. Putting the shipment's entire lifecycle inside the order can increase conflicts and shared responsibilities without protecting a rule that requires it.

You can accept an explicit state such as “awaiting logistics preparation” and durably record the work that must continue afterward. When logistics confirms or rejects preparation, the process updates whatever is appropriate according to the agreed rules.

This uses Eventual Consistency: related changes are coordinated in different steps and converge through a designed process. It does not mean “it will update eventually”: failure handling, repeated attempts, tracking pending operations, and a policy for when the later step cannot complete are required.

If Order and Shipment also belong to different Bounded Contexts, preserve the separation of their implementations. In a design using HTTP ACL integrations, the consumer defines what it needs and the adapter translates the response. HTTP does not share your database transaction.

Using eventual consistency between Aggregates is design guidance, not a law requiring it for every requirement. If two changes need strict atomicity, revisit the boundary or justify transactional coordination that is possible in your environment. Choose the guarantee before the mechanism; do not promise simultaneity that the integration does not provide.

The cost of an oversized Aggregate

An Aggregate containing the whole customer and all their orders forces a huge group to be considered for small changes. It can increase load, memory use, version conflicts, and transaction duration.

A boundary that is too small also has a cost: it scatters rules requiring consistency across the group. The useful measure is the relationship between the Invariants and the elements needed to protect them, not a universal number of classes or records.

An Aggregate can contain a single Entity. An editorial note with a required title may need only its root and a simple validation. Do not add internal components, services, or distributed mechanisms to make it look more complete.

Prompts for guiding and reviewing Aggregates with AI

Proposing boundaries from rules

Analyze these order rules: positive quantities, unique products, a maximum of ten units, and a total within budget. Propose the Aggregate boundary, its root, and which references should be maintained by identity. Do not implement or include complete Customer or Product objects by default. Identify which rules require immediate consistency and what information is missing. A person will validate the real constraints and transactional scope before accepting the design.

Implementing changes without partial states

Implement Order and OrderItem in TypeScript without dependencies. Every modification goes through Order. Changing a quantity must construct and validate a candidate before replacing the state; reads must not expose mutable internal instances. Provide a self-contained program and tests for the budget, exact limits, duplicates, and rejection without partial changes. Do not add persistence. A person will run the tests and review alternative modification paths.

Reviewing the real system's guarantees

Review the attached model and saving adapter. Look for direct writes to internal components, partial changes, version checks separated from writes, and retries that do not reload the Aggregate. Do not modify files or assume shared transactions over HTTP. Return evidence and a concurrent scenario for each finding. A person will validate isolation, concurrency control, and tests against real storage.

AI-generated tests can check each line and forget the rule for the whole group. Always review scenarios where several individually valid components produce a disallowed combination.

Three exercises with reasoned solutions

1. An internal reference escapes

AI proposes getItems(): OrderItem[] and returns a new array with the same internal objects, which now have setQuantity(). Is the new array enough?

Reasoned solution: no. Each element retains a mutable reference to the internal component and allows the root to be bypassed. Return independent descriptions or a truly immutable representation, and keep change operations in Order. Test that modifying a read does not alter the order.

2. A global customer budget

The business requires the sum of all a customer's open orders not to exceed a shared credit limit. Is Order's local rule enough?

Reasoned solution: no. Two orders can respect their local limits and collectively exceed the credit. You need to model who controls and reserves that credit, as well as coordinate its results with orders. Do not automatically add all orders to Customer: examine a capacity or credit unit with its own concurrency guarantee and decide which steps can remain pending.

3. The last place and a duplicate enrollment

Enrollments are separated, and the number of occupied places is updated at the end of every minute. Does that satisfy “never accept more than twenty”?

Reasoned solution: not by itself. A stale projection can report places that no longer exist. Allocation must protect capacity with an appropriate immediate guarantee; the read counter can update afterward. Distinguish the data used to display availability from the decision that actually grants a place.

How to recognize a well-chosen consistency boundary

Identify the rules that must hold together, the participating components, and the root controlling their changes. Then check rejections, reads, persistence, and concurrency: each can open a different path to an invalid state.

A useful Aggregate brings together what is needed to protect those rules and leaves outside what can collaborate through identities and explicit processes. That relationship between boundary, behavior, and transactional guarantee lets you assess the design using evidence, not just the shape of the diagram.

Loading conversation…

Keep learning