Aggregate (Root)

Aggregate (and Aggregate Root)

An aggregate is a cluster of entities and value objects treated as a single consistency boundary. The aggregate root is the only entity inside the aggregate that the outside world can reference.

What it's for

A transaction commits or rolls back one aggregate at a time. Whatever invariants you need enforced in the same step must live inside the same aggregate. Whatever is "eventually consistent" lives in different aggregates.

Python shape

@dataclass
class OrderItem:  # value object inside aggregate
    sku: str
    quantity: int
    unit_price: Money


@dataclass
class Order:  # aggregate root
    id: UUID
    customer_id: UUID  # reference to ANOTHER aggregate by ID
    items: list[OrderItem] = field(default_factory=list)
    placed_at: datetime | None = None

    def add_item(self, sku: str, quantity: int, unit_price: Money) -> None:
        if self.placed_at is not None:
            raise OrderAlreadyPlaced()
        if quantity <= 0:
            raise ValueError("quantity must be positive")
        self.items.append(OrderItem(sku, quantity, unit_price))

    def total(self) -> Money:
        return sum(
            (item.unit_price * item.quantity for item in self.items),
            Money(0, "USD"),
        )

    def place(self) -> None:
        if not self.items:
            raise EmptyOrder()
        self.placed_at = datetime.now(timezone.utc)

Four observations:

  1. OrderItem is inside the aggregate — never referenced from outside.
  2. customer_id references another aggregate by ID, not by holding the Customer object.
  3. Invariants (quantity > 0, no add after place, no place if empty) are enforced on the root.
  4. External code interacts only via methods; items is read-only by convention (or wrap in a property returning a tuple).

Four rules for designing aggregates

  1. Small. Smaller aggregates -> smaller transactions -> less contention.
  2. One root per aggregate. Internal entities reachable only through the root.
  3. Reference by ID across aggregates. Holding another aggregate's object reference invites cross-transaction temptation.
  4. One transaction = one aggregate. Need to update two? Use events for eventual consistency, or reconsider boundaries.

Anti-patterns

How big should an aggregate be?

The smallest cluster that lets you enforce the invariants you actually need atomically. Anything optional, eventually-consistent, or independently-evolved belongs in a different aggregate.

The acid test

If you cannot answer "what is the invariant that requires these two entities to be in the same transaction?" — they belong in different aggregates.