Catalog My learning Blog
System Design Roadmap: 100-Day Course for Engineers · Phase 5 · Lesson 47 · 5 min read

Event Sourcing Pattern in System Design

On this page
  1. What is event sourcing?
  2. Rebuilding state by replaying events
  3. Optimistic concurrency in an event store
  4. Name events for what happened
  5. Benefits of event sourcing
  6. Drawbacks of event sourcing
  7. Check yourself

What is event sourcing?

In a typical table, an order has a status column, and shipping the order runs UPDATE orders SET status = 'shipped'. The previous value is gone. If someone asks "when was this paid, and was it ever cancelled and reinstated?", you need a separate audit table, if anyone remembered to build one.

Event sourcing turns this around. You never update state. You append events describing what happened: OrderCreated, PaymentCaptured, OrderShipped. The event log is the source of truth. Current state is computed by replaying the events in order.

State is derived by replaying an immutable event log rather than stored as a row that gets overwritten.
State is derived by replaying an immutable event log rather than stored as a row that gets overwritten.

Rebuilding state by replaying events

Current state is a fold: start empty, apply each event in sequence.

Python
# es.py: an order's state is a fold over its events
from dataclasses import dataclass, field

@dataclass
class Order:
    order_id: int
    status: str = "new"
    items: list = field(default_factory=list)
    paid: float = 0.0
    version: int = 0

def apply(order: Order, event: dict) -> Order:
    kind = event["type"]
    if kind == "OrderCreated":
        order.items = event["items"]; order.status = "created"
    elif kind == "PaymentCaptured":
        order.paid += event["amount"]; order.status = "paid"
    elif kind == "OrderShipped":
        order.status = "shipped"
    elif kind == "OrderCancelled":
        order.status = "cancelled"
    order.version += 1
    return order

def load(order_id: int, events: list[dict]) -> Order:
    order = Order(order_id)
    for e in events:                      # in the order they were appended
        order = apply(order, e)
    return order
Code
load(5001, all three events)  -> status='shipped', paid=39.0, version=3
load(5001, first two events)  -> status='paid',    paid=39.0, version=2

The second line is something update-in-place can't do: state as of any point in time, by replaying fewer events.

Optimistic concurrency in an event store

To append, the writer loads the order (version 3), decides the change is valid, and appends the new event only if the stream is still at version 3. If another writer appended first, the append fails and the command is retried with fresh state. Event stores such as KurrentDB (formerly EventStoreDB) and Marten (on PostgreSQL, for .NET) build this check in; with a plain table, a unique constraint on (order_id, version) does it.

Name events for what happened

The most common way event sourcing goes wrong is generic events. A stream of OrderUpdated { status: "cancelled" } is just update-in-place written as a log: it records the new value but not why. OrderCancelledByCustomer and OrderCancelledOutOfStock tell support, analytics and future projections something real. If your events mirror table columns, you've paid for event sourcing without getting the history that justifies it.

Benefits of event sourcing

  • Complete history and audit: every change, when and why, by construction. Valuable in finance, healthcare and anything regulated.
  • Rebuildable read models: projections (tables shaped for queries) can be thrown away and rebuilt from events, including new ones nobody imagined at the start (Day 48).
  • Debugging: replay a stream to see exactly how an entity reached a bad state.

Drawbacks of event sourcing

  • Queries need projections. "All shipped orders over 100 EUR" isn't a SELECT on the event log; you maintain read models fed by events, and they lag slightly.
  • Event schemas live forever. You can't edit old events. Changing shapes means versioned events and code that reads every version, or "upcasting" old ones on load.
  • Long streams get slow to replay. Save a snapshot of state every N events and replay only events after it.
  • Deleting personal data is harder with an immutable log. Common approaches: keep personal data out of events, or encrypt it per person and delete the key.

Use event sourcing where history matters to the business, not as the default for every table.

Check yourself

The events record the new state rather than what happened and why. A generic OrderUpdated loses the business intent, so nobody can tell a customer cancellation from a fraud block. Model specific events, such as OrderCancelledByCustomer or OrderCancelledForFraud, so the log answers business questions directly.

Optimistic concurrency. Each append includes the stream version the writer last saw, such as "expected version 7". The store accepts the first append and moves the stream to version 8, then rejects the second because its expected version is stale. The losing request reloads the events, re-checks its rules and retries.

Take periodic snapshots of the computed state, for example every 1,000 events. Loading then starts from the latest snapshot and replays only the events after it. The full log is still the source of truth, so snapshots can be rebuilt or discarded whenever the projection logic changes.

You can build new read models from history. A projection added today can replay every past event and answer questions the original design never anticipated, such as how long orders spent in each state.

Old events are stored forever and must still be readable. You can't rewrite history freely, so you add new versions of events and upcast old ones when reading, which adds complexity that a mutable database doesn't have.