Skip to content

State as a Projection

Wouter Naessens edited this page Jun 9, 2026 · 1 revision

State is a Projection

In traditional object-oriented design, an aggregate holds its state as a mutable object that is serialized and persisted. When you load an aggregate, you deserialize that object; when you save it, you serialize it back.

Event sourcing flips this model. The persisted artifact is not the current state — it is the sequence of events that led to the current state. State is never stored directly; it is derived on demand by replaying those events from the beginning of the stream.

This has a subtle but important consequence: there is no single canonical state object for an aggregate. State is a fold over the event stream, and you can fold the same stream in different ways to obtain different projections — each optimized for a specific purpose.

How this works in Aggregates

IState<TState, TEvent> defines a single projection: an initial value and an Apply method that steps the projection forward one event at a time.

ICommand<TState, TEvent> binds a command to exactly one such projection. When the command handler executes, it replays the event stream through that specific IState implementation, then hands the resulting state to the command's ProgressAsync method.

Because the binding is per-command rather than per-aggregate, two commands that target the same aggregate — and therefore write to the same event stream — can use entirely different state representations:

// Only needs to track the current balance
record struct BalanceState(decimal Amount) : IState<BalanceState, AccountEvent> {
    public static BalanceState Initial => new(0m);
    public BalanceState Apply(AccountEvent e) => e switch {
        MoneyDeposited d => this with { Amount = Amount + d.Amount },
        MoneyWithdrawn w => this with { Amount = Amount - w.Amount },
        _                => this
    };
}

// Only needs to know whether the account is open
record struct OpenState(bool IsOpen) : IState<OpenState, AccountEvent> {
    public static OpenState Initial => new(false);
    public OpenState Apply(AccountEvent e) => e switch {
        AccountOpened => this with { IsOpen = true },
        AccountClosed => this with { IsOpen = false },
        _             => this
    };
}

// Uses BalanceState — doesn't care how or when the account was opened
record WithdrawMoney(AggregateIdentifier Id, decimal Amount) : ICommand<BalanceState, AccountEvent> {
    public async IAsyncEnumerable<AccountEvent> ProgressAsync(
        BalanceState state,
        [EnumeratorCancellation] CancellationToken cancellationToken = default) {
        if (state.Amount < Amount) throw new InsufficientFundsException();
        yield return new MoneyWithdrawn(Amount);
    }
}

// Uses OpenState — doesn't care about the balance
record ReopenAccount(AggregateIdentifier Id) : ICommand<OpenState, AccountEvent> {
    public async IAsyncEnumerable<AccountEvent> ProgressAsync(
        OpenState state,
        [EnumeratorCancellation] CancellationToken cancellationToken = default) {
        if (state.IsOpen) throw new AccountAlreadyOpenException();
        yield return new AccountOpened();
    }
}

Both commands target the same aggregate and write to the same event stream. Neither carries state the other doesn't need.

Handling all events

Because all commands on an aggregate share the same event stream, TEvent represents the full set of events that can ever appear in that stream — not just the events relevant to a particular state. Every IState implementation must therefore handle every event type in its Apply method, even the ones it doesn't care about.

The standard pattern for irrelevant events is to return this unchanged, as shown by the catch-all arm in the examples above:

_ => this

Omitting this arm would leave gaps in the pattern match. In practice, this means that when a new event type is added to the aggregate, every existing state implementation must be updated to account for it — even if only to explicitly discard it. This is intentional: the compiler enforces that no event goes unacknowledged.

Why this matters

Keeping state types small and focused has several practical benefits:

  • No accidental coupling. A command that only needs the balance cannot accidentally read or depend on unrelated fields that a different command introduced.
  • Independent evolution. Each state type can change — or be replaced entirely — without affecting any other command. There is no single "aggregate state" shape that must simultaneously satisfy every command.
  • Explicit intent. The ICommand<TState, TEvent> signature documents exactly which view of history a command requires. Its dependencies are visible at a glance, without reading the implementation.

The event stream is the contract. State representations are free to come and go.

Clone this wiki locally