# Event Sourcing in Python: A Visual Guide to Talk Python Episode 548

**Guide**: https://talkpython.fm/guides/548/event-sourcing-design-pattern
**Episode**: [Talk Python to Me #548: Event Sourcing Design Pattern](https://talkpython.fm/episodes/show/548/event-sourcing-design-pattern)
**Featuring**: Chris May (co-founder of PyRVA)
**Published**: December 02, 2026

**TL;DR:** Event sourcing saves every change to your data as an immutable event instead of overwriting a row, so the current state is something you compute, not the only thing you keep. In Python the eventsourcing library is one good way in. The payoffs are reports you can backfill, bugs you can trace to the event that caused them, and code that AI agents seem to work well in. The costs are more storage, new concepts and a team that has to buy in.

What if your database worked more like Git? Instead of a single row that gets overwritten every time something changes, you keep a history of every change and replay it to get to the current state. That's event sourcing, and it's older than it sounds. It grew out of the domain-driven design world of the 2000s.

The appeal is easy to see in a normal web app. Pages get slower the more data and configuration pile up behind them, and an event-sourced design can keep reads fast by building the data each page needs ahead of time. As one practitioner put it, "And so the thought of never having a slow page load again was intoxicating to me." Following the idea for years and finally trying it, his verdict was "it turns out it's a lot easier than I thought."

The core is small. A change becomes an event, such as "item added to cart". Events are appended and never edited. The current state is whatever you get when you apply them in order. Everything else people talk about, from read models to CQRS, is a design pattern layered on top.

This guide follows the topic from the ground up: what a CRUD table loses, what an event store keeps, what the Python library gives you, how to keep reads fast and streams short, how to change events that can't be changed, and why AI coding agents seem to like event-sourced code. It ends with when you shouldn't use it at all.

## What CRUD forgets: the shopping cart problem

![The Hidden Cost of CRUD: Historical Amnesia. CRUD databases optimize for current state. User A adds 5 items, removes 2 and checks out; User B adds 3 items and checks out. Both rows end up nearly identical (Items: 3, Status: Checkout).](https://blobs.talkpython.fm/guides/548/02.webp?cache_id=8974f5a1)

Most applications are CRUD applications: create, read, update, delete. A row holds the current state of something, and when that something changes, you update the row. It's how most developers learn to build with databases, and it works.

A shopping cart shows what it costs. Picture a `carts` table with a column holding the product IDs in each cart. One shopper adds five items, removes two of them and checks out. Another shopper adds three items and checks out. Look at the two rows afterward and they're nearly identical. Both bought the same products, and a marketing team would put both shoppers in the same cohort.

But the shoppers behaved differently. The first hesitated, changed their mind twice and put things back. Which two items were they? Did that shopper come back for them later? The database can't say, because the answer was overwritten the moment the cart changed.

Is that a design flaw? Not really. A CRUD application mutates the database so the data always matches the current state, which optimizes for data integrity. That's a reasonable goal, and plenty of software needs nothing more. The trade is that the database can only tell you what is true now. How you got there is gone for good.

That gap is where event sourcing starts. Instead of keeping the latest version of the cart, it keeps every change that happened to the cart and works out the current state from those.

> "And if you look at the database, you'd have no idea that one of them removed two items from their shopping cart."
>
> Chris May

## What is event sourcing? A database that works like Git

![What If Your Database Worked Like Git? State is derived and every change is an immutable event. CRUD crosses out Items: 5 for Items: 3, while event sourcing keeps a timeline: Cart Created, Item Added, Item Added, Item Removed.](https://blobs.talkpython.fm/guides/548/03.webp?cache_id=ba4f3b29)

Event sourcing is a way of saving data. Where a CRUD application updates a row, an event-sourced application records each change that happens in the system as its own record. The first shopper's cart becomes a series of events: cart created, item added five times, item removed twice, checkout. Nothing is updated in place. A new event is appended each time something happens, and events are never edited afterward.

So where's the current state? You compute it. To find what's in the cart right now, read the cart's events in order and apply each one. In Python that's a fold over a list of small immutable records:

```python
from dataclasses import dataclass
from functools import reduce

@dataclass(frozen=True)
class ItemAdded:
    item: str

@dataclass(frozen=True)
class ItemRemoved:
    item: str

def apply(cart: list[str], event) -> list[str]:
    match event:
        case ItemAdded(item):
            return [*cart, item]
        case ItemRemoved(item):
            return [i for i in cart if i != item]
    return cart

events = [ItemAdded('pen'), ItemAdded('ink'), ItemAdded('pad'), ItemRemoved('ink')]
print(reduce(apply, events, []))      # ['pen', 'pad']
```

That replay is the whole core of the pattern. Read models, CQRS and upcasters are more design patterns layered on top.

Source control is the closest analogy. The database becomes something like an audit log: what you store is the file and then the diff, then the diff, then the diff, and you get back to the file by running the operations. Most developers already trust Git to rebuild any version of a file from its history, and an event store does the same for your data.

Two terms come up constantly. The **event store** is where events live. A **stream** is the sequence of events for one thing, such as one cart. How long a stream gets turns out to matter.

Does "immutable" mean keeping everything forever? No. Events aren't edited, but you decide when old ones go. More on that in [Closing the books](#closing-the-books-how-event-streams-stay-short).

> "Event sourcing, on the other hand, captures every change that happens within the system."
>
> Chris May

**Resources**

- [Martin Fowler: Event Sourcing](https://martinfowler.com/eaaDev/EventSourcing.html)

## Event sourcing vs CRUD: what gets stored, and why document databases fit

![Two Approaches to Persistence. A table compares CRUD and event sourcing. Core action: in-place mutation vs. append-only log. Source of truth: the current snapshot vs. the behavioral history. Data integrity: in-place overwrites vs. an append-only record of events. Storage footprint: minimal (1 row) vs. expansive (N events).](https://blobs.talkpython.fm/guides/548/04.webp?cache_id=132729e1)

A CRUD table holds one row per thing. An event store holds a stream of events per thing. A single stored event is a small envelope around a payload: the stream it belongs to, usually an event version, the type of event, and the details as a blob, serialized as JSON or bytes. KurrentDB, a database built for event sourcing, stores an ID, a type such as an order being placed, and a JSON body. Here is one event in that shape:

```python
import json

event = {
    'stream': 'cart-104',
    'version': 3,
    'type': 'ItemAdded',
    'payload': json.dumps({'item': 'pad', 'price': 4.5}),
}
print(event['type'], json.loads(event['payload'])['item'])  # ItemAdded pad
```

Keeping the payload opaque means one table or collection can hold every kind of event. And if there's no event version in the envelope, you'll probably wish there were one later.

A small envelope around a JSON payload is a document, which makes document databases a natural fit. You can index fields inside the payload, and an event without that field simply doesn't use the index. Cloud Firestore, a document database, works as an event store in practice.

One variation uses MongoDB. Keep one document per cart, put the computed answers (cart value, item count) at the top level and the events in a nested list inside the same document. A single document updates atomically, so the computed values and the event history change together in one operation. It's an idea worth experimenting with rather than a settled pattern, since it centers the model, and that is the part of the tradition now being questioned.

Some background explains why. Event sourcing came out of domain-driven design, where everything revolves around the aggregate (many people call it a model): you draw a boundary around the shopping cart and the events that modify it. The newer movement is to go model-less and focus on the events themselves, because the models developers draw tend to change, and so does the bounded context as the problem shifts. *Architecture Patterns with Python* (the Cosmic Python book) is a Python-flavored introduction to those ideas.

The last row of the table above is real, too. An event store takes more space than one row per thing. How much more, and what to do about it, is covered in [Closing the books](#closing-the-books-how-event-streams-stay-short).

> "What has been a new movement in event sourcing is to essentially be model less, to focus on the events themselves because they are so flexible."
>
> Chris May

**Resources**

- [MongoDB](https://www.mongodb.com)
- [Cloud Firestore](https://firebase.google.com/docs/firestore)
- [Cosmic Python: Architecture Patterns with Python](https://www.cosmicpython.com)

## The eventsourcing library: event sourcing in Python without building it yourself

![No Magic Required: Event Sourcing in Python. Python classes flow into the eventsourcing framework (decorators handle storage and replay) and on to SQLite, Postgres or KurrentDB, with Django ORM and SQLAlchemy integrations. A snippet shows an @event decorated item_added method.](https://blobs.talkpython.fm/guides/548/05.webp?cache_id=9dc89832)

Do you need a framework at all? Many people in the event sourcing world say no: the pattern isn't that complicated, and you can write the code yourself. That's a good way to learn it, but there are many decisions to make, and a hand-rolled store can hide concurrency issues you don't know about yet. The `eventsourcing` package, maintained by John Bywater and contributors, makes those decisions for you and shows one way the pieces can fit together.

You write ordinary Python classes and subclass the library's `Aggregate`. Each method decorated with `@event` turns a call into a recorded event, and `Application` stores them and replays them. Here is the cart again, tested with version 9.5.6:

```python
from eventsourcing.application import Application
from eventsourcing.domain import Aggregate, event

class Cart(Aggregate):
    @event('Created')
    def __init__(self):
        self.items = []

    @event('ItemAdded')
    def add_item(self, item: str):
        self.items.append(item)

    @event('ItemRemoved')
    def remove_item(self, item: str):
        self.items.remove(item)

app = Application()
cart = Cart()
cart.add_item('pen')
cart.add_item('ink')
cart.remove_item('ink')
app.save(cart)
print(app.repository.get(cart.id).items)  # ['pen']
```

`app.save` appends the four pending events (Created, ItemAdded twice, ItemRemoved) to the store. `app.repository.get` loads them back and replays them, which is exactly the fold from earlier, written for you. The result is readable, understandable code.

Out of the box you can store events in SQLite or Postgres, and extension projects add databases designed for event sourcing, such as KurrentDB. Companion packages, `eventsourcing-django` and `eventsourcing-sqlalchemy`, let the events table live in the same database as the rest of a web app. With Django, read models are ordinary Django models: describe the shape you want, apply the migrations, and deploy.

The project has also opted into DeepWiki, an AI chat that knows its source and docs. Asked for an example of using the library, it returns a complete example application with all the code.

> "If you're somebody who wants to grab a framework and run with it, this is an exceptional one to do it with."
>
> Chris May

**Resources**

- [eventsourcing on GitHub](https://github.com/pyeventsourcing/eventsourcing)
- [eventsourcing on PyPI](https://pypi.org/project/eventsourcing)
- [eventsourcing-django](https://pypi.org/project/eventsourcing-django)
- [eventsourcing-sqlalchemy](https://pypi.org/project/eventsourcing-sqlalchemy)

## Isn't event sourcing slow? Read models, CQRS and caching

![The Read Optimization Menu. 1, Raw Event Store: best for short streams. 2, Database Read Model: incremental projections updated as events arrive. 3, In-Memory or Live: push state to Valkey or NATS for live UIs. 4, Zero-Infra Local: Python diskcache, no extra servers.](https://blobs.talkpython.fm/guides/548/07.webp?cache_id=2eee0def)

The first objection to event sourcing is speed. Changing a cart means loading all of its events, rebuilding its state and checking whether the item you want to remove is even there. That sounds like a lot of work for every change, but computers are fast, and for many queries the extra cost is negligible. When a page takes three seconds to load, a missing index is the most likely culprit, and sometimes better caching. Still, there are several ways to make reads quicker, and they stack from least machinery to most.

**The event store itself.** Rebuilding one item's state should take milliseconds, if that. Martin Dilger's book *Understanding Event Sourcing* suggests thinking about optimization once a stream reaches about 2,000 events. That advice comes from the Java world, so the number is probably lower in Python, and streams should be shorter than that anyway.

**Snapshots.** Some libraries can shorten the replay for you. In the `eventsourcing` library, an application lists how often to snapshot each aggregate, and loading then starts from the latest snapshot and replays only the events after it.

```python
from eventsourcing.application import Application
from eventsourcing.domain import Aggregate, event

class Cart(Aggregate):
    @event('Created')
    def __init__(self):
        self.items = []

    @event('ItemAdded')
    def add_item(self, item: str):
        self.items.append(item)

class Shop(Application):
    snapshotting_intervals = {Cart: 50}  # snapshot every 50 events
```

**A read model.** This is the read side of CQRS. Code subscribes to only the events it cares about and incrementally updates a database table, a file cache or a Redis cache each time one arrives. A table holding just the current state does duplicate data, and databases were built to avoid that. Here the events remain the source of truth, so the copy can always be regenerated.

**A cache.** Check the cache first, rebuild from events on a miss, and invalidate when a new event arrives. Valkey is a fork of Redis made just before Redis moved to a source-available license, and the Redis Python library can talk to it as if it were Redis. To avoid another server, diskcache keeps a local file-based cache in a container's volume.

**A live push.** For a busy web UI that changes quickly, push updates to the client. NATS is one option, and plain websockets or server-sent events work too: send the delta whenever something changes.

All of these are viable, depending on the use case. Read models are also disposable. In one app, a user's ideas for a status screen led to cloning the vertical slice behind that view and giving it a new collection. Each time the design changed, the read model was deleted and rebuilt from the events. At go-live the URL pointed to the new version, and the old code and old table were deleted.

> "Getting the current state of any individual item should not take, you know, essentially should take milliseconds if, if that long."
>
> Chris May

**Resources**

- [eventsourcing on GitHub](https://github.com/pyeventsourcing/eventsourcing)
- [Valkey](https://github.com/valkey-io/valkey)
- [Redis](https://redis.io)
- [NATS](https://nats.io)
- [diskcache](https://grantjenks.com/docs/diskcache/)

## Closing the books: how event streams stay short

![Controlling Scale by Closing the Books. Emit periodic summary events at natural boundaries, so future replays start from the summary, not day one. Scissors cut a timeline of 100 events, which drop into Cold Storage, leaving a Summary Event: End of Day Balance.](https://blobs.talkpython.fm/guides/548/08.webp?cache_id=4591b749)

If events are never overwritten, won't the store grow forever? It's a fair worry, and the answer starts with how many events it takes to reach a final state. A cart checkout is no big deal. Using event sourcing as an application log might be a problem. Most models have maybe a dozen events, maybe two dozen, depending on the domain, and the design goal is to keep streams short on purpose.

The practice for that comes from accounting, where it is called closing the books. A store wants its revenue for the whole year, but it doesn't add up every sale since January. Every night it closes, reconciles the registers and records what it made that day. Event sourcing borrows the move: at a natural boundary in the domain, an event summarizes what came before. To get the current state, read the latest summary and add the events after it instead of replaying from day one.

```python
from dataclasses import dataclass

@dataclass(frozen=True)
class Sale:
    amount: int

@dataclass(frozen=True)
class DayClosed:
    total: int  # everything up to and including this day

def revenue(stream: list) -> int:
    total = 0
    for e in reversed(stream):  # walk back to the latest summary
        if isinstance(e, DayClosed):
            return e.total + total
        total += e.amount
    return total
```

Unlike a snapshot, which a library writes for you, this summary is an event in the domain's own language. The history is still there, too. You can start from today and read forward, or keep following the stream back to where it began.

None of this makes the extra storage disappear. The store will take more space, and that is the trade-off. On the upside, storage space is the cheapest commodity around. Old events don't have to stay in the operational database either, because event sourcing lets you choose when to lose data. After 90 days, for example, move events to cold storage or delete them. Many teams send old events straight to cold storage as a just-in-case backup and rarely touch them again.

One app has not deleted a single event yet. Anything older than about a week is kept only for analytics and for understanding how the system behaves, and offloading it is on the to-do list.

> "But ideally, you will keep your events short and they have practices called closing the books where you will use events in your domain to kind of keep it short."
>
> Chris May

## Event versioning: defaults, upcasters and the nuclear option

![Immutability vs. Changing Schemas (Versioning). Defaults, document DB style: handle fallbacks inside domain logic, for minor additive changes. Upcasters: local functions that transform v1 to v2 on read. The Nuclear Option: copy and transform the entire event store into a new database.](https://blobs.talkpython.fm/guides/548/09.webp?cache_id=da2c9c02)

Events never change, but code changes all the time, and sooner or later the two collide. In a relational database the fix is a migration: add a column, split some data out, move it around, and the current state is transformed into the new shape. Event sourcing has no single current state to migrate. It has old events and new events, and they may be incompatible in a real way. There are several strategies, and three come up most.

**Defaults.** This is the document-database way of working. When a change only adds fields to an event, most code never notices. The code that does care about the new attribute falls back to a default when it meets an older event without it. Those fallbacks work best close to the domain logic that needs them, in the vertical slice, rather than in one global place.

**Upcasters.** When two versions are truly different, say an item-added event and a second version of it with completely different fields, write code that converts the old version into the new one. It belongs wherever state is rebuilt, because that loop already looks at each event. If a cache is fed from events, the code feeding it knows both versions and the format the cache needs, so it upcasts old events and converts new ones on the way in. The change stays local to the one process that needs it.

The `eventsourcing` library builds this in. An event class carries a `class_version`, and a static method named for the versions it bridges receives the stored state of an old event. Here a second version adds a quantity that version one never had.

```python
from eventsourcing.application import Application
from eventsourcing.domain import Aggregate, event

class Cart(Aggregate):
    @event('Created')
    def __init__(self):
        self.items = []

    class ItemAdded(Aggregate.Event):
        sku: str
        qty: int
        class_version = 2

        @staticmethod
        def upcast_v1_v2(state):
            state['qty'] = 1  # v1 events had no quantity

        def apply(self, aggregate):
            aggregate.items.append((self.sku, self.qty))

    def add_item(self, sku: str, qty: int):
        self.trigger_event(self.ItemAdded, sku=sku, qty=qty)

app = Application()
cart = Cart()
cart.add_item('pen', 2)
app.save(cart)
print(app.repository.get(cart.id).items)  # [('pen', 2)]
```

**The nuclear option.** Transform the whole event store: create a new store and copy every event across, mapping each one to the new version as it goes.

Which to pick depends on how the events are read. If people run a lot of direct SQL and data science against the events, transform the store. If the data mostly comes out through an API, let the code upgrade events as it reads them. Greg Young, who popularized event sourcing in the 2000s, wrote a book on event versioning that lists out the strategies, when to use each and why.

Accidental versions happen too. A renamed attribute on an event that was already published to production produced two versions of the same event, and a view started throwing errors. The fix was small: if this attribute doesn't exist, look for that one. Because the events were all still there, nothing was lost.

> "You have so many strategies. You just have to choose which one works for your situation."
>
> Chris May

**Resources**

- [eventsourcing on GitHub](https://github.com/pyeventsourcing/eventsourcing)
- [Greg Young on event versioning (Leanpub)](https://leanpub.com/esversioning)

## Querying the past: analytics, debugging and audit trails

![Surprise Win 1: Time Travel and Instant Analytics. The Backfill Superpower: syncing to BigQuery gives months of history on day 1, and a 30-day report went live with 30 days of history. Audit trails: the events are the source of truth. Debugging: find the event that made a row null.](https://blobs.talkpython.fm/guides/548/10.webp?cache_id=ebef3165)

A CRUD table mostly answers questions about now. An event store keeps what happened and when, including the additions and removals a thing went through on its way to its final state. That means questions nobody planned for can still be answered: not just the customers from California who bought this month, but the Californians who abandoned a cart and then came back. You don't know in advance which questions you'll want to ask, and data that was never stored can't answer them. With events, "what if we ask this over time instead of by region?" is a slightly different query instead of a dead end.

The mechanism is a projection: a function that replays events to build whatever view you need. Stop the replay at a date and the view is the state as of that date.

```python
from dataclasses import dataclass
from datetime import date

@dataclass(frozen=True)
class Event:
    day: date
    kind: str  # 'added' or 'removed'
    sku: str

def cart_as_of(events: list[Event], when: date) -> set[str]:
    items: set[str] = set()
    for e in events:
        if e.day > when:
            break  # events are stored in order
        items.add(e.sku) if e.kind == 'added' else items.discard(e.sku)
    return items
```

A data scientist who wants a pandas DataFrame of average cart size may not want to compute it from raw events every time. The answer is to have it both ways: a script that runs every day or every few hours transforms the raw events into whatever shape analysts want. Many BI systems already work like this, running against a warehouse or data lake rather than the operational database.

That pays off fast. In one production service, another service's BigQuery table needed the service's data. A daily export went live, and three days later the team found months of history in the table instead of three days, because every event since the first one was still in the store. A later request for a table of the last 30 days on a reports page went live with 30 days of history on day one.

Debugging gets the same benefit. When a field turns up null and nobody can say how, an event store lets you find the event that made it null, rather than just the end state. An AI assistant can also be asked to query the logs and the event store together to explain a production bug.

Audit trails matter for frameworks such as PCI, HIPAA and GDPR. An event store isn't a certification, but it makes the audit trail the primary record instead of a side table. Teams often build history tables to do the same job, and those can quietly drift. A new developer may not learn the table exists for two or three months, so their changes never reach it, and replaying a history table often doesn't reproduce the current data. A history table that has never been replayed is like a backup strategy that has never been tested. With event sourcing the events are the source of truth, and everything else is generated from them.

> "And to be able to answer those questions with precision is intoxicating."
>
> Chris May

**Resources**

- [Google BigQuery](https://cloud.google.com/bigquery)

## Why event sourcing seems to suit AI coding agents

![Surprise Win 2: Event Sourcing and AI Coding. Small vertical slices fit in a context window. A tangled Spaghetti CRUD Context of 100s of files overflows an LLM context window, while a Vertical Slice Context holds just Command, Event and Read Model.](https://blobs.talkpython.fm/guides/548/11.webp?cache_id=41464546)

A coding agent can only keep so much code in view at once - that limit is its context window. The bigger and more tangled the codebase, the more the agent has to read before it understands what a change touches. So the question for any architecture is how little code a single change needs the agent to load.

Event sourcing is usually paired with vertical slice architecture, which organizes code by feature rather than by technical layer. A slice holds only the code responsible for one feature, so it fits comfortably in a context window. Instead of scanning a hundred files, the agent looks at about five.

There's a second advantage. Event sourcing is a well-known pattern, and the agent already knows it: it knows it's subscribing to events, these are the events, and here's where they live. It doesn't have to rediscover how the application keeps its state.

Chris May's production app gives a firsthand comparison. It's three services in one monorepo, he's responsible for the event-sourced one, and he's required to use Claude Code. When he describes a change to his own service, the agent generally does a really great job. In the other two services it takes a lot more context for the agent to understand the state of the code, and he has to work harder to get what he needs. That's one developer's experience in one codebase, not a controlled test.

It's also a mixed picture overall. That company has a mandate to use AI to write every piece of code, and the results swing between being much more productive and AI-written code that has brought down production. Is a mandate like that the wrong call? Maybe not - it might even be the right one. But it only works if AI coding is treated as a skill you learn, not "just throw stuff at the chat bot" and call that the job. People who treat the two as the same thing tend to decide it doesn't work, and then they get frustrated.

> "And I think a lot of this has to do with the vertical slice architecture because vertical slices only hold code that is responsible for one feature. And so that really fits very nice into a context window."
>
> Chris May

**Resources**

- [Claude Code](https://www.claude.com/product/claude-code)

## Event modeling diagrams, and working with AI like an overconfident intern

![Event Modeling and AI. Treat AI as an overconfident intern; isolate features with Git worktrees (max 2-3) and track work as GitHub issues via the GitHub CLI. A timeline runs Plan, Model, Code: Client Planning Session, AI Generates Event Modeling Diagram, AI Generates Code.](https://blobs.talkpython.fm/guides/548/12.webp?cache_id=bf9ffb72)

Event modeling is a documentation technique: a diagram, drawn on a timeline, that shows how information moves through an application. It uses a deliberately reduced visual language of just a few elements, yet you can follow an application's whole life cycle from one diagram. That makes it a good way to keep a team current on what does what, which matters most when a team is moving to an event-driven design.

It's one of four ideas that tend to travel together: event sourcing as the base, vertical slice architecture, CQRS (read models kept ready and optimized for whoever reads them), and event modeling diagrams. Learning them is harder than it should be, because event sourcing grew out of the domain-driven design community and brings a lot of jargon with it. Martin Dilger wrote the ebook *Understanding Event Sourcing* to fill that gap, in about two months by one recollection, and he and Adam Dymitruk arrived at this combination independently.

AI turns out to understand event modeling diagrams. In their research spikes, they started from a recorded conversation with a client, generated a transcript, generated a diagram from it, and generated code from the diagram. It didn't solve everything, but the recollection is that it got 80 or 85% of the way there, in hours, which would turn months of work into weeks. Treat that as a recollection of research, not a benchmark.

Day to day, the working pattern is to keep the agent on a short leash. One way to put it is an overconfident intern: very smart, very confident, and in need of guidance. Two habits help.

**Git worktrees.** A worktree is a second checkout of the same repository, so each feature gets its own isolated directory and the agent can work there without touching the main one. One developer's limit is two or three at a time; any more and the human starts losing context.

**Plans as GitHub issues.** Run a planning session first, then have the agent write the plan up as a GitHub issue instead of executing it. With the GitHub CLI installed, the next session can start with "let's work on issue 127" and end with a retrospective comment on the issue and a pull request that closes it.

```bash
git worktree add ../myapp-new-slice -b new-slice
gh issue create --title "Plan: new slice" --body-file plan.md
```

> "But it's an engineering skill. It is not just, let's fire it up and ask for it."
>
> Michael Kennedy

**Resources**

- [Event Modeling](https://eventmodeling.org)
- [git worktree documentation](https://git-scm.com/docs/git-worktree)
- [GitHub CLI](https://cli.github.com)

## When to use event sourcing, and when not to

![The Adoption Diagnostic: When to Use It. Do use: your table requires a status column; you are ever concerned about losing data. Don't use: pure forms over data (a contact form); lack of team buy-in.](https://blobs.talkpython.fm/guides/548/13.webp?cache_id=d9aefef9)

Most developers are comfortable building without event sourcing, so the useful question is the reverse one: when is it worth it? The best advice heard over the last decade comes down to two rules of thumb.

**Your table has a status column.** A status column means one item can be in several different states, and each state behaves differently in some way. At that point you're not really doing create, read, update, delete anymore, and event sourcing is a good option.

**You're ever concerned about losing data.** By default event sourcing loses nothing, and it lets you choose when to let data go, rather than losing a little every time a row is updated.

When is it the wrong tool? Applications that are truly CRUD, the kind often called forms over data. Picture a web page that almost exactly mirrors the database table it saves to, maybe a contact form. The UI is just an easy way to get data into the database, there's no status field, and there are no rules about how things behave in different states.

The costs are real elsewhere too. It takes more space than overwriting rows. The domain-driven design jargon takes some getting through. And it only pays off when the team wants it. A team where some people won't buy in works around the pattern, and that's like a CI pipeline that some people refuse to run: it stops helping and starts getting in the way. One suggestion for a skeptical team is to build a single feature the event-sourced way so they can see the benefits.

It also isn't all or nothing. Chris May's event-sourced application has one model that is plain CRUD. That's what a properly factored data access layer buys you: the rest of the app sees an opaque layer of actions, and some of those actions can be driven by events while others are straight CRUD.

Gradual adoption goes further. One practitioner works with companies whose database schema is holding them back so badly they struggle to ship new features. He teaches them event sourcing, then uses the event store to publish both the dream schema they wish they had and the old one, side by side. Once the new features are done, traffic moves over to the event-sourced version slowly, and the old schema can eventually be deleted. Most of the teams he's worked with have stayed with the event-sourced version.

> "Adopting event sourcing doesn't mean you have to do it for everything. You can use it for even just a small bit of your project, especially if you want to try it out and see how it could be."
>
> Chris May

## Getting started with event sourcing

Where do you start if this sounds worth a try? Start small: pick one part of an application, ideally something with a status column or a history you wish you'd kept, and try event sourcing there while the rest stays CRUD.

For the ideas, there's a free ebook introducing event sourcing, written for someone who has heard about these ideas, is curious, and just needs more information. It's a first version that's still being improved, and it lives at Everyday Superpowers, along with a Discord you can join from the site.

For code, the eventsourcing library is a good next step once the ideas click. You write Python classes, and the library handles storage and replay. It's maintained by John Bywater, supports SQLite and Postgres among other stores, and has companion packages, eventsourcing-django and eventsourcing-sqlalchemy, for putting the event store next to your existing models. Trying it takes one line:

```bash
uv run --with eventsourcing python -c "import eventsourcing"
```

For ongoing learning, the Event Modeling and Event Sourcing Podcast covers patterns nearly every week. The name is a bit verbose. And if you're near Richmond, Virginia, PyRVA, the Python user group, meets once a month.

If you want to build the foundations first, Talk Python Training has courses that line up with this topic. [MongoDB with Async Python](https://training.talkpython.fm/courses/mongodb-with-async-python-beanie-and-pydantic?utm_source=talkpythondeepdive) covers the document database side, where event payloads fit naturally. [Django: Getting Started](https://training.talkpython.fm/courses/getting-started-with-django?utm_source=talkpythondeepdive) and [Building Data-Driven Web Apps with Flask and SQLAlchemy](https://training.talkpython.fm/courses/python-flask-sqlalchemy-web-apps?utm_source=talkpythondeepdive) pair with the eventsourcing-django and eventsourcing-sqlalchemy packages. [Async Techniques and Examples in Python](https://training.talkpython.fm/courses/python-concurrency-deep-dive?utm_source=talkpythondeepdive) helps when you start pushing events to live UIs, [Getting started with pytest](https://training.talkpython.fm/courses/getting-started-with-testing-in-python-using-pytest?utm_source=talkpythondeepdive) helps you test event-driven code, and [Up and Running with Git](https://training.talkpython.fm/courses/up-and-running-with-git-a-pragmatic-ui-based-introduction?utm_source=talkpythondeepdive) is a good base for the worktree workflow. If Python itself is new to you, start with [Python for Absolute Beginners](https://training.talkpython.fm/courses/python-for-absolute-beginners?utm_source=talkpythondeepdive).

> "It is just unlocking so much joy again and so much flexibility as I've said before that I cannot imagine having to go back."
>
> Chris May

**Resources**

- [Everyday Superpowers (Chris May)](https://everydaysuperpowers.dev)
- [eventsourcing on GitHub](https://github.com/pyeventsourcing/eventsourcing)

---

Listen to the full episode: https://talkpython.fm/episodes/show/548/event-sourcing-design-pattern
Episode show notes as Markdown: https://talkpython.fm/episodes/show/548/event-sourcing-design-pattern.md
