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:
OrderItemis inside the aggregate — never referenced from outside.customer_idreferences another aggregate by ID, not by holding theCustomerobject.- Invariants (
quantity > 0, no add after place, no place if empty) are enforced on the root. - External code interacts only via methods;
itemsis read-only by convention (or wrap in a property returning a tuple).
Four rules for designing aggregates
- Small. Smaller aggregates -> smaller transactions -> less contention.
- One root per aggregate. Internal entities reachable only through the root.
- Reference by ID across aggregates. Holding another aggregate's object reference invites cross-transaction temptation.
- One transaction = one aggregate. Need to update two? Use events for eventual consistency, or reconsider boundaries.
Anti-patterns
- God aggregate.
Customeraggregate containing all theirOrders, everyOrdercontaining allPayments. Loading one customer loads everything. Locks everything. - Cross-aggregate transactions.
with session.begin(): order.cancel(); refund.create(); inventory.restock(). Each is its own aggregate; coordinate via events. - Leaking the internal model.
order.items.append(...)from outside the aggregate. Hide collections behind methods. - Holding object references between aggregates.
Order.customer: Customer. Either cross-tx sneaks in, or you've merged two aggregates.
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.