Skip to content

Aggregate Root

Spicy — senior dev territoryBackend

ELI5 — The Vibe Check

An aggregate root is the boss entity that controls a group of related objects. Want to add an item to an order? You don't talk to OrderItem directly — you go through the Order (the aggregate root). It enforces all the business rules for its cluster of objects.

Real Talk

In domain-driven design, an aggregate root is the entry point entity for a cluster of domain objects (aggregate) that are treated as a single unit for data changes. All modifications to objects within the aggregate must go through the root, which enforces invariants and consistency rules. External objects can only reference the aggregate root, not internal entities.

Show Me The Code

class Order {
  private items: OrderItem[] = [];

  addItem(product: Product, qty: number) {
    if (this.items.length >= 50) throw new Error('Max 50 items');
    if (this.status !== 'draft') throw new Error('Cannot modify shipped order');
    this.items.push(new OrderItem(product, qty));
    this.recalculateTotal();
  }
}

When You'll Hear This

"Order is the aggregate root — all item modifications go through it." / "Never modify entities inside an aggregate directly; always use the root's methods."

Made with passive-aggressive love by manoga.digital. Powered by Claude.