Skip to content

Event Sourcing: The Event Store as a Logbook

Event Sourcing doesn’t store the current state but the sequence of events as the source of truth: the event store as a logbook, the state as the result of a fold. Benefits, honest costs and how it differs from CQRS.

≈ 11 min readSoftwareArchitecture
UPDATE accounts SET balance = 300 WHERE id = 42;

After this statement, the database says that the account holds 300 euros. The previous value is overwritten, and with it the answer to the question of how the 300 came about: one deposit of 300, or two of 200 plus a withdrawal of 100? The row no longer knows. Every booking eats its predecessor, and the balance field keeps only the result.

Event Sourcing reverses this order. The truth isn’t the current state but the sequence of events that produced it. The event store is a logbook – an append-only log that only ever gets appended to and in which nothing is changed or deleted. The current state is then no longer a stored fact but a derived artifact: you fold the events and get the state out.

Event Sourcing is almost always mentioned in the same breath as CQRS, and that’s exactly where the most stubborn misunderstandings arise. So first the core, then the boundaries – drawn deliberately sharp.

State is a left fold#

Martin Fowler describes Event Sourcing as “Capture all changes to an application state as a sequence of events.” Every state change is recorded as an event, which makes the application state fully derivable from the event log. You can throw away the cached state completely and reconstruct it by replaying all events onto an empty initial state.

Greg Young coined the most didactically elegant formula for this: “Current state is a left fold of previous behaviours.” The state isn’t a table but the result of a fold over the event sequence. In code anyone can read right away:

type Event =
  | { type: "AccountOpened"; owner: string }
  | { type: "MoneyDeposited"; amount: number }
  | { type: "MoneyWithdrawn"; amount: number };

type Account = { owner: string; balance: number };

const apply = (state: Account, event: Event): Account => {
  switch (event.type) {
    case "AccountOpened":
      return { owner: event.owner, balance: 0 };
    case "MoneyDeposited":
      return { ...state, balance: state.balance + event.amount };
    case "MoneyWithdrawn":
      return { ...state, balance: state.balance - event.amount };
  }
};

const fold = (events: Event[]): Account =>
  events.reduce(apply, { owner: "", balance: 0 });

That’s the whole trick, and it’s deliberately little. apply takes a state and an event and returns the next state. fold runs over the stream with reduce and is nothing other than a left fold with apply as the folding function. The code here is illustrative – not a runnable repository, but the idea reduced to its essentials.

A few properties are already in these lines. The events are named in the past tense – AccountOpened, MoneyDeposited. They’re facts that have already happened, and therefore immutable: an event is never changed and never deleted; only a new one is added. And apply has no side effects; it’s a pure function from the old to the new state. That’s no accident but the precondition for replay to work reliably at all.

This all comes down to the same dividing line as in Cleanly Separating Commands, Events and Queries: a command is an intention that may fail; an event is what actually came of it and can no longer fail. Event Sourcing consistently stores the second kind.

The logbook as the source of truth#

If you look at the flow, a simple picture emerges. A command arrives, the aggregate decides and produces one or more events from it, which are appended to the log. The state then comes from folding.

flowchart LR
  C[Command] --> A[Aggregate decides]
  A --> E[New Event]
  E --> L[(Event Store<br/>append-only)]
  L --> F[fold / apply]
  F --> S[Current State]

What matters in this picture is the direction. The command produces an event, the log only grows at the end, and the state hangs at the end of the chain. If the state is lost – cache gone, new service, changed calculation – it can be restored from the log at any time. The log is authoritative; the state is derivable.

This leads to three benefits that make Event Sourcing attractive, and they all hinge on the same property: the log is preserved in full.

  • A complete audit trail comes for free. Not as an after-the-fact protocol, but because the event log is the state. It doesn’t just describe what happened – it is what happened.
  • Temporal queries become possible. Because every earlier state is an intermediate result of the fold, I can ask: what did the account look like on January 3? I simply fold up to the event that was written on that day.
  • Projections can be rebuilt. A read model I don’t have today I can introduce tomorrow by running through the existing events again. History that would long have been overwritten with state-based storage is fully available here.

The third point weighs the most in practice: when writing, nobody has to foresee which views will be needed later.

Projections: read models from the stream#

If the state is derived anyway, then so are any number of views on the same stream. That’s exactly what projections are, and they’re the natural transition to read models as projections: derived models optimized for reading, disposable and rebuildable at any time.

type BalanceView = Record<string, number>;

const project = (events: Event[]): BalanceView =>
  events.reduce((view, event) => {
    switch (event.type) {
      case "AccountOpened":
        return { ...view, [event.owner]: 0 };
      case "MoneyDeposited":
        // update the read model per event
        return view;
      case "MoneyWithdrawn":
        return view;
    }
  }, {} as BalanceView);

project is also a fold, just with a different target model. One fold produces the aggregate for decisions, the other a flat overview for the read side. From the same log you can derive an account overview, a monthly revenue report and fraud detection – three projections, three folds, one stream.

flowchart LR
  L[(Event Store<br/>append-only)] -->|project| A[Read Model A<br/>balances]
  L -->|project| B[Read Model B<br/>monthly report]
  L -->|project| C[Read Model C<br/>fraud signals]

Two things have to be named honestly here. First, these read models are only eventually consistent – they lag behind the write log because the projection runs after the append. If you need immediate consistency between writing and reading, you don’t get it for free here. Second, projections must not trigger any external side effects, and that leads directly to the first serious pitfall.

Replay is not innocent#

Fowler points out a detail that never stands out in demos and gets expensive in production: external systems don’t distinguish between real processing and replay. If I rebuild a read model and run through the events again, a gateway that sent an email or triggered a payment the first time sees no difference. It would send the email again.

That’s why the rule is: apply and project are pure folds without side effects. Everything that has an effect on the outside – emails, payments, notifications – doesn’t belong in the fold but behind gateways that know a replay mode and suppress their effects in it. If you don’t separate this, you build yourself a disaster at the first rebuild.

Snapshots: the memoized fold#

That leaves the question of performance. An account with twenty bookings folds in microseconds. An aggregate with two hundred thousand events no longer does on every access. The answer is called a snapshot, and Greg Young put it so precisely that his wording can hardly be improved: “A snapshot is a memoization of your left fold.”

A snapshot is a stored capture of the fold result at event N. You then keep folding from the snapshot instead of starting at event 0.

type Snapshot = { version: number; state: Account };

const rebuild = (snapshot: Snapshot, newerEvents: Event[]): Account =>
  newerEvents.reduce(apply, snapshot.state);
// snapshot = memorized left fold at version N

The crucial point: a snapshot is purely a performance optimization, not a new source of truth. Because the events are immutable, a snapshot can never become invalid – the past it was folded from doesn’t change, after all. If a snapshot is lost or the folding logic changes, you throw it away and fold again from the start. The log remains authoritative; the snapshot is only a cache of the fold.

The distinction: Event Sourcing is not CQRS#

Event Sourcing and CQRS are almost always mentioned together, and many people think they’re the same thing. They aren’t.

CQRS is a domain boundary – the separation of write model and read model. Event Sourcing is a persistence strategy – events instead of state as what gets stored. These are two different decisions on two different axes. You can run CQRS without Event Sourcing: separate write and read sides, both classically with state tables. And you can run Event Sourcing without strict CQRS, even though the read model projections then suggest the separation almost by themselves.

They’re often combined because Event Sourcing produces read model projections very naturally and CQRS offers exactly the right frame for them. But neither forces the other. If you keep them apart, you make both decisions consciously instead of one in the wake of the other.

And one more distinction that becomes important in distributed systems: Event Sourcing isn’t Event-Driven Architecture. Event Sourcing is storage and source of truth within an aggregate. Pub/sub messaging between services is integration. A domain event that travels over a bus as an integration message isn’t automatically a stored Event Sourcing event. Where the two levels blur, you get systems nobody can see through after a year.

The honest costs#

As attractive as the logbook sounds – Event Sourcing is expensive. The benefit comes with a real price, and both sides belong on the table next to each other.

The benefits are a complete audit trail, temporal queries, projections you can introduce after the fact and good domain semantics through intentional events. The costs are event schema versioning over the entire lifetime, replay performance including snapshot management, the eventual consistency of the read models and higher operational complexity overall.

The biggest cost block is versioning. Events live forever, and a replay still has to be able to read the old event versions from three years ago. If the schema changes – a field is added, a meaning shifts – I need a strategy for upcasting: converting old events to the current form when reading. If you underestimate this, you’ll notice at the first big rebuild that your log contains events in five generations that all still need to be read. You either plan for this effort from the start or you plan for it painfully afterward.

On top of that comes eventual consistency – a permanent companion no ticket can debug away. And snapshots aren’t a free tool: additional infrastructure you have to manage, invalidate and regenerate when the folding logic changes.

Two anti-patterns that destroy the benefit#

I see two mistakes so often that they deserve their own section.

The first is “CRUD in disguise.” If the events are called EntityUpdated or generic FieldChanged, you’ve built in Event Sourcing mechanically but thrown away the actual intent. A MoneyWithdrawn tells you what happened in the domain; a BalanceFieldSetTo only tells you that some setter ran. All the value – intent, audit, semantics – lies in the domain naming. Generic setter events are CRUD with more ceremony and less benefit.

The second is “Event Sourcing everywhere.” It isn’t a default persistence. It pays off where history, audit and temporal questions have real domain value – accounting, trading, anything with regulatory traceability. For a master data CRUD service that only needs the latest state, it’s expensive overhead. The art lies in drawing the line where the context really justifies the logbook, and not pushing it across the whole system out of enthusiasm.

Conclusion#

Event Sourcing shifts a single assumption: the truth isn’t the state but the sequence of events that produced it. The event store becomes a logbook – append-only, immutable, authoritative – and the state falls out as a left fold over this stream. Audit trail, temporal queries and any number of rebuildable projections grow out of it almost by themselves.

The price for this is real: event versioning over years, replay performance with snapshots as a memoized fold, eventual consistency and the discipline to keep side effects out of the folds. And the most important conceptual separation: Event Sourcing is a persistence strategy, CQRS a domain boundary – often together, never forced by each other.

If you weigh this up soberly, you use Event Sourcing where the history pays back the effort, and otherwise keep storing good old state. Exactly this decision – conscious, not driven by fashion – is the real gain.

Further reading#

Revised and translated from German with the help of AI.