Nguyen Le Phong

Event Sourcing for Beginners: Keep the Whole Story

Event Sourcing stores every change as an event and rebuilds state from that history.

A support ticket comes in: "The parcel went to my old address, but I changed it before checkout." You open the orders table. The address column shows the new address. When did it change? Before or after the shipping label was printed? Who changed it, the customer or an agent? The table can't tell you, because every update overwrote the value before it.

Your bank doesn't work like that. Your balance is a number on the screen, but the bank keeps every deposit, withdrawal and fee that produced it. If the number looks wrong, you scroll down and read the list. Event Sourcing asks your software to keep records the way the bank does.

Store what happened, then work out what's true

Martin Fowler's 2005 write-up gives the one-line version: "Capture all changes to an application state as a sequence of events." Instead of one row per order that keeps getting updated, you store each fact as it happens: OrderPlaced, AddressChanged, PaymentReceived, OrderShipped. The log is append-only. You never edit an old event. When something was wrong, you add a new event that corrects it, which Microsoft's pattern guide calls a compensating event.

The current state is whatever you get by applying those events in order. In code, that's a fold:

type OrderEvent =
  | { type: "OrderPlaced"; total: number; address: string }
  | { type: "AddressChanged"; address: string }
  | { type: "PaymentReceived"; amount: number }
  | { type: "OrderShipped" };

type Order = {
  status: "new" | "placed" | "paid" | "shipped";
  total: number;
  paid: number;
  address: string;
};

const empty: Order = { status: "new", total: 0, paid: 0, address: "" };

function apply(order: Order, event: OrderEvent): Order {
  switch (event.type) {
    case "OrderPlaced":
      return { ...order, status: "placed", total: event.total, address: event.address };
    case "AddressChanged":
      return { ...order, address: event.address };
    case "PaymentReceived": {
      const paid = order.paid + event.amount;
      return { ...order, paid, status: paid >= order.total ? "paid" : order.status };
    }
    case "OrderShipped":
      return { ...order, status: "shipped" };
  }
}

const currentState = (history: OrderEvent[]): Order => history.reduce(apply, empty);

That apply function is most of the idea. Microsoft's guide calls the replay "rehydration": load the events for one order, run them through apply, and you have the order as it stands right now. Run only the events up to last Tuesday, and you have the order as it stood last Tuesday. Fowler calls that a temporal query, and you get it without writing a separate history table.

A timeline that only grows to the right, linking four events in order: OrderPlaced, PaymentConfirmed, Packed and Shipped.
The stream only grows. The current state of the order is what you get by reading it from left to right.

Using events and Event Sourcing are different things

This trips up a lot of people. Plenty of systems update a normal table and then publish an OrderShipped message for other services. That's useful, and it isn't Event Sourcing. In What do you mean by "Event-Driven"? Fowler separates four patterns that all get called event-driven: event notification, event-carried state transfer, Event Sourcing and CQRS. The test for Event Sourcing is where the truth lives. In his words, "the event store becomes the principal source of truth, and the system state is purely derived from it."

If the row is the truth and the message is a heads-up, you're doing event notification, and the hard part there is making sure the row and the message never disagree (that's the job of the Outbox pattern). For messaging between services in general, see Event-Driven Architecture, Explained.

What the history buys you

  • An audit trail by default. Every change is a stored event with its time and data, so "who changed this and when?" becomes a lookup. Add the user ID and a reason to each event's metadata and you can answer "why?" too.
  • Time travel. You can rebuild any entity as it was at any point, which helps a lot when you're debugging something that happened three weeks ago.
  • New views from old data. Need a report nobody thought of last year? Write a new projection and replay the history through it. The guide points out that intent-based events give you room to build new read models later without touching the write side.
  • Fewer write conflicts. Appending a new event avoids the read, modify, write cycle and the row locks that come with updating in place. Two writers to the same stream still need a rule, which we'll get to.

Reading every stream from the start each time someone opens a page would be slow, so event-sourced systems keep projections: read models (tables, documents, search indexes) built from the events and shaped for one screen or one query. The support dashboard reads its projection. The events stay the source of truth, and any projection can be dropped and rebuilt from them.

A flow diagram where an event stream passes through a projector and comes out as a read model that can be rebuilt.
A projection is a cache you can throw away. Delete it, replay the events, and you get it back.

This is why Event Sourcing so often shows up with CQRS: commands append events on the write side, and queries read projections on the read side. The two are separate ideas, though. Fowler notes you can use CQRS without any events at all, and our CQRS post covers it on its own. The price of projections is lag. A projection updates a moment after the event lands, so a user can save something and not see it on the next screen right away. Eventual Consistency in the Real World covers how to design around that gap.

Name events the way the business talks

Events stay in your store for years, so their names matter more than the names of most things in code. Microsoft's guide has a neat example from seat booking: an event that says two seats were reserved is worth more than one that says remaining seats changed to 42. The first tells you what happened. The second only tells you the result, and you've lost the reason.

Same with generic names. UserUpdated hides the meaning. EmailChanged, CreditLimitApproved and RefundRequested tell the next reader the story without opening the UI or guessing from column names. A good check: could someone from the business read your event list out loud and nod along?

What it costs

The Azure guide opens with a clear warning: Event Sourcing is "a complex pattern," it's costly to migrate into or out of, and for most systems, traditional data management is enough. Here's where that cost shows up.

  • Changing an event's shape. Events are permanent, so a schema change has to work with every old event still in the store. The usual tools are tolerant readers that ignore unknown fields, a version number on each event, and upcasters that convert old events to the new shape as they're read. Rewriting history in place is the last resort, because it breaks the audit trail. Greg Young wrote a whole book on this one topic, which tells you something.
  • Long streams. An entity with thousands of events gets slow to rehydrate. The standard fix is a snapshot every N events: load the latest snapshot, then replay only what came after. A snapshot is an optimization you can regenerate. The stream stays the source of truth.
  • Two writers, one stream. If two requests load the same order at the same time, both see the same state and both try to append. Event stores handle this with optimistic concurrency: each append says which version it expects, and the store rejects it if the stream moved on. The loser reloads and tries again.
  • Duplicate deliveries. Consumers usually get events "at least once," so a projection will sometimes see the same event twice. Every handler has to be idempotent: track the last event number you processed and skip anything older.
  • Replays with side effects. Rebuilding a projection must not email every customer again or charge their card twice. Fowler's answer from 2005 still works: put external systems behind a gateway that does nothing during a replay.
  • Deleting personal data. An append-only log and the right to be forgotten don't mix well. The guide suggests keeping personal data outside the events and referencing it by ID, or encrypting it per person and deleting the key when you need to erase it (crypto-shredding).
  • Querying. There's no SELECT ... WHERE across raw events. Every question you want to ask needs a projection that answers it.
Three panels: stored events, a projection being rebuilt from them, and side effects such as emails and payments locked while the replay runs.
A replay should rebuild projections and nothing else. Emails, charges and calls to other systems stay switched off.

One more trap: a message broker isn't an event store. The Azure guide calls out Kafka by name. Brokers usually lack per-entity stream reads and optimistic concurrency, so they're great for fanning events out to projections and other services, and a poor place to keep the source of truth.

When it's worth it, and when it isn't

Event Sourcing earns its keep when the history is part of the product:

  • Ledgers, payments and anything money-shaped, where you have to explain how a balance came to be.
  • Bookings, claims, approvals and other workflows where the order of steps matters as much as the result.
  • Domains where people keep asking "why did this change?" and today the honest answer is "we don't know."

It's a poor fit for plain CRUD with no need for history, for MVPs and short-lived projects, for screens that must show a change the instant it happens, for mostly static reference data, and for teams that haven't worked with event-driven systems yet. That list comes straight from the Azure guide's "might not be suitable" section, and it's worth reading in full before a design review.

You also don't have to choose for the whole system. The guide's own tip is to use Event Sourcing where it pays (a payment ledger, an order pipeline) and plain CRUD where it doesn't (user profiles, app settings). If all you need is "who changed what, when," a normal table plus an audit table gets you most of the way for a fraction of the effort.

Try this week

  • Pick one small flow where history matters, like order status or a leave request.
  • Write five to ten event names for it in the past tense, in words the business would use.
  • Write the apply function and rebuild the current state from a hand-written list of events.
  • Build one projection, delete it and rebuild it from the events.
  • Feed the same event in twice and check the projection doesn't change the second time.
  • Add a fake email sender and make sure a replay never calls it.

You'll learn more about versioning and idempotency from that small exercise than from any diagram. Once it clicks, the CQRS post is a good next read.

What did you think?

Frequently asked questions

What is Event Sourcing?
A way to store data where every change is saved as an event in an append-only log, such as OrderPlaced or AddressChanged. The current state is rebuilt by applying those events in order. Old events are never edited; mistakes are fixed by adding a new event that corrects them.
Is Event Sourcing the same as event-driven architecture?
No. Many systems update a normal table and then publish events, which Martin Fowler calls event notification. It's Event Sourcing only when the event store is the main source of truth and the current state is derived from it.
Do I need CQRS to use Event Sourcing?
Not strictly, but they often go together. Rebuilding state from events on every read is slow, so most event-sourced systems keep projections: read models built from the events for specific screens or queries. CQRS can also be used without any events.
How do you change the shape of an event?
Old events stay in the store forever, so new code has to read them. Common approaches are readers that ignore unknown fields, a version number on each event, and upcasters that convert old events to the new shape when they're read. Rewriting stored events is a last resort because it breaks the audit trail.
When should I avoid Event Sourcing?
For simple CRUD with no need for history, MVPs and short-lived projects, screens that must show changes instantly, mostly static reference data, and teams new to event-driven systems. You can also use it for one part of a system, like a payment ledger, and keep plain tables elsewhere.