# Event Sourcing: Store Every Change as an Event and Rebuild State From It

> Instead of overwriting data, Event Sourcing keeps an ordered log of what happened. You learn how replay works, what it costs, and how to design good events.

**In short:** Event Sourcing stores every change as an event in an ordered log instead of overwriting data, and rebuilds the current state by replaying those events.

From "System design", a free course by Venkat R. Murty: https://designervenkat.online/learn/system-design/event-sourcing

## What You Will Learn

Most applications save only the latest version of their data. Event Sourcing takes another route. It saves every change as its own record, and it works out the current picture by reading those records in order. By the end of this lesson you will know what Event Sourcing means, how its events are stored and replayed, what it gives you and what it costs, how to name and correct events, and when a plain database is the better choice.

- **Event:** A record of something that already happened, such as 'Deposited $50'.
- **Append-only:** A store where you can only add new records at the end. You never change or remove old ones.
- **Immutable:** Unable to be changed once written.
- **Event store:** The storage that keeps the events for one thing, in order. Some teams call it an event log.
- **Current state:** The data as it looks right now, such as a bank balance.
- **Replay:** Reading events from the start and applying them one by one to rebuild the state.
- **Snapshot:** A saved copy of the state at one known point, so replay can start from there.
- **CRUD:** Create, Read, Update, Delete. The common style where new values overwrite old ones.
- **Source of truth:** The one place whose data wins when copies disagree.

## What Is the Old Way of Overwriting the Current State?

Most programs use the CRUD style. When a customer changes an address, the program finds the row in a table and overwrites the old address with the new one. The old value is gone. This style is simple and fast for most screens, and most systems should use it for most data.

The trouble starts when someone asks what the data looked like last week, or why it changed. A table that only holds the latest value cannot answer that. Teams then add a separate audit table by hand, and that extra table can drift out of step with the real data. Event Sourcing avoids this problem by making the history the main record.

## Why Are Events the Source of Truth?

In Event Sourcing, the events are the real record. The current state is not the main truth. It is a result that the program works out from the events. If a stored copy of the state ever disagrees with the events, the events are right and the copy must be fixed.

### The Append-Only Event Log

Each change becomes a new event added to the end of the log. Writing is quick, because the system never has to find and rewrite an old row. Old events stay exactly as they were. A helpful picture is a diary written in pen. You can add a new line, but you do not scratch out the old ones.

Each event usually carries more than its name. It also stores a time, a unique ID, and related details, so later readers can understand the change without guessing.

### How Does Replaying Events Find the Current State?

To answer the question 'what is the balance now?', the program reads one account's events from the first one and applies each event in order. Each event nudges a running total. When the last event is applied, the total is the current state.

1. **Start empty:** Begin with a balance of zero, or with whatever value the first event expects.
2. **Apply each event:** Add deposits and subtract withdrawals and fees, one event at a time.
3. **Keep the result:** The total after the final event is the current state. Show it on the screen.

### How Do Snapshots Speed Up Replay?

Replaying a short list of events is instant. Replaying a very long history every time someone opens a screen is slow. A snapshot solves this. It is a saved copy of the state at a known point in the log. The program loads the snapshot, then replays only the events that came after it.

Snapshots are a speed trick, not a second record. If a snapshot is wrong or lost, the program can throw it away and build a new one from the events, because the events remain the truth.

> **Tip:** Take snapshots at set intervals, such as after every fixed number of events. Keep the events forever and treat each snapshot as a disposable copy.

## Worked Example: A Bank Account Screen

Imagine a banking app whose account screen shows one balance. For one account, the app stores three events: 'Deposited $50', 'Withdrew $20' and 'Fee charged $2'. No record holds the number 28. The screen calculates it by replaying the three events in order.

1. **Read the events:** The app loads the account's three events in the order they happened.
2. **Apply the deposit:** Start at zero and add $50. The running total is $50.
3. **Apply the withdrawal:** Subtract $20. The running total is $30.
4. **Apply the fee:** Subtract $2. The running total is $28, and the screen shows $28.

```python
balance = 0
events = [('Deposited', 50), ('Withdrew', 20), ('Fee charged', 2)]
for name, amount in events:
    if name == 'Deposited':
        balance = balance + amount
    else:
        balance = balance - amount
print(balance)
```

Output:

```text
28

```

The same log also gives the statement. Each line of history is an event, so the statement comes straight from the log. If a customer disputes the $2 fee, support staff open that event, check its time and its details, and answer from the record. The app needs no separate audit table, because the events already form the audit trail.

## What Does Event Sourcing Give You?

- **A full audit trail:** Every change is kept with its time and details, so you can see what changed and when.
- **Past states on request:** Replay only the events up to a chosen moment to see the data as it was then.
- **Bug fixes by replay:** After you fix faulty code, you can replay the stored events to rebuild correct state and test the fix against real history.
- **Insight from history:** Teams can study the event list to spot usage trends and slow steps in the process.

## What Event Sourcing Costs

Event Sourcing is not free. Microsoft's guidance warns that it brings significant trade-offs, changes how data is stored and read, and limits later design choices in the parts of a system that use it. It is also costly to move a system onto or off this approach. Use it only when the benefits justify the extra work.

- **Extra complexity:** Developers must learn replay, snapshots and read copies, and manage more moving parts than a single table.
- **Changing event shapes:** The fields of an event may need to change over time. The code must still read older events correctly.
- **Lagging read copies:** Screens that read from a separate copy can briefly show older data after a new event is saved.

### Eventual Consistency in Read Views

Many systems keep a separate, ready-to-read copy of the data for fast screens. That copy is updated by handling new events, which takes a little time. Between the moment an event is saved and the moment the copy catches up, a screen may show the old number. This is the eventual consistency idea from an earlier lesson. Plan the user experience so people understand that the newest change may take a moment to appear.

### Event Schema Versioning

A schema is the agreed shape of an event: its name and fields. Once an event is stored, its shape is fixed forever, but the business may need new fields later. Teams handle this by writing a version number into each event. When the code reads an old event, it converts that event into the current shape first. This small conversion step is sometimes called an upcaster.

> **Tip:** Add a version number to every event from day one. It costs almost nothing and makes later changes far easier.

## Designing Good Events

Good events make the log useful for years. Three habits matter most: name events in the past tense, never edit or delete them, and record the reason for a change as well as the result.

### Name Events in the Past Tense

An event records a fact that has already happened, so its name should be in the past tense. Names such as ItemAdded, MoneyWithdrawn and OrderCanceled read as facts. A name such as AddItem asks for something to happen. That kind of request is a command, and it may be refused. Only accepted facts belong in the log.

### Never Edit or Delete, Correct With New Events

If a mistake reaches the log, do not open the bad event and change it. Add a new event that corrects the result, such as a reversal. The bad event and the correction both stay in the history, so the record shows what went wrong and how it was fixed.

> **Tip:** When you write a correction event, store the ID of the event it corrects and a short reason. Future readers can then follow the chain of fixes.

**Quick check:** A bug charged a $2 fee twice on one account. Which fix keeps the event log honest?

A. Delete one of the two duplicate fee events from the log
B. Change the amount of the first fee event to $0
C. Add a new event that reverses the extra $2, and keep both fee events
D. Rebuild the whole log from scratch with the correct fees

**Answer:** C. A correction is a new event, so the log keeps the original charges and the reversal. Deleting, editing or rebuilding the log would erase the evidence that the bug happened.

### Record Intent, Not Only the Result

Compare two designs for a seat-booking system. One stores an event saying two seats were reserved. The other stores an event saying the number of free seats changed to 42. The first event tells you what a person did. The second tells you only the outcome. Events that capture intent give richer history and let you build new views later from the same facts.

## Replaying to Investigate a Shopping Cart

Suppose a shopping cart service stores only the cart's contents right now. A customer says an item vanished without anyone on their side removing it. The team can see the current cart, but not earlier cart states or the steps that led to the change. If the service stored events instead, every add and removal would have a time, and the team could replay them to check any moment.

To see the cart at 2:00 pm, replay only the events up to 14:00 and stop there. The sample below uses three short events. The result at 14:00 holds both items. Replaying to 15:00 shows that a later removal took the shoes out.

```python
events = [
    ('13:05', 'ItemAdded', 'shoes'),
    ('13:20', 'ItemAdded', 'hat'),
    ('14:30', 'ItemRemoved', 'shoes'),
]

def cart_at(events, cutoff):
    cart = []
    for time, kind, item in events:
        if time > cutoff:
            break
        if kind == 'ItemAdded':
            cart.append(item)
        elif kind == 'ItemRemoved':
            cart.remove(item)
    return cart

print(cart_at(events, '14:00'))
print(cart_at(events, '15:00'))
```

Output:

```text
['shoes', 'hat']
['hat']

```

The log also shows the removal event itself. If the team stored which request or session caused it, they can check whether the customer's own device made the change. Without events, none of this is possible.

**Quick check:** A shopping cart service stores only the current cart contents. A customer says an item was removed without their action. Which change lets you see the cart as it was at 2:00 pm?

A. Read the current cart and trust what it shows
B. Replay the cart's events in order, and stop at the last event before 2:00 pm
C. Restore last night's database backup and read the cart from it
D. Edit the removal event so the item goes back into the cart

**Answer:** B. Replaying the events up to 2:00 pm rebuilds the cart as it was at that time, and it shows each add and removal. A backup gives the wrong time, and editing an event destroys the evidence.

## When to Choose Event Sourcing Over CRUD

Event Sourcing fits parts of a system where history has real value, such as money movements, orders, disputes and audits. It fits poorly where only the latest value matters and nobody will ever ask about the past.

- **Choose event sourcing when:** You must explain past states, keep a legal or financial record, or replay history to test fixes.
- **Choose plain CRUD when:** The data is simple and only its latest value matters, such as a profile picture or a display name.
- **Wait when the team is new to it:** The pattern demands careful design and operations skills. Start small in one area before using it widely.

Event Sourcing is often paired with CQRS, a pattern that separates the code that changes data from the code that reads it. That pairing has its own lesson, so this lesson only introduces it.

> **Tip:** Start with CRUD for the whole system. Add an event log only to the parts where history truly matters.

**Quick check:** A team builds a notes app. Users only ever need the latest text of each note, and no one asks for older versions. Which design fits best?

A. Event Sourcing for every edit to every note
B. A plain CRUD table that overwrites the note text
C. A log of every keystroke, replayed each time a note opens

**Answer:** B. Only the latest text matters here, so overwriting a row is simple and enough. The other designs add complexity that no one needs.

## Key Takeaways

Event Sourcing stores each change as an immutable event in an append-only log. The current state is rebuilt by replaying those events, and snapshots can speed that up without replacing the log. The approach gives you an audit trail and the power to see or rebuild past states, at the price of more complexity, careful event versioning, and read copies that may lag. Name events in the past tense, correct mistakes with new events, and choose the approach only where history matters.

## Sources

- [Event Sourcing pattern, Microsoft Azure Architecture Center](https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing)
- [Minimize coordination, Microsoft Azure Architecture Center](https://learn.microsoft.com/en-us/azure/architecture/guide/design-principles/minimize-coordination)
- [Event Sourcing, AWS Event-Driven Architecture on AWS samples](https://aws-samples.github.io/eda-on-aws/patterns/event-sourcing/)
- [Event Sourcing: Store Events, Rebuild Past State, Loglune](https://loglune.com/blog/event-sourcing)
- [Event Sourcing: Events as the Source of Truth, The HLD Handbook](https://hld.handbook.academy/curriculum/architecture-patterns/event-sourcing/)
- [Event Sourcing: A History Lesson Your Database Actually Wants, Architect View Master](https://www.architectviewmaster.com/blog/event-sourcing-a-history-lesson-your-database-actually-wants/)
- [Event Sourcing in System Design: A Beginner's Guide, Java-HandsOn](https://javahandson.com/event-sourcing-in-system-design/)
- [Event Sourcing Explained: Logs, Projections, Snapshots, Replay, System Design Tutorial](https://systemdesigntutorial.com/m28-event-sourcing.html)
- [Event Sourcing explained: when to use it and how it works, Sandorian](https://sandorian.com/blog/mastering-event-sourcing)
