0PricingLogin
Node.js Backend Development Bootcamp · Lesson

Aggregates, Commands, and Domain Event Modeling

Design aggregates that validate commands and emit domain events while enforcing consistency boundaries.

Why Aggregates Exist

In Event Sourcing, an aggregate is the unit that owns business rules and the source of truth for state changes. It is not a database table — it is a cluster of objects treated as one for the purpose of consistency.

  • An aggregate has a single root entity that the outside world talks to.
  • Every change goes through the root, so invariants can be enforced in one place.
  • The aggregate is the consistency boundary: everything inside is kept transactionally valid together.

In CQRS terms, the aggregate lives on the write side. It accepts commands, validates them, and emits domain events that describe what happened.

Commands vs Events

Two message types drive an event-sourced system, and confusing them is the most common modeling mistake.

  • A command is an intent: a request to do something that may be rejected. Named imperatively: OpenAccount, WithdrawFunds.
  • A domain event is a fact: something that already happened and cannot be rejected. Named in past tense: AccountOpened, FundsWithdrawn.

The aggregate is the bridge: command in → validate → events out. Events are the only thing that gets persisted; state is derived from them.

// Commands express intent (may be rejected)
const openAccount = { type: 'OpenAccount', accountId: 'a-1', owner: 'Ada' };
const withdraw = { type: 'WithdrawFunds', accountId: 'a-1', amount: 50 };

// Events express facts (already happened)
const accountOpened = { type: 'AccountOpened', accountId: 'a-1', owner: 'Ada' };
const fundsWithdrawn = { type: 'FundsWithdrawn', accountId: 'a-1', amount: 50 };

console.log('command:', withdraw.type);
console.log('event:', fundsWithdrawn.type);

All lessons in this course

  1. Events as the Source of Truth and the Append-Only Log
  2. Aggregates, Commands, and Domain Event Modeling
  3. Building Read Models and Projections
  4. Snapshots, Versioning, and Event Schema Evolution
← Back to Node.js Backend Development Bootcamp