Aggregates and Consistency Boundaries
What you'll learn: How aggregates define transactional boundaries that protect your domain model's consistency and enforce business rules.
What Is an Aggregate?
An aggregate is a cluster of related domain objects (entities and value objects) treated as a single unit for data changes. Think of it as a protective fence around a group of objects that must remain consistent with each other.
The aggregate has one aggregate root—an entity that serves as the gatekeeper. All external access to objects inside the aggregate must go through this root. You never directly modify internal objects from outside.
Why Aggregates Matter
Without clear boundaries, any part of your system could modify any object, leading to violated business rules (invariants) and inconsistent data. For example, imagine an Order aggregate containing OrderLine items. The business rule might be "total price must equal sum of all line items."
If external code could add order lines directly without going through the Order root, it could forget to update the total—breaking consistency. By forcing changes through the aggregate root, you ensure all invariants are checked and maintained.
Transactional Boundaries
Each aggregate represents a transactional boundary. Within a single transaction, you should only modify one aggregate instance. This keeps transactions small, fast, and reduces lock contention.
If you need to update multiple aggregates, use eventual consistency—update one now, trigger the others asynchronously via domain events.
Key Principles
- Small aggregates perform better than large ones
- Protect invariants that must be immediately consistent
- Reference other aggregates by ID, not object reference
- One aggregate per transaction
Key Takeaway: Aggregates are consistency guardians—they bundle objects that must change together atomically, enforce business rules through their root, and define clear transactional boundaries that keep your domain model reliable and predictable.