Video in progress
What are an aggregate and an aggregate root? How do you draw their boundaries?
An aggregate is a group of objects that change together and together protect one set of invariants. It is accessed from outside only through the root. The boundary is drawn by asking "which rules must be immediately correct within a single transaction".
📖 Answer
An example: an Order (the root) and its OrderLines. The invariant: "the order total equals the sum of the lines and doesn't exceed the limit". To protect this rule, the lines must change only through Order:
public class Order {
private final List<OrderLine> lines = new ArrayList<>();
private Money total = Money.ZERO;
public void addLine(ProductId p, int qty, Money price) {
var line = new OrderLine(p, qty, price);
var newTotal = total.plus(line.subtotal());
if (newTotal.greaterThan(LIMIT)) throw new OrderLimitExceeded(id);
lines.add(line);
total = newTotal;
}
}
There is no OrderLineRepository, only OrderRepository.
The boundary rules:
- One transaction, one aggregate. If you need to change two aggregates in one transaction, either the boundary is wrong or you need eventual consistency.
- Refer to another aggregate only by ID. Inside
Order,CustomerId customerId, notCustomer customer. Otherwise lazy loading pulls in the whole DB graph. - Keep it small. If "a customer and all their orders" is one aggregate, every new order locks the whole customer object, and concurrent requests hit optimistic lock errors.
You can tell the boundary is too big in prod when OptimisticLockException on @Version shows up often, or loading a single root pulls in hundreds of rows.
Rules across aggregates (for example "the stock in the warehouse decreased") are carried out in a separate transaction through a domain event.
Sign up to mark studied questions and save your progress.