Video in progress
In event sourcing, aggregate state is rebuilt from events. How does this affect OOP design, and what are the traps?
Aggregate methods don't change state directly: they check the rule and create an event, and the state only changes by "applying" the event. The traps: the event schema stays forever, long event streams need snapshots, and it's easy to put a side effect inside apply.
📖 Answer
In a classic aggregate, a method changes a field. In an event-sourced aggregate there are two steps: the decision and the state change.
public final class Account {
private BigDecimal balance = BigDecimal.ZERO;
private final List<Object> pending = new ArrayList<>();
// decision: checks, emits an event
public void withdraw(BigDecimal amount) {
if (balance.compareTo(amount) < 0) throw new InsufficientFundsException();
raise(new MoneyWithdrawn(amount, Instant.now()));
}
// state: changes only here, no checks and no side effects
private void apply(Object e) {
switch (e) {
case MoneyDeposited d -> balance = balance.add(d.amount());
case MoneyWithdrawn w -> balance = balance.subtract(w.amount());
default -> throw new IllegalArgumentException(e.toString());
}
}
private void raise(Object e) { apply(e); pending.add(e); }
public static Account replay(List<Object> history) {
Account a = new Account();
history.forEach(a::apply);
return a;
}
}
Traps:
- Logic inside
apply. Ifapplyvalidates or callsInstant.now(), a replay gives a different result. It must be deterministic and "dumb". - Events are forever. You can't change them. Schema changes go through upcasters: when reading, convert the old
MoneyWithdrawnV1into the new shape. - Long streams. Replaying an account with 50,000 events every time is slow: take a snapshot every N events.
- Fixing a bug. If a wrong event was written, you don't delete it: you write a compensating event.
- Queries. You can't find "accounts with a balance over 1 million" in the event store: you need a projection (CQRS).
When it's worth it: an audit is mandatory (finance), the question "what was the state in the past" matters, and the domain is naturally a sequence of events. For a plain CRUD domain it's far too expensive.
Sign up to mark studied questions and save your progress.