Event Sourcing in Depth: Expected Versions, Projections, Snapshots and Upcasting, in C# and Python
November 11, 2025 · 36 min read
Software Architecture, Design Patterns, Distributed Systems, Event Sourcing, CQRS, C#, Python
Earlier this year I wrote a five-part series on event sourcing and sagas. Part 1 asked whether you need event sourcing at all, and Part 2 built one on Azure with Cosmos DB, Functions and Service Bus. Both were C# and Azure all the way down.
This post goes underneath them. It's about the mechanics that stay the same whatever you run on: what an event store has to promise, how an aggregate rebuilds itself, how two writers are stopped from corrupting each other, how read models stay correct when a process crashes halfway, and how you change an event's shape five years in without touching history. Each mechanism has a C# version and a Python version, and both run.
| Section | The question it answers |
|---|---|
| Events vs state | What do you store, and what do you derive? |
| The event store contract | What must the database promise? |
| Folding and optimistic concurrency | How is state rebuilt, and how are lost updates stopped? |
| Projections | How do read models stay correct through crashes and rebuilds? |
| Snapshots | What do you do when a stream gets long? |
| Schema evolution | How do events change without editing history? |
| GDPR and crypto-shredding | How do you forget someone in an append-only log? |
| CQRS, engines and when not to | How does this fit a real system? |
How to run the code. C# snippets are .NET 10 file-based apps: save as store.cs and run dotnet run store.cs. The ones that use SQLite pull in Microsoft.Data.Sqlite with a #:package line at the top. Python snippets use only the standard library and run with python3 (3.12). Every output block below is pasted from a real run.
Events vs state
A normal table stores the latest state: account 42 has a balance of 20. Event sourcing stores the facts that led there: the account was opened, 100 was deposited, 80 was withdrawn. The balance is something you compute.
That one shift has consequences that are easy to state and take a while to absorb:
- Events are facts in the past tense.
Withdrawn, notWithdraw. A command is a request that can be refused. An event already happened, so it can't be refused, only reacted to. - The log is the source of truth. Any table you query is derived and can be thrown away and rebuilt.
- History is append-only. You never update or delete an event to fix a mistake. You append a correcting event, the same way an accountant posts a reversing entry.
- State is a function of events. Same events in, same state out. That's what makes replay, debugging by replay, and new read models over old data possible.
The event store contract
Strip away the products and an event store makes three promises:
- Append to a stream, with an expected version. "Add these events to
account-42, but only if it's currently at version 2." If someone else got there first, the append fails and nothing is written. - Read a stream in order. All events for one aggregate, oldest first, optionally from a version.
- Read everything in a global order. All events across all streams, with a position you can resume from. This is what projections and subscriptions consume.
Version and position are different numbers. A stream's version counts events inside that one stream (1, 2, 3). The global position orders events across the whole store. Projections checkpoint on position. Concurrency checks use version.
Real stores spell these the same way. KurrentDB (the new name for EventStoreDB) appends with an expected revision, or with states like "no stream" and "any", and exposes the $all stream for global reads. Marten appends to streams in PostgreSQL with an optional expected version. Cosmos DB has no built-in expected-version append, so Part 2 used a transactional batch on the stream's partition plus a unique id per version to get the same effect.
Folding events into state, and a concurrency conflict
Rebuilding an aggregate is a left fold: start from an empty state and apply each event in order. Two rules keep it honest. First, apply never checks business rules and never fails. The event already happened, so arguing with it is pointless. Second, commands check rules against the folded state and return new events. They don't save anything. The handler saves them, with the version it loaded as the expected version.
The demo below shows why that expected version matters. Two requests load the same account at version 2 with a balance of 100. Both want to withdraw 80. Each check passes on its own copy. Without a version check, both appends would succeed and the account would end at minus 60. With it, the second append is rejected, the handler reloads, re-runs the command against the new state, and the business rule refuses it.
import json
import sqlite3
class ConcurrencyError(Exception):
pass
class EventStore:
"""The whole contract: append with an expected version, read a stream, read everything in order."""
def __init__(self):
self.db = sqlite3.connect(":memory:", isolation_level=None)
self.db.execute("""
CREATE TABLE events (
position INTEGER PRIMARY KEY AUTOINCREMENT, -- global order, for projections
stream_id TEXT NOT NULL,
version INTEGER NOT NULL, -- order inside one stream
type TEXT NOT NULL,
data TEXT NOT NULL,
UNIQUE (stream_id, version))""")
def append(self, stream_id, expected_version, events):
self.db.execute("BEGIN IMMEDIATE")
try:
actual = self.db.execute(
"SELECT COALESCE(MAX(version), 0) FROM events WHERE stream_id = ?", (stream_id,)
).fetchone()[0]
if actual != expected_version:
raise ConcurrencyError(f"{stream_id}: expected v{expected_version}, but stream is at v{actual}")
for i, (event_type, data) in enumerate(events, start=1):
self.db.execute(
"INSERT INTO events (stream_id, version, type, data) VALUES (?, ?, ?, ?)",
(stream_id, expected_version + i, event_type, json.dumps(data)))
self.db.execute("COMMIT")
except sqlite3.IntegrityError as e: # the UNIQUE index is the real guard under races
self.db.execute("ROLLBACK")
raise ConcurrencyError(f"{stream_id}: version taken ({e})")
except BaseException:
self.db.execute("ROLLBACK")
raise
return expected_version + len(events)
def read_stream(self, stream_id, from_version=0):
rows = self.db.execute(
"SELECT version, type, data FROM events WHERE stream_id = ? AND version > ? ORDER BY version",
(stream_id, from_version))
return [(v, t, json.loads(d)) for v, t, d in rows]
class Account:
"""State is a left fold over the events. apply() never fails and never checks rules."""
def __init__(self):
self.version, self.balance, self.is_open = 0, 0, False
def apply(self, event_type, data):
if event_type == "AccountOpened":
self.is_open = True
elif event_type == "Deposited":
self.balance += data["amount"]
elif event_type == "Withdrawn":
self.balance -= data["amount"]
self.version += 1
return self
@staticmethod
def load(store, stream_id):
account = Account()
for _, event_type, data in store.read_stream(stream_id):
account.apply(event_type, data)
return account
# Commands check rules against the folded state, then return new events. They don't save anything.
def withdraw(self, amount):
if amount > self.balance:
raise ValueError(f"insufficient funds: balance {self.balance}, asked {amount}")
return [("Withdrawn", {"amount": amount})]
store = EventStore()
store.append("account-42", 0, [("AccountOpened", {"owner": "Ada"}), ("Deposited", {"amount": 100})])
# Two requests load the same account at the same time.
a = Account.load(store, "account-42")
b = Account.load(store, "account-42")
print(f"A and B both loaded v{a.version}, balance {a.balance}")
store.append("account-42", a.version, a.withdraw(80))
print("A withdrew 80 -> stream now at v3")
try:
store.append("account-42", b.version, b.withdraw(80)) # B still thinks balance is 100
except ConcurrencyError as e:
print(f"B rejected: {e}")
b = Account.load(store, "account-42") # reload and re-run the command
try:
store.append("account-42", b.version, b.withdraw(80))
except ValueError as e:
print(f"B retried on v{b.version}: {e}")
for version, event_type, data in store.read_stream("account-42"):
print(f" v{version} {event_type} {data}")
print(f"final balance: {Account.load(store, 'account-42').balance}")
A and B both loaded v2, balance 100
A withdrew 80 -> stream now at v3
B rejected: account-42: expected v2, but stream is at v3
B retried on v3: insufficient funds: balance 20, asked 80
v1 AccountOpened {'owner': 'Ada'}
v2 Deposited {'amount': 100}
v3 Withdrawn {'amount': 80}
final balance: 20
The same store in C#, on SQLite through Microsoft.Data.Sqlite:
#:package Microsoft.Data.Sqlite@10.0.13
using System.Text.Json;
using Microsoft.Data.Sqlite;
var store = new EventStore();
store.Append("account-42", 0, [new("AccountOpened", """{"owner":"Ada"}"""), new("Deposited", """{"amount":100}""")]);
// Two requests load the same account at the same time.
var a = Account.Load(store, "account-42");
var b = Account.Load(store, "account-42");
Console.WriteLine($"A and B both loaded v{a.Version}, balance {a.Balance}");
store.Append("account-42", a.Version, a.Withdraw(80));
Console.WriteLine("A withdrew 80 -> stream now at v3");
try
{
store.Append("account-42", b.Version, b.Withdraw(80)); // B still thinks balance is 100
}
catch (ConcurrencyException e)
{
Console.WriteLine($"B rejected: {e.Message}");
b = Account.Load(store, "account-42"); // reload and re-run the command
try { store.Append("account-42", b.Version, b.Withdraw(80)); }
catch (InvalidOperationException e2) { Console.WriteLine($"B retried on v{b.Version}: {e2.Message}"); }
}
foreach (var e in store.ReadStream("account-42"))
Console.WriteLine($" v{e.Version} {e.Type} {e.Data}");
Console.WriteLine($"final balance: {Account.Load(store, "account-42").Balance}");
record NewEvent(string Type, string Data);
record StoredEvent(long Version, string Type, string Data);
class ConcurrencyException(string message) : Exception(message);
class EventStore
{
private readonly SqliteConnection _db = new("Data Source=:memory:");
public EventStore()
{
_db.Open();
Exec("""
CREATE TABLE events (
position INTEGER PRIMARY KEY AUTOINCREMENT, -- global order, for projections
stream_id TEXT NOT NULL,
version INTEGER NOT NULL, -- order inside one stream
type TEXT NOT NULL,
data TEXT NOT NULL,
UNIQUE (stream_id, version))
""");
}
public long Append(string streamId, long expectedVersion, IReadOnlyList<NewEvent> events)
{
using var tx = _db.BeginTransaction();
var check = _db.CreateCommand();
check.CommandText = "SELECT COALESCE(MAX(version), 0) FROM events WHERE stream_id = $s";
check.Parameters.AddWithValue("$s", streamId);
var actual = (long)check.ExecuteScalar()!;
if (actual != expectedVersion)
throw new ConcurrencyException($"{streamId}: expected v{expectedVersion}, but stream is at v{actual}");
try
{
for (var i = 0; i < events.Count; i++)
{
var insert = _db.CreateCommand();
insert.CommandText = "INSERT INTO events (stream_id, version, type, data) VALUES ($s, $v, $t, $d)";
insert.Parameters.AddWithValue("$s", streamId);
insert.Parameters.AddWithValue("$v", expectedVersion + i + 1);
insert.Parameters.AddWithValue("$t", events[i].Type);
insert.Parameters.AddWithValue("$d", events[i].Data);
insert.ExecuteNonQuery();
}
}
catch (SqliteException e) when (e.SqliteErrorCode == 19) // UNIQUE index is the real guard under races
{
throw new ConcurrencyException($"{streamId}: version taken ({e.Message})");
}
tx.Commit();
return expectedVersion + events.Count;
}
public List<StoredEvent> ReadStream(string streamId, long fromVersion = 0)
{
var cmd = _db.CreateCommand();
cmd.CommandText = "SELECT version, type, data FROM events WHERE stream_id = $s AND version > $v ORDER BY version";
cmd.Parameters.AddWithValue("$s", streamId);
cmd.Parameters.AddWithValue("$v", fromVersion);
using var r = cmd.ExecuteReader();
var list = new List<StoredEvent>();
while (r.Read()) list.Add(new(r.GetInt64(0), r.GetString(1), r.GetString(2)));
return list;
}
private void Exec(string sql) { var c = _db.CreateCommand(); c.CommandText = sql; c.ExecuteNonQuery(); }
}
// State is a left fold over the events. Apply never fails and never checks rules.
class Account
{
public long Version { get; private set; }
public long Balance { get; private set; }
public bool IsOpen { get; private set; }
public Account Apply(string type, string data)
{
switch (type)
{
case "AccountOpened": IsOpen = true; break;
case "Deposited": Balance += Amount(data); break;
case "Withdrawn": Balance -= Amount(data); break;
}
Version++;
return this;
}
public static Account Load(EventStore store, string streamId) =>
store.ReadStream(streamId).Aggregate(new Account(), (acc, e) => acc.Apply(e.Type, e.Data));
// Commands check rules against the folded state, then return new events. They don't save anything.
public List<NewEvent> Withdraw(long amount)
{
if (amount > Balance)
throw new InvalidOperationException($"insufficient funds: balance {Balance}, asked {amount}");
return [new("Withdrawn", $$"""{"amount":{{amount}}}""")];
}
private static long Amount(string json) => JsonDocument.Parse(json).RootElement.GetProperty("amount").GetInt64();
}
A and B both loaded v2, balance 100
A withdrew 80 -> stream now at v3
B rejected: account-42: expected v2, but stream is at v3
B retried on v3: insufficient funds: balance 20, asked 80
v1 AccountOpened {"owner":"Ada"}
v2 Deposited {"amount":100}
v3 Withdrawn {"amount":80}
final balance: 20
The outputs match line for line. The only difference is in the last three lines: Python prints the parsed dictionary ({'owner': 'Ada'}), and C# prints the raw JSON string it stored.
Three details worth noticing:
- The version check gives a clear error, but the unique index does the real work. Two processes can both read "version 2" before either inserts. The
UNIQUE (stream_id, version)constraint guarantees only one of them can write version 3. Both snippets catch the constraint error and turn it into the sameConcurrencyError. Every real store has an equivalent: a unique key, a conditional write, or a single writer per stream. - Retrying means re-running the command, not re-sending the events. B's retry reloaded the stream and called
withdrawagain. Resending B's originalWithdrawnevent would have defeated the whole point. - The conflict scope is one stream. That's why aggregate boundaries matter. If every order in the system shared one stream, every write would conflict. If one business rule spans two streams, the version check can't protect it, and you need a different tool, like a saga or a reservation.
Projections and read models
Nobody wants to replay a stream to render a list page. A projection reads events and writes a shape that's cheap to query: a balance per account, orders per customer, a search index. In CQRS terms, this is the read side.
Sync or async
An inline (synchronous) projection updates the read model in the same transaction as the append. Reads are never stale, but every write pays for every inline projection, and a bug in one blocks writes. Marten calls these inline projections.
An async projection runs in the background, reading the global log from a checkpoint. Writes stay fast and projections are isolated from each other, but reads are eventually consistent. Marten's async daemon, KurrentDB catch-up subscriptions, and a Cosmos DB change feed processor with its lease container are all this shape.
A practical default: inline for the one or two views the write path itself needs, async for everything else.
Checkpoints, crashes and idempotency
An async projection keeps a checkpoint: the last global position it finished. On restart it reads from there. The trap is what happens between "I updated the read model" and "I saved the checkpoint". If the process dies in that gap, the events since the last checkpoint get processed again. That's at-least-once delivery, and it's the normal case for change feeds and subscriptions.
There are two fixes. If the read model and the checkpoint live in the same database, update both in one transaction, and a crash rolls back both. If they can't share a transaction (a document store, a search index, another service), make each update idempotent. The demo stores the last applied position on each row and only applies an event with a higher position. That works because events inside one stream always arrive in order.
The demo runs the same crash twice: once with a naive projection, once with the guard. It crashes before position 6, after positions 4 and 5 were applied but before the checkpoint moved past 3.
import sqlite3
# The event log, in global order. In a real store this is "read $all from position N".
log = sqlite3.connect(":memory:")
log.execute("CREATE TABLE events (position INTEGER PRIMARY KEY, stream_id TEXT, type TEXT, amount INTEGER)")
log.executemany("INSERT INTO events VALUES (?, ?, ?, ?)", [
(1, "acc-1", "AccountOpened", 0), (2, "acc-1", "Deposited", 100),
(3, "acc-2", "AccountOpened", 0), (4, "acc-2", "Deposited", 50),
(5, "acc-1", "Withdrawn", 30), (6, "acc-2", "Deposited", 25),
(7, "acc-1", "Deposited", 10),
])
class Crash(Exception):
pass
class BalanceProjection:
"""An async read model with its own checkpoint. Autocommit on purpose: like a document store,
the row update and the checkpoint are NOT in one transaction, so a crash can replay events."""
def __init__(self, name, idempotent=True):
self.name, self.idempotent = name, idempotent
self.db = sqlite3.connect(":memory:", isolation_level=None)
self.db.execute("CREATE TABLE balances (account TEXT PRIMARY KEY, balance INTEGER, last_position INTEGER)")
self.db.execute("CREATE TABLE checkpoint (projection TEXT PRIMARY KEY, position INTEGER)")
def checkpoint(self):
row = self.db.execute("SELECT position FROM checkpoint WHERE projection = ?", (self.name,)).fetchone()
return row[0] if row else 0
def handle(self, position, stream_id, event_type, amount):
if event_type == "AccountOpened":
self.db.execute("INSERT OR IGNORE INTO balances VALUES (?, 0, ?)", (stream_id, position))
return
delta = amount if event_type == "Deposited" else -amount
# The guard: only apply an event newer than the last one this row has seen.
guard = position if self.idempotent else 10**9
cur = self.db.execute(
"UPDATE balances SET balance = balance + ?, last_position = ? WHERE account = ? AND last_position < ?",
(delta, position, stream_id, guard))
if cur.rowcount == 0:
print(f" skip position {position}: already applied")
def run(self, batch_size=3, crash_at=None):
while True:
start = self.checkpoint()
batch = log.execute(
"SELECT * FROM events WHERE position > ? ORDER BY position LIMIT ?", (start, batch_size)).fetchall()
if not batch:
return
for event in batch:
if event[0] == crash_at:
raise Crash(f"crashed before position {crash_at}, checkpoint still {start}")
self.handle(*event)
self.db.execute("INSERT OR REPLACE INTO checkpoint VALUES (?, ?)", (self.name, batch[-1][0]))
def show(self):
rows = self.db.execute("SELECT account, balance FROM balances ORDER BY account").fetchall()
return ", ".join(f"{a}={b}" for a, b in rows) + f" (checkpoint {self.checkpoint()})"
for idempotent in (False, True):
p = BalanceProjection("balances", idempotent)
print(f"{'idempotent' if idempotent else 'naive'} projection:")
try:
p.run(crash_at=6)
except Crash as e:
print(f" {e}")
p.run() # restart: resumes from the checkpoint, so positions 4 and 5 come again
print(f" {p.show()}")
# Rebuild: a new projection with an empty table and checkpoint 0 replays the whole log.
# Build it beside the old one, check it, then point reads at it and drop the old table.
rebuilt = BalanceProjection("balances-v2")
rebuilt.run(batch_size=100)
print(f"rebuilt from zero: {rebuilt.show()}")
naive projection:
crashed before position 6, checkpoint still 3
acc-1=50, acc-2=125 (checkpoint 7)
idempotent projection:
crashed before position 6, checkpoint still 3
skip position 4: already applied
skip position 5: already applied
acc-1=80, acc-2=75 (checkpoint 7)
rebuilt from zero: acc-1=80, acc-2=75 (checkpoint 7)
#:package Microsoft.Data.Sqlite@10.0.13
using Microsoft.Data.Sqlite;
// The event log, in global order. In a real store this is "read $all from position N".
Event[] log =
[
new(1, "acc-1", "AccountOpened", 0), new(2, "acc-1", "Deposited", 100),
new(3, "acc-2", "AccountOpened", 0), new(4, "acc-2", "Deposited", 50),
new(5, "acc-1", "Withdrawn", 30), new(6, "acc-2", "Deposited", 25),
new(7, "acc-1", "Deposited", 10),
];
foreach (var idempotent in new[] { false, true })
{
var p = new BalanceProjection("balances", log, idempotent);
Console.WriteLine($"{(idempotent ? "idempotent" : "naive")} projection:");
try { p.Run(crashAt: 6); }
catch (CrashException e) { Console.WriteLine($" {e.Message}"); }
p.Run(); // restart: resumes from the checkpoint, so positions 4 and 5 come again
Console.WriteLine($" {p.Show()}");
}
// Rebuild: a new projection with an empty table and checkpoint 0 replays the whole log.
// Build it beside the old one, check it, then point reads at it and drop the old table.
var rebuilt = new BalanceProjection("balances-v2", log);
rebuilt.Run(batchSize: 100);
Console.WriteLine($"rebuilt from zero: {rebuilt.Show()}");
record Event(long Position, string StreamId, string Type, long Amount);
class CrashException(string message) : Exception(message);
// An async read model with its own checkpoint. No transaction on purpose: like a document store,
// the row update and the checkpoint are NOT atomic together, so a crash can replay events.
class BalanceProjection
{
private readonly SqliteConnection _db = new("Data Source=:memory:");
private readonly string _name;
private readonly Event[] _log;
private readonly bool _idempotent;
public BalanceProjection(string name, Event[] log, bool idempotent = true)
{
(_name, _log, _idempotent) = (name, log, idempotent);
_db.Open();
Exec("CREATE TABLE balances (account TEXT PRIMARY KEY, balance INTEGER, last_position INTEGER)");
Exec("CREATE TABLE checkpoint (projection TEXT PRIMARY KEY, position INTEGER)");
}
public long Checkpoint() =>
(long?)Scalar("SELECT position FROM checkpoint WHERE projection = $n", ("$n", _name)) ?? 0;
private void Handle(Event e)
{
if (e.Type == "AccountOpened")
{
Exec("INSERT OR IGNORE INTO balances VALUES ($a, 0, $p)", ("$a", e.StreamId), ("$p", e.Position));
return;
}
var delta = e.Type == "Deposited" ? e.Amount : -e.Amount;
// The guard: only apply an event newer than the last one this row has seen.
var guard = _idempotent ? e.Position : 1_000_000_000;
var changed = Exec(
"UPDATE balances SET balance = balance + $d, last_position = $p WHERE account = $a AND last_position < $g",
("$d", delta), ("$p", e.Position), ("$a", e.StreamId), ("$g", guard));
if (changed == 0) Console.WriteLine($" skip position {e.Position}: already applied");
}
public void Run(int batchSize = 3, long? crashAt = null)
{
while (true)
{
var start = Checkpoint();
var batch = _log.Where(e => e.Position > start).OrderBy(e => e.Position).Take(batchSize).ToList();
if (batch.Count == 0) return;
foreach (var e in batch)
{
if (e.Position == crashAt)
throw new CrashException($"crashed before position {crashAt}, checkpoint still {start}");
Handle(e);
}
Exec("INSERT OR REPLACE INTO checkpoint VALUES ($n, $p)", ("$n", _name), ("$p", batch[^1].Position));
}
}
public string Show()
{
var cmd = _db.CreateCommand();
cmd.CommandText = "SELECT account, balance FROM balances ORDER BY account";
using var r = cmd.ExecuteReader();
var parts = new List<string>();
while (r.Read()) parts.Add($"{r.GetString(0)}={r.GetInt64(1)}");
return string.Join(", ", parts) + $" (checkpoint {Checkpoint()})";
}
private SqliteCommand Cmd(string sql, (string, object)[] ps)
{
var c = _db.CreateCommand();
c.CommandText = sql;
foreach (var (k, v) in ps) c.Parameters.AddWithValue(k, v);
return c;
}
private int Exec(string sql, params (string, object)[] ps) => Cmd(sql, ps).ExecuteNonQuery();
private object? Scalar(string sql, params (string, object)[] ps) => Cmd(sql, ps).ExecuteScalar();
}
naive projection:
crashed before position 6, checkpoint still 3
acc-1=50, acc-2=125 (checkpoint 7)
idempotent projection:
crashed before position 6, checkpoint still 3
skip position 4: already applied
skip position 5: already applied
acc-1=80, acc-2=75 (checkpoint 7)
rebuilt from zero: acc-1=80, acc-2=75 (checkpoint 7)
The naive projection double-counted positions 4 and 5. Account 1 lost an extra 30 and account 2 gained an extra 50. Nothing crashed loudly and nothing logged an error. The numbers were just wrong. The idempotent one skipped both and ended correct.
Rebuilding from zero
The last line is the important one. A projection is disposable, so you fix a projection bug by fixing the code and replaying, instead of writing a data patch. You also add a new read model to old data the same way.
The safe way to do it in production is blue/green: build the new projection into a new table with its own checkpoint, starting from position 0, while the old one keeps serving. When the new one catches up to the live position, switch reads to it and drop the old table. Rebuild time is the real cost. A store with tens of millions of events can take hours to replay, which is a good reason to keep projections simple and fast, and to measure replay speed before you need it.
Snapshots
Loading an aggregate means reading its whole stream. For most aggregates that's a few dozen events and it's fine. For a long-lived stream (an account with years of transactions, a device sending readings) it gets slow.
A snapshot saves the folded state at some version. Loading becomes: read the latest snapshot, then read only the events after it.
The rules I'd hold to:
- Snapshots are a cache, never the truth. You can delete every snapshot and the system still works, just slower. Never write business data only to a snapshot.
- Version the snapshot's shape. When a deploy changes the state class, old snapshots don't fit. Store a schema number with each one and ignore any that don't match. The fold from events still works, because events are the truth.
- Snapshot on a rule. Every N events is simple and good enough. Axon's event count snapshot trigger, Marten's inline single-stream projections, and the Python
eventsourcinglibrary's snapshotting intervals all follow this idea. - Measure first. Snapshots add a second write path and a cache invalidation problem. If loads are fast, don't add them. A very long stream is sometimes a sign the aggregate boundary is wrong. "Account" might really be "account per statement period", which also closes old streams naturally.
import json
SNAPSHOT_EVERY = 250
class Store:
"""Events plus a separate, disposable snapshot table. Snapshots are a cache, never the truth."""
def __init__(self):
self.events, self.snapshots, self.reads = {}, {}, 0
def append(self, stream_id, event):
self.events.setdefault(stream_id, []).append(event)
def read_stream(self, stream_id, from_version=0):
tail = self.events.get(stream_id, [])[from_version:]
self.reads += len(tail)
return tail
class Account:
SCHEMA = 1 # bump when the shape of the state (not the events) changes
def __init__(self, version=0, balance=0, deposits=0):
self.version, self.balance, self.deposits = version, balance, deposits
def apply(self, event):
self.balance += event["amount"]
self.deposits += 1
self.version += 1
class Repository:
def __init__(self, store):
self.store = store
def load(self, stream_id, use_snapshots=True):
account, note = Account(), "no snapshot"
snap = self.store.snapshots.get(stream_id) if use_snapshots else None
if snap and snap["schema"] == Account.SCHEMA:
account, note = Account(**json.loads(snap["state"])), f"snapshot v{snap['version']}"
elif snap:
note = f"snapshot v{snap['version']} ignored (schema {snap['schema']} != {Account.SCHEMA})"
for event in self.store.read_stream(stream_id, account.version):
account.apply(event)
return account, note
def save(self, stream_id, account, event):
self.store.append(stream_id, event)
account.apply(event)
if account.version % SNAPSHOT_EVERY == 0: # cheap rule: every N events
state = json.dumps({"version": account.version, "balance": account.balance, "deposits": account.deposits})
self.store.snapshots[stream_id] = {"version": account.version, "schema": Account.SCHEMA, "state": state}
store = Store()
repo = Repository(store)
account = Account()
for i in range(1050):
repo.save("acc-7", account, {"type": "Deposited", "amount": i % 7 + 1})
def report(label, **kwargs):
store.reads = 0
acc, note = repo.load("acc-7", **kwargs)
print(f"{label:<15} {note:<38} read {store.reads:>4} events -> v{acc.version} balance {acc.balance}")
report("full replay:", use_snapshots=False)
report("with snapshot:")
Account.SCHEMA = 2 # a deploy changed the state shape
report("after deploy:")
full replay: no snapshot read 1050 events -> v1050 balance 4200
with snapshot: snapshot v1000 read 50 events -> v1050 balance 4200
after deploy: snapshot v1000 ignored (schema 1 != 2) read 1050 events -> v1050 balance 4200
using System.Text.Json;
using System.Text.Json.Serialization;
const int SnapshotEvery = 250;
var store = new Store();
var repo = new Repository(store, SnapshotEvery);
var account = new AccountState();
for (var i = 0; i < 1050; i++)
account = repo.Save("acc-7", account, new Deposited(i % 7 + 1));
void Report(string label, bool useSnapshots = true)
{
store.Reads = 0;
var (acc, note) = repo.Load("acc-7", useSnapshots);
Console.WriteLine($"{label,-15} {note,-38} read {store.Reads,4} events -> v{acc.Version} balance {acc.Balance}");
}
Report("full replay:", useSnapshots: false);
Report("with snapshot:");
AccountState.Schema = 2; // a deploy changed the state shape
Report("after deploy:");
record Deposited(long Amount);
// File-based apps are AOT-friendly by default, so JSON uses a source-generated context.
[JsonSerializable(typeof(AccountState))]
partial class SnapshotJson : JsonSerializerContext;
record Snapshot(long Version, int Schema, string State);
// Events plus a separate, disposable snapshot table. Snapshots are a cache, never the truth.
class Store
{
public Dictionary<string, List<Deposited>> Events { get; } = new();
public Dictionary<string, Snapshot> Snapshots { get; } = new();
public int Reads { get; set; }
public void Append(string streamId, Deposited e)
{
if (!Events.TryGetValue(streamId, out var list)) Events[streamId] = list = [];
list.Add(e);
}
public IEnumerable<Deposited> ReadStream(string streamId, long fromVersion)
{
var tail = Events.GetValueOrDefault(streamId, []).Skip((int)fromVersion).ToList();
Reads += tail.Count;
return tail;
}
}
record AccountState(long Version = 0, long Balance = 0, long Deposits = 0)
{
public static int Schema = 1; // bump when the shape of the state (not the events) changes
public AccountState Apply(Deposited e) =>
this with { Version = Version + 1, Balance = Balance + e.Amount, Deposits = Deposits + 1 };
}
class Repository(Store store, int snapshotEvery)
{
public (AccountState, string) Load(string streamId, bool useSnapshots = true)
{
var state = new AccountState();
var note = "no snapshot";
if (useSnapshots && store.Snapshots.TryGetValue(streamId, out var snap))
{
if (snap.Schema == AccountState.Schema)
{
state = JsonSerializer.Deserialize(snap.State, SnapshotJson.Default.AccountState)!;
note = $"snapshot v{snap.Version}";
}
else note = $"snapshot v{snap.Version} ignored (schema {snap.Schema} != {AccountState.Schema})";
}
state = store.ReadStream(streamId, state.Version).Aggregate(state, (s, e) => s.Apply(e));
return (state, note);
}
public AccountState Save(string streamId, AccountState state, Deposited e)
{
store.Append(streamId, e);
state = state.Apply(e);
if (state.Version % snapshotEvery == 0) // cheap rule: every N events
{
var json = JsonSerializer.Serialize(state, SnapshotJson.Default.AccountState);
store.Snapshots[streamId] = new(state.Version, AccountState.Schema, json);
}
return state;
}
}
full replay: no snapshot read 1050 events -> v1050 balance 4200
with snapshot: snapshot v1000 read 50 events -> v1050 balance 4200
after deploy: snapshot v1000 ignored (schema 1 != 2) read 1050 events -> v1050 balance 4200
With the snapshot, the load read 50 events instead of 1,050. After a deploy bumped the state schema, the old snapshot was ignored and the load fell back to a full replay, still correct. The next save that crosses a multiple of 250 writes a fresh snapshot in the new shape.
One C# detail: file-based apps are trim and AOT friendly by default, so System.Text.Json refuses reflection-based serialization. The snippet uses a source-generated JsonSerializerContext, which is what you'd want in a real service anyway.
Event schema evolution
This is where event-sourced systems really get hard over time. Your code changes every week. Your events live forever. Greg Young wrote a whole book on it, Versioning in an Event Sourced System, and its core rule is simple: never edit history. Old events stay exactly as they were written. You change how you read them.
The main tools, from cheapest to most expensive:
| Technique | What it handles | How |
|---|---|---|
| Weak schema | Added optional fields, removed fields | Read what you know, default what's missing, ignore what you don't know. No version bump needed. |
| Upcasting | Renamed events, renamed or reshaped fields, unit changes | On read, transform old versions to the current one, one small step at a time. |
| New event type | A real change in meaning | OrderShippedV2 or a new name. Old and new both stay valid, and the fold handles both. |
| Copy-and-transform | Big structural mistakes | Write a new stream (or a new store) from the old one, then switch. The old one stays for audit. Rare and expensive. |
The demo has five stored events written by three generations of an app. The 2023 version called the event FundsAdded and stored dollars as a decimal. The 2024 version renamed it to Deposited and stored cents. The current version adds a currency and an optional channel, and one event has a promo field nobody reads anymore. Upcasters lift each version one step. Weak-schema reading fills in the missing channel and ignores the unknown field.
import json
# What is really on disk, written by three generations of the app. We never edit these rows.
stored = [
("AccountOpened", 1, '{"owner": "Ada"}'),
("FundsAdded", 1, '{"amount": 12.5}'), # 2023: old name, dollars
("Deposited", 2, '{"amount_cents": 4000}'), # 2024: cents, no currency
("Deposited", 3, '{"amount_cents": 1500, "currency": "USD", "channel": "app"}'),
("Deposited", 3, '{"amount_cents": 700, "currency": "USD", "promo": "x1"}'),
]
# Each upcaster lifts one (type, version) a single step. Small steps chain; nobody writes v1 -> v3 by hand.
UPCASTERS = {
("FundsAdded", 1): lambda d: ("Deposited", 1, d), # rename
("Deposited", 1): lambda d: ("Deposited", 2, {"amount_cents": round(d["amount"] * 100)}),
("Deposited", 2): lambda d: ("Deposited", 3, {**d, "currency": "USD"}), # default for old rows
}
def upcast(event_type, version, data):
while (event_type, version) in UPCASTERS:
event_type, version, data = UPCASTERS[(event_type, version)](data)
return event_type, version, data
def to_deposit(data):
# Weak schema on read: take what you know, default what's missing, ignore what you don't know.
return {"cents": data["amount_cents"], "currency": data["currency"], "channel": data.get("channel", "unknown")}
balance = 0
for event_type, version, raw in stored:
t, v, data = upcast(event_type, version, json.loads(raw))
if t == "Deposited":
dep = to_deposit(data)
balance += dep["cents"]
print(f"{event_type} v{version:<2} -> {t} v{v} {dep}")
else:
print(f"{event_type} v{version:<2} -> {t} v{v}")
print(f"balance: {balance} cents; stored rows changed: 0")
AccountOpened v1 -> AccountOpened v1
FundsAdded v1 -> Deposited v3 {'cents': 1250, 'currency': 'USD', 'channel': 'unknown'}
Deposited v2 -> Deposited v3 {'cents': 4000, 'currency': 'USD', 'channel': 'unknown'}
Deposited v3 -> Deposited v3 {'cents': 1500, 'currency': 'USD', 'channel': 'app'}
Deposited v3 -> Deposited v3 {'cents': 700, 'currency': 'USD', 'channel': 'unknown'}
balance: 7450 cents; stored rows changed: 0
using System.Text.Json.Nodes;
// What is really on disk, written by three generations of the app. We never edit these rows.
(string Type, int Version, string Json)[] stored =
[
("AccountOpened", 1, """{"owner": "Ada"}"""),
("FundsAdded", 1, """{"amount": 12.5}"""), // 2023: old name, dollars
("Deposited", 2, """{"amount_cents": 4000}"""), // 2024: cents, no currency
("Deposited", 3, """{"amount_cents": 1500, "currency": "USD", "channel": "app"}"""),
("Deposited", 3, """{"amount_cents": 700, "currency": "USD", "promo": "x1"}"""),
];
// Each upcaster lifts one (type, version) a single step. Small steps chain; nobody writes v1 -> v3 by hand.
var upcasters = new Dictionary<(string, int), Func<JsonObject, (string, int, JsonObject)>>
{
[("FundsAdded", 1)] = d => ("Deposited", 1, d), // rename
[("Deposited", 1)] = d => ("Deposited", 2,
new JsonObject { ["amount_cents"] = (long)Math.Round(d["amount"]!.GetValue<decimal>() * 100) }),
[("Deposited", 2)] = d => { d["currency"] = "USD"; return ("Deposited", 3, d); }, // default for old rows
};
(string, int, JsonObject) Upcast(string type, int version, JsonObject data)
{
while (upcasters.TryGetValue((type, version), out var step))
(type, version, data) = step(data);
return (type, version, data);
}
// Weak schema on read: take what you know, default what's missing, ignore what you don't know.
Deposit ToDeposit(JsonObject d) => new(
d["amount_cents"]!.GetValue<long>(),
d["currency"]!.GetValue<string>(),
d["channel"]?.GetValue<string>() ?? "unknown");
long balance = 0;
foreach (var (type, version, json) in stored)
{
var (t, v, data) = Upcast(type, version, JsonNode.Parse(json)!.AsObject());
if (t == "Deposited")
{
var dep = ToDeposit(data);
balance += dep.Cents;
Console.WriteLine($"{type} v{version,-2} -> {t} v{v} {dep}");
}
else Console.WriteLine($"{type} v{version,-2} -> {t} v{v}");
}
Console.WriteLine($"balance: {balance} cents; stored rows changed: 0");
record Deposit(long Cents, string Currency, string Channel);
AccountOpened v1 -> AccountOpened v1
FundsAdded v1 -> Deposited v3 Deposit { Cents = 1250, Currency = USD, Channel = unknown }
Deposited v2 -> Deposited v3 Deposit { Cents = 4000, Currency = USD, Channel = unknown }
Deposited v3 -> Deposited v3 Deposit { Cents = 1500, Currency = USD, Channel = app }
Deposited v3 -> Deposited v3 Deposit { Cents = 700, Currency = USD, Channel = unknown }
balance: 7450 cents; stored rows changed: 0
Same numbers in both languages. The only difference is how each one prints a record: Python's dict repr versus the C# record's generated ToString.
A few habits make this much easier:
- Store the event type and a version with every event, from day one. Retrofitting a version field onto millions of events is a copy-and-transform job.
- Keep upcasters as small, single steps: v1 to v2, v2 to v3. Each one is a few lines and easy to test. A new version adds one step and never touches the old ones.
- Use explicit event type names instead of CLR or Python class names. If the stored type is
MyApp.Domain.Events.Deposited, MyApp, then a namespace refactor breaks every old event. StoreDepositedand map it. - Test old events forever. Keep a fixture file of real (anonymized) events from every version and run it through the current read path in CI.
Library support exists. Axon has SingleEventUpcaster. The Python eventsourcing library upcasts with a class version and upcast_v1_v2 style methods. Marten supports upcasting transforms on read. KurrentDB leaves it to your serializer layer, which is where the code above lives.
GDPR, the right to erasure, and crypto-shredding
Append-only and "delete my data" look like they can't both be true. There are three common answers, and most systems use more than one:
- Keep personal data out of events. Store a customer ID in the event and keep the name, email and address in a normal table you can delete from. The event says "customer 981 placed an order", which is still a useful fact after 981 is forgotten.
- Crypto-shredding. Encrypt personal fields in each event with a key per person, stored in a key store. To forget the person, delete their key. The events stay, but the personal fields become unreadable ciphertext everywhere, including in backups and in every downstream copy. Projections must handle "key not found" by showing a placeholder.
- Stream deletion or truncation. Some stores can delete or truncate a stream (KurrentDB supports soft and hard deletes and truncate-before). Use it for whole aggregates that belong to one person, and remember that projections and backups still need cleaning.
I haven't put runnable code here, because doing it properly needs a real authenticated cipher, and Python's standard library doesn't include one. The shape is small though: a keys table keyed by subject ID, an encrypt step in the serializer for fields marked personal, and a decrypt step that returns a placeholder when the key is gone. Get legal advice on what counts as erasure in your situation. Crypto-shredding is widely used, but it's a technical control and doesn't settle the legal question.
How it pairs with CQRS
CQRS (command query responsibility segregation) means using a different model for writes than for reads. You can do CQRS without event sourcing: write to normal tables, then update a denormalized read store. You can, in theory, do event sourcing without CQRS, but you'd be querying by replaying streams, which almost nobody wants.
In practice they arrive together:
- Write side: commands load an aggregate by folding its stream, check rules, append events with an expected version.
- Read side: projections turn the global log into as many read models as you need, each shaped for one screen or one API.
- The seam: the read side lags the write side. Design the UI for it: return the new version from the command, and let the client wait for the projection to reach that version, or show the optimistic result.
Publishing events to other services is a separate concern from storing them. If your store can't publish reliably on its own (a change feed or subscription), the transactional outbox is how you avoid the dual write between "saved the event" and "sent the message". Part 2 of the series used the Cosmos DB change feed for this.
The engines, briefly
| Engine | Language | What it gives you |
|---|---|---|
| KurrentDB (formerly EventStoreDB) | Any (gRPC clients for .NET, Python, Java, Node, Go, Rust) | A purpose-built event database: streams, expected revisions, $all, catch-up and persistent subscriptions, server-side projections. |
| Marten | C# (.NET) | Event store and document DB on PostgreSQL: streams, inline and async projections with the async daemon, live aggregation, upcasting. A good fit if you already run Postgres. |
| Axon Framework / Axon Server | Java, Kotlin | A full CQRS and event sourcing framework: aggregates, sagas, snapshot triggers, upcasters, plus an event store server. |
| eventsourcing | Python | A mature library: aggregates with an @event decorator, applications and repositories, snapshotting, upcasting, and adapters for SQLite and PostgreSQL. |
| Cosmos DB + change feed | Any | Not an event store, but a common way to build one: partition by stream ID, use a transactional batch for appends, and the change feed (ordered within a partition key, at-least-once, checkpointed in a lease container) for projections. |
The code in this post is a teaching model of what these products do. Don't ship a hand-rolled event store unless you have a reason. The hard parts (subscriptions under load, global ordering at scale, operations) are exactly what the products are for.
When not to use it
Part 1 covers this properly, so here's the short version from the mechanics side. Every section above is a cost you sign up for: versioned events forever, projections to rebuild, snapshots to invalidate, eventual consistency in the UI, and erasure that needs a plan. Pay it when the history itself is the product: audit as a hard requirement, "what did this look like on March 15th" as a feature, or a domain where the events drive other processes.
Don't pay it for CRUD, for a whole system when one bounded context needs it, or when an audit table or temporal tables would answer the actual question. You can event-source the ledger and keep the user profile in a normal table. Mixing styles per bounded context is normal.
Check yourself: questions and answers
1. What's the difference between a stream's version and the store's global position?
Version counts events inside one stream and is what the expected-version check uses. Position orders events across all streams and is what projections checkpoint on. An event has both.
2. Two requests withdraw from the same account at the same moment. What stops the overdraft?
Each loads the stream and appends with the version it loaded as the expected version. The second append sees the stream has moved on and fails. The handler reloads, re-runs the command against the new state, and the business rule rejects it. Under the hood, a unique key on stream and version makes sure only one write can win.
3. Why must apply never throw or check business rules?
Because events are facts that already happened. If apply could refuse an event, an old stream could become impossible to load after a rule change. Rules belong in commands, which run before the event exists.
4. Your async projection crashed and reprocessed some events. How do you keep it correct?
Either commit the read model update and the checkpoint in one transaction, or make each update idempotent. A common guard is storing the last applied position per row and skipping anything not newer. The naive alternative silently double-counts.
5. When would you add snapshots, and what's the one rule for them?
When measured load times for long streams hurt. The rule: snapshots are a disposable cache. Version their shape, ignore stale ones, and make sure deleting them all only costs speed. Also check whether a long stream means the aggregate boundary is wrong.
6. An event from 2023 has a field in dollars, and the current code expects cents. What do you do?
Write an upcaster that converts the old version to the new one on read. Don't edit the stored events. Chain small single-step upcasters, and keep test fixtures of real old events.
7. How do you honor a deletion request in an append-only log?
Keep personal data out of events where you can, encrypt what remains with a per-person key and delete the key to forget them (crypto-shredding), and use stream deletion for aggregates that belong to one person. Remember the projections and backups too.
8. Is CQRS the same as event sourcing?
No. CQRS splits the write model from the read model and works with plain tables. Event sourcing stores events as the source of truth. They pair well because event sourcing almost forces a separate read side, and projections are a natural way to build it.
Further reading
- Martin Fowler, Event Sourcing and CQRS
- Greg Young, CQRS Documents and Versioning in an Event Sourced System
- Kurrent (KurrentDB / EventStoreDB) documentation and Kurrent's article on snapshots in event sourcing
- Marten event store documentation
- Axon documentation
- eventsourcing (Python) documentation
- Microsoft Learn, Event Sourcing pattern, CQRS pattern and Materialized View pattern
- Microsoft Learn, Change feed in Azure Cosmos DB
- Martin Kleppmann, Designing Data-Intensive Applications, chapter 11 on stream processing and event logs
- From this blog: Event Sourcing Part 1: The Honest Truth, Part 2: Azure Building Blocks, Saga Orchestration, The Transactional Outbox in Depth, The Saga Pattern in Depth
Thoughts on this?
Tell me on X: @bobbyencoded · Share this post on X
Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.