Article · Event Sourcing · CQRS
Event sourcing: store the facts, not just the latest state
State as a sequence of immutable events: streams, rehydration by folding, optimistic concurrency, projections, snapshots and event versioning. An aggregate and an event store in C# (Marten), TypeScript, Java, Go and Python.
"Where did my points go?" asks Mr Zdzisio, a regular at Halina's pierogi place. The database only shows balance = 40. Nobody knows whether the points expired, whether someone redeemed them, or whether there was a bug during a refund. Event sourcing answers such questions by definition: instead of overwriting state, the system records every change as an immutable event and computes the current state by replaying the history.
- 2005
- the "Event Sourcing" pattern write-up – Martin Fowler, a continuation of the PoEAA catalogue
- 6M
- orders per second at LMAX – one thread, logic rebuilt from events (Fowler, 2011)
- 0
- UPDATEs and DELETEs on events – the event store is append-only
Context and forces
- Audit and disputes – the loyalty programme is about the customer's money; you need to be able to show where every point came from.
- Questions about the past – "how many points did Zdzisio have on Christmas Eve?" or "what if the promotion had lasted longer?".
- New views from existing data – marketing wants a report nobody thought of when the tables were designed.
- Integration through events – other modules and services need to know what happened anyway.
Banking and accounting have done this for centuries: an account balance is the result of postings, and a mistake isn't erased with a rubber but corrected with another posting. Martin Fowler described the pattern in 2005, and Greg Young popularised it together with CQRS and the EventStoreDB database (now KurrentDB).
Structure
| Concept | Meaning |
|---|---|
| Event | A fact from the past, in the past tense, immutable: PointsRedeemed(reward, 300) |
| Stream | The ordered events of one aggregate, e.g. loyalty-<id>; the position in it is the version |
| Rehydration | Rebuilding the state by applying (folding) all events in the stream |
| Expected version | A condition on append: "append if the stream is still at version 12" – optimistic concurrency |
| Projection | A process that reads events and builds a read model from them; it can be rebuilt from scratch |
| Snapshot | Saved state after N events, so thousands of events needn't be replayed on every read |
A good way to see the idea is the stream of a single account – this is the history that was missing when Mr Zdzisio asked:
- 1 March AccountOpened – Zdzisio opens an account in the app, balance 0.
- 3 March PointsEarned +85 – An order of 20 ruskie and 10 blueberry pierogi.
- 17 March PointsEarned +120 – Catering for his granddaughter's birthday.
- 2 April Attempt to redeem 300 pts – Rejected by the rule (balance 205) – no event is recorded.
- 20 April PointsEarned +140 – More orders, balance 345.
- 21 April PointsRedeemed −300 – A free portion of 10 ruskie, balance 45.
- 1 July PointsExpired −5 – Points older than a year expire under the terms – balance 40.
What it looks like in code
The aggregate has two functions: apply/evolve (how an event changes the state) and decide (which events follow from a command in a given state). Both are pure and are tested without a database: "given these events, after this command I expect these events".
An aggregate rebuilt from events
// Events are facts in the past tense. They are the source of truth.
public abstract record LoyaltyEvent;
public sealed record AccountOpened(Guid CustomerId, DateTimeOffset At) : LoyaltyEvent;
public sealed record PointsEarned(Guid OrderId, int Points, DateTimeOffset At) : LoyaltyEvent;
public sealed record PointsRedeemed(string Reward, int Points, DateTimeOffset At) : LoyaltyEvent;
public sealed record PointsExpired(int Points, DateTimeOffset At) : LoyaltyEvent;
public sealed class LoyaltyAccount
{
public Guid Id { get; private set; }
public int Balance { get; private set; }
public int Version { get; private set; } // number of events applied so far
// State = left fold of all events. No setters, no ORM mapping.
public static LoyaltyAccount Rehydrate(Guid id, IEnumerable<LoyaltyEvent> history)
{
var account = new LoyaltyAccount { Id = id };
foreach (var e in history) account.Apply(e);
return account;
}
// Decide: check the rules against the current state and return NEW events (nothing is mutated yet).
public IReadOnlyList<LoyaltyEvent> Redeem(string reward, int cost, DateTimeOffset now) =>
Balance >= cost
? [new PointsRedeemed(reward, cost, now)]
: throw new InvalidOperationException($"Balance {Balance} is lower than {cost}.");
public void Apply(LoyaltyEvent e)
{
Balance = e switch
{
AccountOpened => 0,
PointsEarned x => Balance + x.Points,
PointsRedeemed x => Balance - x.Points,
PointsExpired x => Balance - x.Points,
_ => Balance
};
Version++;
}
}// Events are facts in the past tense. They are the source of truth.
export type LoyaltyEvent =
| { type: "AccountOpened"; customerId: string; at: string }
| { type: "PointsEarned"; orderId: string; points: number; at: string }
| { type: "PointsRedeemed"; reward: string; points: number; at: string }
| { type: "PointsExpired"; points: number; at: string };
export interface LoyaltyState {
balance: number;
version: number;
}
// evolve: (state, event) -> state. State is a left fold of the whole stream.
export const evolve = (s: LoyaltyState, e: LoyaltyEvent): LoyaltyState => {
switch (e.type) {
case "AccountOpened": return { balance: 0, version: s.version + 1 };
case "PointsEarned": return { balance: s.balance + e.points, version: s.version + 1 };
case "PointsRedeemed":
case "PointsExpired": return { balance: s.balance - e.points, version: s.version + 1 };
}
};
export const rehydrate = (events: LoyaltyEvent[]): LoyaltyState =>
events.reduce(evolve, { balance: 0, version: 0 });
// decide: (command, state) -> new events. Pure function, trivially testable.
export function redeem(state: LoyaltyState, reward: string, cost: number, now: Date): LoyaltyEvent[] {
if (state.balance < cost) throw new Error(`Balance ${state.balance} is lower than ${cost}`);
return [{ type: "PointsRedeemed", reward, points: cost, at: now.toISOString() }];
}public sealed interface LoyaltyEvent permits AccountOpened, PointsEarned, PointsRedeemed, PointsExpired {}
public record AccountOpened(UUID customerId, Instant at) implements LoyaltyEvent {}
public record PointsEarned(UUID orderId, int points, Instant at) implements LoyaltyEvent {}
public record PointsRedeemed(String reward, int points, Instant at) implements LoyaltyEvent {}
public record PointsExpired(int points, Instant at) implements LoyaltyEvent {}
public final class LoyaltyAccount {
private int balance;
private int version;
public static LoyaltyAccount rehydrate(List<LoyaltyEvent> history) {
var account = new LoyaltyAccount();
history.forEach(account::apply); // state = fold of events
return account;
}
public List<LoyaltyEvent> redeem(String reward, int cost, Instant now) {
if (balance < cost) throw new IllegalStateException("Balance " + balance + " is lower than " + cost);
return List.of(new PointsRedeemed(reward, cost, now)); // decide, don't mutate
}
public void apply(LoyaltyEvent e) {
balance = switch (e) { // exhaustive thanks to the sealed interface
case AccountOpened o -> 0;
case PointsEarned p -> balance + p.points();
case PointsRedeemed r -> balance - r.points();
case PointsExpired x -> balance - x.points();
};
version++;
}
public int balance() { return balance; }
public int version() { return version; }
}package loyalty
import (
"fmt"
"time"
)
// Event is a fact in the past tense; concrete types below.
type Event interface{ isEvent() }
type AccountOpened struct {
CustomerID string
At time.Time
}
type PointsEarned struct {
OrderID string
Points int
At time.Time
}
type PointsRedeemed struct {
Reward string
Points int
At time.Time
}
func (AccountOpened) isEvent() {}
func (PointsEarned) isEvent() {}
func (PointsRedeemed) isEvent() {}
type Account struct {
Balance int
Version int
}
// Rehydrate folds the stream into the current state.
func Rehydrate(history []Event) Account {
var a Account
for _, e := range history {
a.Apply(e)
}
return a
}
func (a *Account) Apply(e Event) {
switch ev := e.(type) {
case AccountOpened:
a.Balance = 0
case PointsEarned:
a.Balance += ev.Points
case PointsRedeemed:
a.Balance -= ev.Points
}
a.Version++
}
// Redeem decides which events should happen; it does not mutate the account.
func (a Account) Redeem(reward string, cost int, now time.Time) ([]Event, error) {
if a.Balance < cost {
return nil, fmt.Errorf("balance %d is lower than %d", a.Balance, cost)
}
return []Event{PointsRedeemed{Reward: reward, Points: cost, At: now}}, nil
}from dataclasses import dataclass, replace
from datetime import datetime
from functools import reduce
# Events are facts in the past tense. They are the source of truth.
@dataclass(frozen=True)
class AccountOpened:
customer_id: str
at: datetime
@dataclass(frozen=True)
class PointsEarned:
order_id: str
points: int
at: datetime
@dataclass(frozen=True)
class PointsRedeemed:
reward: str
points: int
at: datetime
@dataclass(frozen=True)
class Account:
balance: int = 0
version: int = 0
def evolve(state: Account, event) -> Account:
match event:
case AccountOpened():
return Account(balance=0, version=state.version + 1)
case PointsEarned(points=p):
return replace(state, balance=state.balance + p, version=state.version + 1)
case PointsRedeemed(points=p):
return replace(state, balance=state.balance - p, version=state.version + 1)
return state
def rehydrate(history: list) -> Account:
return reduce(evolve, history, Account())
def redeem(state: Account, reward: str, cost: int, now: datetime) -> list:
if state.balance < cost:
raise ValueError(f"Balance {state.balance} is lower than {cost}")
return [PointsRedeemed(reward=reward, points=cost, at=now)]The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Event evolution and personal data
- Trade-offs
- Adoption path
- In practice
- Anti-patterns
- Related topics
- Test yourself