Event Sourcing in Rust With a Small Working Example
Event sourcing stores changes as an append-only list of events and derives state by folding them. A small Rust example: events enum, aggregate, command handling, store and replay.

Most programs store the current state and throw the history away: a balance is a number in a table, and the number changed from something to something else, nobody knows why. Event sourcing stores the opposite. It keeps the facts, in order, and treats the current state as a value you can recompute. That buys an audit trail, the ability to rebuild any past state, and read models you can change without migrations. It costs discipline in three places: what an event may contain, where the rules live and what happens when two writers race. This guide builds a small bank ledger in Rust that does it properly, tests it with a property test and measures the costs. Everything compiled and ran on Rust 1.99, edition 2024, with serde 1, serde_json 1, thiserror 2 and, in tests, proptest and tempfile.
Three ideas, in code
Event sourcing separates three things that most programs blur together.
An event is a fact that already happened. It is named in the past tense, it is immutable and it is stored forever. Deposited { id, cents } is an event.
A command is a request that might be refused. Deposit { id, cents } is a command. It carries the same data but a different promise: nobody has agreed to it yet.
State is what you get by folding events in order. It is a cache of the log, never the truth, and it can be thrown away and rebuilt.
Here are the types:
//! Event sourcing in one file: the stored truth is a list of facts, and the
//! current state is what you get by replaying them.
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::Path;
/// Something that happened. Past tense, immutable, never edited after it is stored.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Event {
AccountOpened {
id: String,
owner: String,
},
Deposited {
id: String,
cents: u64,
/// Added after the first release; old events simply have no note.
#[serde(default, skip_serializing_if = "Option::is_none")]
note: Option<String>,
},
Withdrawn {
id: String,
cents: u64,
},
AccountClosed {
id: String,
},
}
/// What someone asks for. It may be refused; an event is never refused.
#[derive(Debug, Clone, PartialEq)]
pub enum Command {
Open { id: String, owner: String },
Deposit { id: String, cents: u64 },
Withdraw { id: String, cents: u64 },
Close { id: String },
}
#[derive(Debug, PartialEq, thiserror::Error)]
pub enum Rejected {
#[error("account {0} already exists")]
AlreadyExists(String),
#[error("account {0} does not exist")]
Unknown(String),
#[error("account {0} is closed")]
Closed(String),
#[error("account {id} has {have} cents, cannot withdraw {want}")]
Insufficient { id: String, have: u64, want: u64 },
#[error("account {0} still has money and cannot be closed")]
NotEmpty(String),
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Account {
pub owner: String,
pub balance: u64,
pub open: bool,
}
/// The read model: derived entirely from events, rebuildable at any time.
#[derive(Debug, Default, PartialEq, Clone, Serialize, Deserialize)]
pub struct Ledger {
pub accounts: BTreeMap<String, Account>,
pub version: u64,
}Event derives Serialize and Deserialize with #[serde(tag = "type")], which writes each variant as a JSON object with a "type" field. That makes the log readable by a human, and by a tool written in another language. Command is deliberately not serialisable: commands are inputs to a decision, not records. Rejected lists every reason a command can fail, with a message for each; the thiserror derive writes the Display impl from the #[error(...)] attributes.
Ledger is the read model: a map of accounts and a version that counts the events applied. It carries serde derives only because a snapshot will need them later.
apply and decide
The two functions that matter are small, and keeping them apart is the whole discipline:
impl Ledger {
/// Pure and total: applying an event never fails, because events are facts.
pub fn apply(&mut self, event: &Event) {
match event {
Event::AccountOpened { id, owner } => {
self.accounts.insert(
id.clone(),
Account {
owner: owner.clone(),
balance: 0,
open: true,
},
);
}
Event::Deposited { id, cents, .. } => {
if let Some(a) = self.accounts.get_mut(id) {
a.balance += cents;
}
}
Event::Withdrawn { id, cents } => {
if let Some(a) = self.accounts.get_mut(id) {
a.balance -= cents;
}
}
Event::AccountClosed { id } => {
if let Some(a) = self.accounts.get_mut(id) {
a.open = false;
}
}
}
self.version += 1;
}
pub fn replay<'a>(events: impl IntoIterator<Item = &'a Event>) -> Ledger {
let mut ledger = Ledger::default();
for e in events {
ledger.apply(e);
}
ledger
}
/// Decide: check the rules against the current state and return the events to record.
pub fn decide(&self, cmd: &Command) -> Result<Vec<Event>, Rejected> {
match cmd {
Command::Open { id, owner } => {
if self.accounts.contains_key(id) {
return Err(Rejected::AlreadyExists(id.clone()));
}
Ok(vec![Event::AccountOpened {
id: id.clone(),
owner: owner.clone(),
}])
}
Command::Deposit { id, cents } => {
self.open_account(id)?;
Ok(vec![Event::Deposited {
id: id.clone(),
cents: *cents,
note: None,
}])
}
Command::Withdraw { id, cents } => {
let a = self.open_account(id)?;
if a.balance < *cents {
return Err(Rejected::Insufficient {
id: id.clone(),
have: a.balance,
want: *cents,
});
}
Ok(vec![Event::Withdrawn {
id: id.clone(),
cents: *cents,
}])
}
Command::Close { id } => {
let a = self.open_account(id)?;
if a.balance != 0 {
return Err(Rejected::NotEmpty(id.clone()));
}
Ok(vec![Event::AccountClosed { id: id.clone() }])
}
}
}
fn open_account(&self, id: &str) -> Result<&Account, Rejected> {
let a = self
.accounts
.get(id)
.ok_or_else(|| Rejected::Unknown(id.to_string()))?;
if a.open {
Ok(a)
} else {
Err(Rejected::Closed(id.to_string()))
}
}
}apply takes an event and changes the state. It never fails and it checks nothing. That is not laziness, it is the rule: an event is a fact, and a fact cannot be rejected after the fact. The tempting if balance < cents { return Err(...) } inside apply looks defensive and breaks the system; the section on rule changes shows how.
decide takes the current state and a command and returns either the events to record or a Rejected. All the business rules live here: a withdrawal needs sufficient funds, a closed account takes no deposits, an account can only close with a zero balance. decide does not change the state. It reads it, and it can be exercised without any storage at all.
replay is a fold: start from Ledger::default() and apply each event. The ledger counts events in version, so after a replay the version equals the number of events consumed.
The log is a file of facts
The store is an append-only file with one JSON event per line:
/// An append-only file of one JSON event per line.
pub struct Store {
file: File,
}
impl Store {
pub fn open(path: &Path) -> std::io::Result<Store> {
Ok(Store {
file: OpenOptions::new()
.create(true)
.append(true)
.read(true)
.open(path)?,
})
}
pub fn append(&mut self, events: &[Event]) -> std::io::Result<()> {
for e in events {
let mut line = serde_json::to_vec(e).expect("events always serialise");
line.push(b'\n');
self.file.write_all(&line)?;
}
self.file.sync_data()
}
pub fn load(path: &Path) -> std::io::Result<Vec<Event>> {
if !path.exists() {
return Ok(Vec::new());
}
let mut events = Vec::new();
for line in BufReader::new(File::open(path)?).lines() {
let line = line?;
if line.trim().is_empty() {
continue;
}
events.push(serde_json::from_str(&line).map_err(std::io::Error::other)?);
}
Ok(events)
}
}append writes each event as a line and calls sync_data, so an acknowledged event survives a crash; remove that call and a power cut can lose the last few events while the process believes they are saved. load reads the file back, skipping blank lines, and returns an error rather than silently dropping a line it cannot parse. The format is JSON Lines because it is trivially appendable and survives a torn last write better than one big array.
The command handler ties the pieces together, and the order of its three steps is the correctness argument:
/// Decide, persist, then apply: the order matters.
pub fn handle(ledger: &mut Ledger, store: &mut Store, cmd: Command) -> Result<usize, Rejected> {
let events = ledger.decide(&cmd)?;
store.append(&events).expect("disk write");
for e in &events {
ledger.apply(e);
}
Ok(events.len())
}- Decide against the in-memory state. If it fails, return the rejection: nothing was recorded.
- Persist the events. If this fails, the state is unchanged, so memory and disk still agree.
- Apply the events to the in-memory state, only after they are durable.
Reversing steps two and three would let the process hold a state that its own log does not contain, which is exactly the inconsistency event sourcing exists to avoid.
Run a script of commands, some of which are refused:
use ledger::{Command, Ledger, Store, handle};
use std::path::Path;
fn main() {
let path = Path::new("ledger.jsonl");
let _ = std::fs::remove_file(path);
let mut store = Store::open(path).unwrap();
let mut ledger = Ledger::default();
let script = [
Command::Open {
id: "a1".into(),
owner: "ada".into(),
},
Command::Deposit {
id: "a1".into(),
cents: 10_000,
},
Command::Withdraw {
id: "a1".into(),
cents: 2_500,
},
Command::Withdraw {
id: "a1".into(),
cents: 99_999,
},
Command::Close { id: "a1".into() },
Command::Deposit {
id: "zz".into(),
cents: 1,
},
];
for cmd in script {
match handle(&mut ledger, &mut store, cmd.clone()) {
Ok(n) => println!("ok {cmd:?} -> {n} event(s)"),
Err(why) => println!("deny {cmd:?} -> {why}"),
}
}
println!("\n-- the file on disk --");
print!("{}", std::fs::read_to_string(path).unwrap());
println!("\n-- state rebuilt from the file --");
let rebuilt = Ledger::replay(&Store::load(path).unwrap());
println!("{:#?}", rebuilt.accounts);
println!(
"version {} same as live state: {}",
rebuilt.version,
rebuilt == ledger
);
}ok Open { id: "a1", owner: "ada" } -> 1 event(s)
ok Deposit { id: "a1", cents: 10000 } -> 1 event(s)
ok Withdraw { id: "a1", cents: 2500 } -> 1 event(s)
deny Withdraw { id: "a1", cents: 99999 } -> account a1 has 7500 cents, cannot withdraw 99999
deny Close { id: "a1" } -> account a1 still has money and cannot be closed
deny Deposit { id: "zz", cents: 1 } -> account zz does not exist
-- the file on disk --
{"type":"AccountOpened","id":"a1","owner":"ada"}
{"type":"Deposited","id":"a1","cents":10000}
{"type":"Withdrawn","id":"a1","cents":2500}
-- state rebuilt from the file --
{
"a1": Account {
owner: "ada",
balance: 7500,
open: true,
},
}
version 3 same as live state: trueThree commands were accepted and three refused, and the file on disk has exactly three lines. The withdrawal of 99,999 cents was denied with a message naming the balance (7,500 cents after the 2,500 withdrawal), the close was denied because money remained, and the deposit to an unknown account was denied. None of those left a trace in the log, which is correct: they never happened. The state rebuilt from the file is identical to the live state, shown by the final comparison.
Testing it
The rules are tested at the level where they live. Four behaviour tests pin the decisions that are easy to get wrong:
use ledger::{Command, Conflict, Event, Ledger, Rejected, Store, handle};
fn cmd_open(id: &str) -> Command {
Command::Open {
id: id.into(),
owner: "ada".into(),
}
}
#[test]
fn rules_live_in_decide_and_a_rejection_records_nothing() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("log.jsonl");
let mut store = Store::open(&path).unwrap();
let mut ledger = Ledger::default();
handle(&mut ledger, &mut store, cmd_open("a")).unwrap();
let err = handle(
&mut ledger,
&mut store,
Command::Withdraw {
id: "a".into(),
cents: 5,
},
)
.unwrap_err();
assert_eq!(
err,
Rejected::Insufficient {
id: "a".into(),
have: 0,
want: 5
}
);
assert_eq!(
Store::load(&path).unwrap().len(),
1,
"only the open was stored"
);
}
#[test]
fn old_events_without_the_new_field_still_load() {
let old = r#"{"type":"Deposited","id":"a","cents":100}"#;
let event: Event = serde_json::from_str(old).unwrap();
assert_eq!(
event,
Event::Deposited {
id: "a".into(),
cents: 100,
note: None
}
);
}
#[test]
fn a_stale_writer_gets_a_conflict() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("log.jsonl");
let mut one = Store::open(&path).unwrap();
let mut two = Store::open(&path).unwrap();
let opened = [Event::AccountOpened {
id: "a".into(),
owner: "ada".into(),
}];
// Both writers last saw an empty log (version 0).
one.append_checked(&path, 0, &opened).unwrap();
let err = two.append_checked(&path, 0, &opened).unwrap_err();
assert_eq!(
err,
Conflict {
expected: 0,
actual: 1
}
);
assert_eq!(Store::load(&path).unwrap().len(), 1);
}
#[test]
fn a_snapshot_plus_the_tail_equals_a_full_replay() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("log.jsonl");
let snap = dir.path().join("snapshot.json");
let mut store = Store::open(&path).unwrap();
let mut ledger = Ledger::default();
handle(&mut ledger, &mut store, cmd_open("a")).unwrap();
handle(
&mut ledger,
&mut store,
Command::Deposit {
id: "a".into(),
cents: 500,
},
)
.unwrap();
ledger.save_snapshot(&snap).unwrap();
handle(
&mut ledger,
&mut store,
Command::Deposit {
id: "a".into(),
cents: 250,
},
)
.unwrap();
let events = Store::load(&path).unwrap();
assert_eq!(
Ledger::from_snapshot(&snap, &events).unwrap(),
Ledger::replay(&events)
);
}The first confirms that a rejection stores nothing: the log holds one event after an open and a refused withdrawal. The second proves that old events stay loadable. The third and fourth cover concurrency and snapshots, discussed below. Then a property test checks the system-level invariants on random input:
use ledger::{Command, Ledger, Store, handle};
use proptest::prelude::*;
fn command() -> impl Strategy<Value = Command> {
let id = prop::sample::select(vec!["a", "b", "c"]).prop_map(String::from);
prop_oneof![
id.clone().prop_map(|id| Command::Open {
id,
owner: "o".into()
}),
(id.clone(), 0..500u64).prop_map(|(id, cents)| Command::Deposit { id, cents }),
(id.clone(), 0..500u64).prop_map(|(id, cents)| Command::Withdraw { id, cents }),
id.prop_map(|id| Command::Close { id }),
]
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(64))]
// Whatever sequence of commands arrives, the live state equals the state rebuilt from the log,
// and money is conserved: deposits minus withdrawals equals the sum of balances.
#[test]
fn live_state_equals_replayed_state(cmds in prop::collection::vec(command(), 0..40)) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("log.jsonl");
let mut store = Store::open(&path).unwrap();
let mut ledger = Ledger::default();
for cmd in cmds {
let _ = handle(&mut ledger, &mut store, cmd);
}
let events = Store::load(&path).unwrap();
let rebuilt = Ledger::replay(&events);
prop_assert_eq!(&rebuilt, &ledger);
let net: i128 = events.iter().map(|e| match e {
ledger::Event::Deposited { cents, .. } => *cents as i128,
ledger::Event::Withdrawn { cents, .. } => -(*cents as i128),
_ => 0,
}).sum();
let total: i128 = ledger.accounts.values().map(|a| a.balance as i128).sum();
prop_assert_eq!(net, total);
}
}test old_events_without_the_new_field_still_load ... ok
test a_stale_writer_gets_a_conflict ... ok
test rules_live_in_decide_and_a_rejection_records_nothing ... ok
test a_snapshot_plus_the_tail_equals_a_full_replay ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
test live_state_equals_replayed_state ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered outFor any sequence of up to forty commands over three account ids, two things hold. The live state equals the state rebuilt from the log. And money is conserved: the sum of deposits minus the sum of withdrawals equals the sum of all balances. The second property is an independent check that apply did not lose or invent money, written without reference to apply's logic. 64 random sequences ran in 1.77 seconds including the file writes; many commands in a random sequence are rejected, which is also intended, because rejected commands are half of what a real system sees. For property testing in general see property testing with proptest.
Changing events without breaking the log
The log is permanent, so the shape of an event can only grow in ways that old lines still parse. Adding a note to deposits shows both the trap and the fix. Suppose the Deposited variant gains a note: Option<String> field. Every place that constructs one must now supply it, and the compiler lists them:
error[E0063]: missing field `note` in initializer of `Event`
--> src/lib.rs:126:25
|
126 | Ok(vec![Event::Deposited {
| ^^^^^^^^^^^^^^^^ missing `note`That is a gift: the error is at the one place decide creates the event, not in a data migration three months later. The stored lines are a different matter. A line written before the field existed has no note, and without help serde would reject it. The attribute #[serde(default, skip_serializing_if = "Option::is_none")] on the field handles both directions: a missing field becomes None on load, and a None is left out when writing so new and old lines look the same. The test old_events_without_the_new_field_still_load parses a pre-change line and asserts the result.
The general rules: add fields with defaults; never rename or remove a field on a stored event; if the meaning of an event must change, introduce a new event type (DepositedV2) and keep handling the old one in apply. Upgrading stored events in place defeats the point of an immutable log.
Why apply must not enforce rules
A common mistake in the first version of an event-sourced system is to copy the validation into apply "for safety". Here is what that does. Suppose a rule limits a deposit to 1,000 cents, introduced after the account already holds a legitimate 5,000-cent deposit. Replaying the history with a strict apply:
use ledger::Event;
// A "safer" apply that re-checks business rules while replaying.
fn apply_strict(balance: &mut u64, event: &Event) -> Result<(), String> {
match event {
Event::Deposited { cents, .. } if *cents > 1_000 => Err(format!(
"deposit of {cents} exceeds the new 1000 cent limit"
)),
Event::Deposited { cents, .. } => {
*balance += cents;
Ok(())
}
_ => Ok(()),
}
}
fn main() {
// History recorded back when the limit was 10,000 cents. It really happened.
let history = [
Event::Deposited {
id: "a".into(),
cents: 400,
note: None,
},
Event::Deposited {
id: "a".into(),
cents: 5_000,
note: None,
},
Event::Deposited {
id: "a".into(),
cents: 100,
note: None,
},
];
let mut balance = 0;
for (i, e) in history.iter().enumerate() {
match apply_strict(&mut balance, e) {
Ok(()) => println!("event {i}: ok, balance {balance}"),
Err(why) => {
println!("event {i}: REPLAY FAILED: {why}");
break;
}
}
}
println!("the account can no longer be loaded: balance stuck at {balance}, true balance 5500");
}event 0: ok, balance 400
event 1: REPLAY FAILED: deposit of 5000 exceeds the new 1000 cent limit
the account can no longer be loaded: balance stuck at 400, true balance 5500The second event was valid when it happened and is invalid by today's rule, so the replay stops and the account cannot be loaded at all; the reported balance is stuck at 400 against a true balance of 5,500. The log is the truth, and a rule that did not exist when the fact occurred does not get to veto it. New rules apply to new commands, in decide. If old history needs correcting, record a compensating event (DepositReversed) as a new fact instead of rewriting the old one.
What replay costs, and what a snapshot buys
Replaying from the beginning is the standard objection to event sourcing, so measure it. The first number is the fold alone, over a million events already in memory:
in memory, 1,000,001 events, fold only: 6.8 ms
snapshot + 10,001 tail events (in memory): 0.1 msSix point eight milliseconds to apply a million events: the state transition is cheap. The cost that matters is reading the log from disk and parsing it:
use ledger::{Event, Ledger, Store};
use std::time::Instant;
fn main() {
let dir = std::env::temp_dir().join("ledger_file_cost.jsonl");
let _ = std::fs::remove_file(&dir);
let mut store = Store::open(&dir).unwrap();
let mut batch = vec![Event::AccountOpened {
id: "a".into(),
owner: "o".into(),
}];
for i in 0..1_000_000u64 {
batch.push(Event::Deposited {
id: "a".into(),
cents: i % 100 + 1,
note: None,
});
}
// Write in chunks so only a handful of fsyncs happen.
for chunk in batch.chunks(100_000) {
store.append(chunk).unwrap();
}
let size = std::fs::metadata(&dir).unwrap().len();
let t = Instant::now();
let events = Store::load(&dir).unwrap();
let parse_ms = t.elapsed().as_secs_f64() * 1000.0;
let t = Instant::now();
let ledger = Ledger::replay(&events);
let fold_ms = t.elapsed().as_secs_f64() * 1000.0;
println!(
"file: {} events, {:.1} MB",
events.len(),
size as f64 / 1_048_576.0
);
println!("parse JSON lines : {parse_ms:>7.1} ms");
println!("fold into state : {fold_ms:>7.1} ms");
println!("balance : {}", ledger.accounts["a"].balance);
let _ = std::fs::remove_file(&dir);
}file: 1000001 events, 39.0 MB
parse JSON lines : 262.9 ms
fold into state : 9.1 ms
balance : 50500000The 39 MB log took 262.9 ms to parse and 9.1 ms to fold, so loading is about 29 times more expensive than replaying, and almost all of it is JSON. A snapshot removes both: save the state with its version every so many events, and on startup load the snapshot and replay only the events after it. from_snapshot does exactly that, using ledger.version as the index of the first unseen event, and the test a_snapshot_plus_the_tail_equals_a_full_replay proves it gives the same answer as a full replay. In the in-memory benchmark, a snapshot plus a 10,001-event tail took 0.1 ms. For an on-disk log you would also store the byte offset of the snapshot so you can seek past the parsed prefix instead of reading it. Snapshot when startup time matters, not before: a snapshot is a cache, and a cache is a second thing that can be wrong.
Two writers
Everything so far assumes one process. With two, a race appears: both load version 3, both decide that a withdrawal is allowed, both append, and the account is overdrawn. Each decision was right for the state it saw. The fix is optimistic concurrency: every append states the version it decided against, and the store refuses it if the log has moved. append_checked implements it, and the a_stale_writer_gets_a_conflict test shows two stores starting from an empty log, with the second one refused:
Conflict { expected: 0, actual: 1 }The message of that error tells the caller what to do: reload, decide again against the new state, and retry. The check in this file-based version re-reads the log, so it is not safe against two writers appending in the same instant; a real store makes the check and the append one atomic operation, with a lock, a unique constraint on (stream, version) in a database, or a compare-and-swap. The Postgres JSONB layout does it with a unique index, and the outbox pattern covers publishing the events to other systems without losing any.
A second read model, and what a bug costs
The ledger above is one projection of the log. The same events can feed any number of others, each shaped for a different reader, and each disposable. A statement per account, with a running balance after every line, is a natural second one:
use ledger::Event;
use std::collections::BTreeMap;
/// A second read model over the same log: a running statement per account.
#[derive(Default, Debug)]
struct Statement {
lines: BTreeMap<String, Vec<(i64, String)>>, // account -> (balance after, description)
}
impl Statement {
fn apply(&mut self, e: &Event, fix_withdrawals: bool) {
let (id, delta, what) = match e {
Event::Deposited { id, cents, .. } => (id, *cents as i64, format!("deposit {cents}")),
Event::Withdrawn { id, cents } => {
// Version 1 of this projection forgot that a withdrawal lowers the balance.
let d = if fix_withdrawals { -(*cents as i64) } else { 0 };
(id, d, format!("withdraw {cents}"))
}
_ => return,
};
let rows = self.lines.entry(id.clone()).or_default();
let before = rows.last().map_or(0, |r| r.0);
rows.push((before + delta, what));
}
}
fn main() {
let log = [
Event::AccountOpened {
id: "a1".into(),
owner: "ada".into(),
},
Event::Deposited {
id: "a1".into(),
cents: 10_000,
note: None,
},
Event::Withdrawn {
id: "a1".into(),
cents: 2_500,
},
Event::Deposited {
id: "a1".into(),
cents: 300,
note: None,
},
];
for (label, fixed) in [("buggy projection", false), ("rebuilt after the fix", true)] {
let mut st = Statement::default();
for e in &log {
st.apply(e, fixed);
}
println!("{label}:");
for (balance, what) in &st.lines["a1"] {
println!(" {what:<14} -> balance {balance}");
}
}
}buggy projection:
deposit 10000 -> balance 10000
withdraw 2500 -> balance 10000
deposit 300 -> balance 10300
rebuilt after the fix:
deposit 10000 -> balance 10000
withdraw 2500 -> balance 7500
deposit 300 -> balance 7800Look at the first listing, from the first version of the projection, which forgot that a withdrawal lowers the balance. It shows a balance of 10,000 after the 2,500 withdrawal and 10,300 at the end, which is wrong by exactly 2,500 for every statement ever produced. In a system that stores state directly, that bug would be a data-repair project: find every affected row, work out what each should have been, write migrations and hope. Here the second listing is the whole repair. Fix apply, drop the projection and replay the log: the withdrawal line now reads 7,500 and the final balance is 7,800. The events were never wrong, only the interpretation of them, so correcting the interpretation corrects everything derived from it.
This is the benefit that is hardest to appreciate before you need it, and it comes with a corollary: the log must be right. A wrong event is a wrong fact, and the way to fix it is to append a correction, not to edit history. Treat the events the way an accountant treats a ledger: nothing is erased, errors are reversed by new entries, and the whole record can be audited afterwards.
Read models also let you serve queries that the write side could never support efficiently. A projection keyed by owner, a daily total, a fraud signal that looks at the last ten events per account: each is a fold with its own state, built when it is needed. Because projections are rebuilt from the log, deploying a new one is a replay, not a migration. The cost is that they lag the write side when updated asynchronously, so a user can write and then briefly not see their own change; the usual remedy is to read your own writes from the aggregate that just handled the command, and let the projections catch up.
Where the aggregate boundary goes
The ledger here holds every account in one BTreeMap, which is fine for a demonstration and wrong for production. Commands that concern one account should load only that account's events, and concurrency control should be per account, so a deposit to one customer does not conflict with a withdrawal from another. In event-sourcing vocabulary each account is an aggregate with its own stream of events and its own version. The change in the code is small: Store gains a stream id, Ledger shrinks to one Account and append_checked compares against that stream's version. The decision about what belongs in one stream is the hardest design choice in the whole approach. The test is the invariants: anything that must be checked atomically (a transfer that debits one account and credits another cannot be two independent streams) belongs together, or needs a process that coordinates the two and can compensate.
Putting it into production
The version above keeps everything in a file so the mechanism stays visible. A production system swaps the store for a database table with columns for the stream id, the version, the event type and a JSON payload, with a unique constraint on the stream and version, which makes the optimistic check atomic. It adds a consumer that reads new events in order and updates projections, with its own saved position so a restart resumes where it stopped. And it adds monitoring on the two numbers that reveal trouble early: the lag between the newest event and the newest projected event, and the rate of conflicts, since a rising conflict rate means writers are fighting over the same streams.
Habits
- Name events in the past tense, and make them carry everything needed to apply them without looking anything up.
- Keep
applytotal, pure and rule-free; keep rules indecide. - Write the log before updating memory.
- Test the invariants (replay equals live, conservation) with a property test.
- Version the schema by adding fields with defaults.
- Snapshot only when you measure a startup problem.
When this is the wrong design
If nobody will ever ask "how did it get here", the log is overhead, and a table with a current value is simpler to build, query and operate. Reads against a log need a projection, which means more code and eventual consistency. Deleting data is hard when the data is immutable, and rules like GDPR erasure need design (crypto-shredding, or keeping personal data out of events). And a team new to the idea should start with one aggregate where an audit trail is genuinely required; the ledger above is a fair candidate. A softer alternative, a normal table plus an audit table of changes, is covered in soft deletes and audit logs, and the read-side split that often accompanies event sourcing is in CQRS.


