Persist every state change as an immutable, ordered event in a per-entity stream, and treat that log as the only source of truth. Current state, read models and audit answers are all derived from it by replay. Snapshots bound the replay cost, and upcasters let old events be read in today's shape.
Most services store the current state of a thing and overwrite it on every change. Event sourcing reverses that. You store every change as an immutable event, and current state becomes a value you compute by replaying those events. This guide follows one invented service through the whole pattern. Larder is the inventory service for Basketline, a grocery delivery company. It lost stock updates, and then it could not answer a supplier's audit question. You will see how the event log, optimistic concurrency, snapshots and upcasters fit together. It also covers the parts interviewers push on: rebuild cost, projection lag, schema changes to events that can never be edited, and deleting personal data from a log that is append-only by design.
The problem
A situation where the obvious design starts to hurt.
Larder tracks stock for Basketline's 38 dark stores, about 11,000 SKUs each, so roughly 418,000 store-SKU pairs. At peak it handles around 2,400 stock changes a minute: picker scanners decrementing stock, receiving docks adding pallets, staff writing off damaged goods, and a 02:00 reconciliation job that writes absolute shelf counts.
The original design kept one stock_levels row per store and SKU with a qty column. The ORM did read-modify-write: load the row, subtract in application code, save. The reconciliation job overwrote qty with whatever the count sheet said. During a produce promotion, pickers and the nightly job overlapped and updates were silently lost. Store 17 showed 14 cartons of oat milk while the shelf was empty, and 312 orders in one week were accepted and then substituted or cancelled.
A few weeks later a dairy supplier disputed a credit note for 1,140 written-off yogurts. Finance asked which batches were written off, when, by whom, and why. Larder had the current qty and an updated_at timestamp, nothing else. A trigger-based audit table existed, but it had missed bulk updates from the reconciliation job, so nobody trusted it.
Adding a version column would have stopped the lost updates. It would not have recovered history, because history was a side effect that could drift from the truth. The team needed two things: no lost writes, and a history that is the data rather than a copy of it. The storefront also still had to read stock levels in single-digit milliseconds.
The solution
What the pattern proposes.
Each store-SKU pair becomes a stream with an id like store-17:sku-48213. Every change is appended to that stream as an event: StockReceived, ItemPicked, ItemWrittenOff or CountAdjusted. Each event has a per-stream version number and a schema number. The events table in Postgres is insert-only, with a UNIQUE constraint on (stream_id, version).
A command such as PickItem goes through four steps. The handler loads the stream's latest snapshot, replays only the events after it, checks the business rule (enough stock on hand), and appends the new event with expected_version set to the version it read. If another writer appended first, the unique constraint rejects the insert. The handler reloads and retries up to 3 times. This is the fix for lost updates. The reconciliation job no longer overwrites anything. It appends CountAdjusted, which records both the counted value and the moment it was counted.
Reads never replay. A projector tails the log by a global position column and maintains an available-stock view in Redis that the storefront reads. Because the view is derived, it can be dropped and rebuilt from position 0. A second consumer publishes write-offs to a topic that the finance ledger subscribes to.
Snapshots cap load cost. After the stream crosses each multiple of 200 events, the handler stores the folded state, tagged with a snapshot schema number. A load then replays at most 199 events. Snapshots are a disposable cache: if the fold logic changes, bump the schema and old snapshots are ignored.
Schema evolution happens on read. When ItemWrittenOff gained a reasonCode enum and a batchId, the 2.3 million existing v1 events with free-text reasons stayed untouched. An upcaster converts v1 to v2 in memory before the fold sees the event, so domain code only knows the current shape.
An everyday analogy
The same idea, outside software.
Think of a chess scoresheet. Nobody records the board after each move. Players write down the moves, and anyone can rebuild the position at move 37 by replaying from the opening. If two players claim different positions, the sheet settles it.
A photo of the board at move 40 is a snapshot. To see move 52, you start from the photo and replay twelve moves instead of fifty-two. If you doubt the photo, you throw it away and replay from the start, and you get the same answer.
Old scoresheets use descriptive notation such as P-K4, while modern ones use algebraic e4. Nobody rewrites historic games. A reader translates the old notation as they go, and that is what an upcaster does.
Structure
The pieces and how they relate.
Participants
- Event store
- An append-only table: global_position (bigserial), stream_id, version, type, schema, data (jsonb), recorded_at. It is the only source of truth. A UNIQUE (stream_id, version) constraint turns concurrent appends into a clean conflict instead of a lost update.
- Command handler
- Loads a stream, folds it into state, checks invariants such as no picking below zero, then appends new events at the version it read. It retries on version conflicts with a small attempt limit.
- Fold (apply function)
- A pure function from (state, event) to state. It must be deterministic and must never call the clock, the network or a random source, because the same events have to produce the same state on every replay.
- Snapshot store
- A cache of folded state at a version, tagged with a snapshot schema number. It is safe to delete at any time. Changing the fold logic means bumping the schema so stale snapshots are skipped.
- Upcaster
- Converts stored events from old schema versions into the current shape on read. Stored rows are never modified, and domain code only ever sees the latest shape.
- Projector
- Tails the log in global position order, updates read models such as the Redis stock view, and records its checkpoint. You can reset it to position 0 to rebuild a view or to create a new one.
Pseudocode
The solution to the scenario, language-neutral.
// Write path: PickItem(store 17, sku 48213, qty 3)
function handlePick(streamId, qty, orderId):
repeat up to 3 times:
(state, version) = load(streamId)
if state.onHand < qty: reject "insufficient stock"
event = ItemPicked{ qty, orderId } schema 1
try:
append(streamId, expectedVersion = version, [event])
return ok
catch VersionConflict:
continue // someone else appended; reload and re-decide
fail "too much contention"
function load(streamId):
snap = snapshots.get(streamId)
if snap exists and snap.schema == SNAPSHOT_SCHEMA:
state = snap.state; version = snap.version
else:
state = empty; version = 0
for raw in events where stream_id = streamId and version > version order by version:
state = apply(state, upcast(raw))
version = raw.version
return (state, version)
function append(streamId, expectedVersion, events):
INSERT rows with versions expectedVersion+1 .. expectedVersion+n
// UNIQUE(stream_id, version) violation => VersionConflict
if crossed a multiple of 200:
save snapshot(load(streamId), schema = SNAPSHOT_SCHEMA) // best effort
function upcast(event):
if event.type == ItemWrittenOff and event.schema == 1:
return { qty, reasonCode = classify(event.reason), batchId = null } schema 2
return event
// Read path, separate process
loop:
batch = events where global_position > checkpoint order by global_position limit 500
for e in batch: update stock view; if ItemWrittenOff: publish to stock-events
checkpoint = last position in batch // stored with the view updateThe code
The same solution in TypeScript, Python and PHP.
type EventData = Record<string, unknown>;
interface NewEvent { type: string; schema: number; data: EventData }
interface StoredEvent extends NewEvent { streamId: string; version: number }
interface StockState { onHand: number }
interface Snapshot { version: number; schema: number; state: StockState }
const SNAPSHOT_SCHEMA = 2;
class ConcurrencyError extends Error {}
class InMemoryEventStore {
private streams = new Map<string, StoredEvent[]>();
read(streamId: string, afterVersion: number): StoredEvent[] {
return (this.streams.get(streamId) ?? []).filter((e) => e.version > afterVersion);
}
// In Postgres a UNIQUE (stream_id, version) constraint enforces the same rule.
append(streamId: string, expectedVersion: number, events: NewEvent[]): number {
const stream = this.streams.get(streamId) ?? [];
if (stream.length !== expectedVersion) {
throw new ConcurrencyError(`${streamId}: expected v${expectedVersion}, found v${stream.length}`);
}
events.forEach((e, i) => stream.push({ ...e, streamId, version: expectedVersion + i + 1 }));
this.streams.set(streamId, stream);
return stream.length;
}
}
// v1 write-offs had a free-text reason; v2 has reasonCode and batchId.
function upcast(e: StoredEvent): StoredEvent {
if (e.type === "ItemWrittenOff" && e.schema === 1) {
const reason = String(e.data.reason ?? "").toLowerCase();
const reasonCode = reason.includes("expir") ? "EXPIRED" : reason.includes("damag") ? "DAMAGED" : "OTHER";
return { ...e, schema: 2, data: { qty: e.data.qty, reasonCode, batchId: null } };
}
return e;
}
function apply(s: StockState, e: StoredEvent): StockState {
const qty = Number(e.data.qty ?? 0);
switch (e.type) {
case "StockReceived":
return { onHand: s.onHand + qty };
case "ItemPicked":
case "ItemWrittenOff":
return { onHand: s.onHand - qty };
case "CountAdjusted":
return { onHand: Number(e.data.counted) };
default:
throw new Error(`unknown event type ${e.type}`);
}
}
class StockRepository {
private snapshots = new Map<string, Snapshot>();
constructor(private store: InMemoryEventStore, private snapshotEvery = 200) {}
load(streamId: string): { state: StockState; version: number } {
let state: StockState = { onHand: 0 };
let version = 0;
const snap = this.snapshots.get(streamId);
if (snap && snap.schema === SNAPSHOT_SCHEMA) {
state = { ...snap.state };
version = snap.version;
}
for (const raw of this.store.read(streamId, version)) {
state = apply(state, upcast(raw));
version = raw.version;
}
return { state, version };
}
append(streamId: string, expectedVersion: number, events: NewEvent[]): void {
const newVersion = this.store.append(streamId, expectedVersion, events);
const every = this.snapshotEvery;
if (Math.floor(newVersion / every) > Math.floor(expectedVersion / every)) {
const { state, version } = this.load(streamId);
this.snapshots.set(streamId, { version, schema: SNAPSHOT_SCHEMA, state });
}
}
}
function pickItem(repo: StockRepository, streamId: string, qty: number, orderId: string): void {
for (let attempt = 1; ; attempt++) {
const { state, version } = repo.load(streamId);
if (state.onHand < qty) throw new Error(`insufficient stock: ${state.onHand} < ${qty}`);
try {
repo.append(streamId, version, [{ type: "ItemPicked", schema: 1, data: { qty, orderId } }]);
return;
} catch (err) {
if (!(err instanceof ConcurrencyError) || attempt >= 3) throw err;
}
}
}
const store = new InMemoryEventStore();
const repo = new StockRepository(store, 3);
const id = "store-17:sku-48213";
repo.append(id, 0, [{ type: "StockReceived", schema: 1, data: { qty: 10, batchId: "B-9001" } }]);
// A legacy v1 event written before the schema change.
store.append(id, 1, [{ type: "ItemWrittenOff", schema: 1, data: { qty: 2, reason: "Expired batch" } }]);
pickItem(repo, id, 3, "ord-5521");
const { state, version } = repo.load(id);
console.log(`onHand=${state.onHand} version=${version}`); // onHand=5 version=3from __future__ import annotations
from dataclasses import dataclass, replace
from typing import Any
SNAPSHOT_SCHEMA = 2
class ConcurrencyError(Exception):
pass
@dataclass(frozen=True)
class NewEvent:
type: str
schema: int
data: dict[str, Any]
@dataclass(frozen=True)
class StoredEvent:
stream_id: str
version: int
type: str
schema: int
data: dict[str, Any]
@dataclass(frozen=True)
class StockState:
on_hand: int = 0
@dataclass(frozen=True)
class Snapshot:
version: int
schema: int
state: StockState
class InMemoryEventStore:
def __init__(self) -> None:
self._streams: dict[str, list[StoredEvent]] = {}
def read(self, stream_id: str, after_version: int) -> list[StoredEvent]:
return [e for e in self._streams.get(stream_id, []) if e.version > after_version]
# In Postgres a UNIQUE (stream_id, version) constraint enforces the same rule.
def append(self, stream_id: str, expected_version: int, events: list[NewEvent]) -> int:
stream = self._streams.setdefault(stream_id, [])
if len(stream) != expected_version:
raise ConcurrencyError(
f"{stream_id}: expected v{expected_version}, found v{len(stream)}"
)
for i, e in enumerate(events):
stream.append(
StoredEvent(stream_id, expected_version + i + 1, e.type, e.schema, e.data)
)
return len(stream)
# v1 write-offs had a free-text reason; v2 has reasonCode and batchId.
def upcast(e: StoredEvent) -> StoredEvent:
if e.type == "ItemWrittenOff" and e.schema == 1:
reason = str(e.data.get("reason", "")).lower()
code = "EXPIRED" if "expir" in reason else "DAMAGED" if "damag" in reason else "OTHER"
return replace(
e, schema=2, data={"qty": e.data["qty"], "reasonCode": code, "batchId": None}
)
return e
def apply(s: StockState, e: StoredEvent) -> StockState:
qty = int(e.data.get("qty", 0))
if e.type == "StockReceived":
return StockState(s.on_hand + qty)
if e.type in ("ItemPicked", "ItemWrittenOff"):
return StockState(s.on_hand - qty)
if e.type == "CountAdjusted":
return StockState(int(e.data["counted"]))
raise ValueError(f"unknown event type {e.type}")
class StockRepository:
def __init__(self, store: InMemoryEventStore, snapshot_every: int = 200) -> None:
self._store = store
self._snapshot_every = snapshot_every
self._snapshots: dict[str, Snapshot] = {}
def load(self, stream_id: str) -> tuple[StockState, int]:
state, version = StockState(), 0
snap = self._snapshots.get(stream_id)
if snap is not None and snap.schema == SNAPSHOT_SCHEMA:
state, version = snap.state, snap.version
for raw in self._store.read(stream_id, version):
state = apply(state, upcast(raw))
version = raw.version
return state, version
def append(self, stream_id: str, expected_version: int, events: list[NewEvent]) -> None:
new_version = self._store.append(stream_id, expected_version, events)
every = self._snapshot_every
if new_version // every > expected_version // every:
state, version = self.load(stream_id)
self._snapshots[stream_id] = Snapshot(version, SNAPSHOT_SCHEMA, state)
def pick_item(repo: StockRepository, stream_id: str, qty: int, order_id: str) -> None:
attempt = 0
while True:
attempt += 1
state, version = repo.load(stream_id)
if state.on_hand < qty:
raise ValueError(f"insufficient stock: {state.on_hand} < {qty}")
try:
repo.append(
stream_id, version, [NewEvent("ItemPicked", 1, {"qty": qty, "orderId": order_id})]
)
return
except ConcurrencyError:
if attempt >= 3:
raise
if __name__ == "__main__":
store = InMemoryEventStore()
repo = StockRepository(store, 3)
sid = "store-17:sku-48213"
repo.append(sid, 0, [NewEvent("StockReceived", 1, {"qty": 10, "batchId": "B-9001"})])
# A legacy v1 event written before the schema change.
store.append(sid, 1, [NewEvent("ItemWrittenOff", 1, {"qty": 2, "reason": "Expired batch"})])
pick_item(repo, sid, 3, "ord-5521")
state, version = repo.load(sid)
print(f"onHand={state.on_hand} version={version}") # onHand=5 version=3<?php
declare(strict_types=1);
const SNAPSHOT_SCHEMA = 2;
final class ConcurrencyError extends RuntimeException {}
final class InMemoryEventStore
{
/** @var array<string, list<array<string, mixed>>> */
private array $streams = [];
public function read(string $streamId, int $afterVersion): array
{
return array_values(array_filter(
$this->streams[$streamId] ?? [],
fn (array $e): bool => $e['version'] > $afterVersion
));
}
// In Postgres a UNIQUE (stream_id, version) constraint enforces the same rule.
public function append(string $streamId, int $expectedVersion, array $events): int
{
$stream = $this->streams[$streamId] ?? [];
if (count($stream) !== $expectedVersion) {
throw new ConcurrencyError(sprintf('%s: expected v%d, found v%d', $streamId, $expectedVersion, count($stream)));
}
foreach (array_values($events) as $i => $e) {
$stream[] = $e + ['streamId' => $streamId, 'version' => $expectedVersion + $i + 1];
}
$this->streams[$streamId] = $stream;
return count($stream);
}
}
// v1 write-offs had a free-text reason; v2 has reasonCode and batchId.
function upcast(array $e): array
{
if ($e['type'] === 'ItemWrittenOff' && $e['schema'] === 1) {
$reason = strtolower((string) ($e['data']['reason'] ?? ''));
$code = str_contains($reason, 'expir') ? 'EXPIRED' : (str_contains($reason, 'damag') ? 'DAMAGED' : 'OTHER');
$e['schema'] = 2;
$e['data'] = ['qty' => $e['data']['qty'], 'reasonCode' => $code, 'batchId' => null];
}
return $e;
}
function applyEvent(array $s, array $e): array
{
$qty = (int) ($e['data']['qty'] ?? 0);
return match ($e['type']) {
'StockReceived' => ['onHand' => $s['onHand'] + $qty],
'ItemPicked', 'ItemWrittenOff' => ['onHand' => $s['onHand'] - $qty],
'CountAdjusted' => ['onHand' => (int) $e['data']['counted']],
default => throw new UnexpectedValueException("unknown event type {$e['type']}"),
};
}
final class StockRepository
{
/** @var array<string, array{version:int, schema:int, state:array{onHand:int}}> */
private array $snapshots = [];
public function __construct(private InMemoryEventStore $store, private int $snapshotEvery = 200) {}
/** @return array{0: array{onHand:int}, 1: int} */
public function load(string $streamId): array
{
$state = ['onHand' => 0];
$version = 0;
$snap = $this->snapshots[$streamId] ?? null;
if ($snap !== null && $snap['schema'] === SNAPSHOT_SCHEMA) {
$state = $snap['state'];
$version = $snap['version'];
}
foreach ($this->store->read($streamId, $version) as $raw) {
$state = applyEvent($state, upcast($raw));
$version = $raw['version'];
}
return [$state, $version];
}
public function append(string $streamId, int $expectedVersion, array $events): void
{
$newVersion = $this->store->append($streamId, $expectedVersion, $events);
$every = $this->snapshotEvery;
if (intdiv($newVersion, $every) > intdiv($expectedVersion, $every)) {
[$state, $version] = $this->load($streamId);
$this->snapshots[$streamId] = ['version' => $version, 'schema' => SNAPSHOT_SCHEMA, 'state' => $state];
}
}
}
function pickItem(StockRepository $repo, string $streamId, int $qty, string $orderId): void
{
for ($attempt = 1; ; $attempt++) {
[$state, $version] = $repo->load($streamId);
if ($state['onHand'] < $qty) {
throw new DomainException("insufficient stock: {$state['onHand']} < {$qty}");
}
try {
$repo->append($streamId, $version, [
['type' => 'ItemPicked', 'schema' => 1, 'data' => ['qty' => $qty, 'orderId' => $orderId]],
]);
return;
} catch (ConcurrencyError $e) {
if ($attempt >= 3) {
throw $e;
}
}
}
}
$store = new InMemoryEventStore();
$repo = new StockRepository($store, 3);
$id = 'store-17:sku-48213';
$repo->append($id, 0, [['type' => 'StockReceived', 'schema' => 1, 'data' => ['qty' => 10, 'batchId' => 'B-9001']]]);
// A legacy v1 event written before the schema change.
$store->append($id, 1, [['type' => 'ItemWrittenOff', 'schema' => 1, 'data' => ['qty' => 2, 'reason' => 'Expired batch']]]);
pickItem($repo, $id, 3, 'ord-5521');
[$state, $version] = $repo->load($id);
echo "onHand={$state['onHand']} version={$version}\n"; // onHand=5 version=3When to use it
Situations where it pays off.
Auditors, finance or support regularly ask how an entity reached its current value, as with Larder's supplier write-off dispute.
With event sourcing the history is the primary data, not a trigger-maintained copy that can miss bulk updates. Questions like 'stock on 14 March at 09:00' become a replay up to a timestamp.
Several writers change the same entity concurrently and their intents differ, such as pickers decrementing and a reconciliation job setting absolute counts.
Appending intent-level events with an expected version makes conflicts explicit. CountAdjusted records that a count happened instead of silently replacing a value that a picker had just changed.
You expect to need read models you have not designed yet, such as shrinkage reports per supplier or per-batch expiry dashboards.
A new projector can replay the full log from position 0 and build the view as if it had existed from day one, without a backfill script that reverse-engineers old rows.
Domain events already drive downstream systems (finance, replenishment) and you are fighting dual-write bugs between the database and a message broker.
The event you persist is the event you publish. Consumers tail the same log, so there is no window in which the database says one thing and the broker says another.
Avoid it for simple CRUD data with no audit value, such as store opening hours or a user's UI preferences.
You pay for projections, snapshots, upcasters and eventual consistency on reads. If nobody will ever ask how a value changed, a plain row with a version column is cheaper and easier to operate.
How to implement it
Steps to introduce it in existing code.
Pick the stream boundary from your consistency rule. Larder's invariant (no negative stock) is per store and SKU, so each pair is one stream. Streams that are too large become contention hot spots, and streams that are too small cannot enforce the rule in a single append.
Name events as past-tense business facts that carry intent: ItemPicked with orderId, ItemWrittenOff with reasonCode and batchId. Avoid generic StockChanged{qty} events, because they lose the why that auditors need.
Create an insert-only events table with a global bigserial position, stream_id, version, type, schema and jsonb data. Add UNIQUE (stream_id, version), revoke UPDATE and DELETE from the application role, and index (stream_id, version).
Write the fold as a pure function and append with the version you read. On a unique-violation, reload and re-run the decision, at most 3 times, then return 409 so the scanner can prompt the picker.
Add snapshots once replay shows up in latency. Snapshot every N events (Larder uses 200), store a snapshot schema number, and treat snapshots as a cache that can be deleted and rebuilt.
Build projectors that read in global position order and store their checkpoint in the same transaction or write as the view update. That makes a crash replay the last batch idempotently instead of skipping it.
Evolve schemas additively. Add a new schema number and an upcaster from N-1 to N, and keep upcasters chained so v1 can reach v3. Deploy readers that understand the new version before any writer emits it.
Pros and cons
What you gain and what you pay.
Pros
- No lost updates: concurrent writers conflict on (stream_id, version) instead of overwriting each other.
- Complete, trustworthy history. Larder can answer the yogurt dispute by listing every ItemWrittenOff with batch, reason and timestamp.
- New read models are built by replay. A shrinkage-by-supplier report can be backfilled from the first event without guesswork.
- Bugs in derived views are recoverable. Fix the projector, reset its checkpoint and rebuild the view.
- The same events feed downstream systems, which removes the dual write between the database and the broker.
Cons
- Reads are eventually consistent. The storefront view trails the log by the projector's lag, typically under a second but unbounded if the projector stalls.
- Events are effectively forever, so a bad event design is expensive. You carry its upcasters for the life of the system.
- Deleting personal data conflicts with an immutable log and needs a deliberate design such as crypto-shredding.
- More moving parts than a CRUD table: projectors, checkpoints, snapshots, upcasters, and rebuild runbooks that need testing.
- Queries across streams, such as all SKUs below 5 units, are impossible on the log itself and need a projection.
Trade-offs
Decisions you'll have to make, each with its price.
Stream per store+SKU instead of one stream per store
You gainConflicts only occur between writers on the same item. About 418,000 independent streams means 40 appends a second rarely collide.
You payNo single append can enforce a rule across SKUs, such as a store-wide cap on chilled items. Rules like that need a saga or a separate aggregate.
Snapshot every 200 events instead of on every append
You gainSnapshot writes are 0.5% of appends, and a load replays at most 199 events, which keeps p99 load time low on hot SKUs.
You payCold loads of long streams still replay up to 199 events. A smaller interval like 50 cuts replay but quadruples snapshot writes and storage churn.
Upcast old events on read instead of rewriting the log
You gainStored events stay immutable and auditable, and a bad upcaster is fixed by deploying new code with no data migration.
You payEvery read of a v1 event pays the conversion, and upcaster chains (v1 to v2 to v3) build up as code you can never delete while v1 rows exist.
Asynchronous projector instead of updating the view in the append transaction
You gainAppends stay a single-row insert, and a slow or broken Redis cannot block picking.
You payThe storefront can show stock that was just picked. Lag is usually under a second, so Larder keeps the authoritative check in the PickItem handler, not in the view.
Postgres events table instead of a dedicated event store product
You gainThe team already runs Postgres, gets transactional appends with UNIQUE (stream_id, version), and can use SQL for ad-hoc audits.
You payYou build subscriptions, checkpointing and gap handling yourself, and the table grows by roughly 3.5 million rows a day at Larder's peak rate, so partitioning by month is needed.
How it fails
What goes wrong in production and how to prevent it.
Projector skips events because bigserial global positions commit out of order: position 1001 becomes visible before 1000.
What to doWhen the projector sees a gap, it waits a short time (Larder uses 500 ms) before moving past it. Alternatively, read only rows whose transaction is older than the oldest running transaction, using pg_snapshot_xmin, so in-flight inserts cannot be skipped.
A fold-logic fix deploys, but cached snapshots still contain state computed by the old, buggy logic.
What to doBump SNAPSHOT_SCHEMA in the same change. Loads ignore mismatched snapshots and replay from version 0, and new snapshots are written at the next 200-event boundary. Watch load latency during rollout, because hot streams will replay in full once.
During a rolling deploy, a new instance writes ItemWrittenOff schema 3 and an old instance throws on the unknown version.
What to doShip in two releases. First deploy readers that understand v3 and the upcaster to it. Only then enable writers that emit v3. CI fixtures should include a stored sample of every historical event version.
A hot stream (bananas at store 4 during the morning peak) causes repeated version conflicts and pickers see 409 errors.
What to doKeep retries tight at 3 attempts with 10 to 30 ms jitter, and make the decision cheap by snapshotting hot streams more often. If conflicts persist, split the stock into location-level streams (shelf versus back room) so writers touch different streams.
A data subject requests erasure, but picker names are stored in millions of immutable events.
What to doStore only a picker id in events and keep personal details in a separate, mutable table. Where personal data must sit in events, encrypt it with a per-person key and delete the key on request (crypto-shredding). Then rebuild projections.
Rebuilding the stock view from position 0 takes hours as the log grows, extending outages after projector bugs.
What to doRebuild into a new Redis key prefix in parallel while the old view keeps serving, then switch atomically. Partition the events table by month, and add a periodic closing-balance projection so new projectors can start from a checkpoint.
In a system design interview
When to bring it up and how to explain it.
Bring it up when the prompt involves audit trails, money or stock movements, disputes about how a value got to where it is, or lost updates from concurrent writers. Also use it when the interviewer hints that read models will change over time. Skip it for simple CRUD where history has no value.
What you could say
In the inventory service, I'd make an append-only event log the source of truth instead of a mutable quantity column. Each store-SKU pair is a stream, and changes are events like ItemPicked, StockReceived, ItemWrittenOff and CountAdjusted. To handle a pick, I load the stream, fold it into current stock, check there's enough, and append with the version I read. A unique constraint on stream id and version turns a race into a conflict I can retry, so we never silently lose an update again. Reads don't replay anything. A projector tails the log by global position and keeps a Redis view for the storefront, which I can rebuild from zero if it's ever wrong. To keep loads fast, I snapshot every 200 events and tag each snapshot with a schema number so I can invalidate them when the fold logic changes. Old events are never rewritten. When the write-off event gained a reason code and batch id, an upcaster converts v1 events on read. The payoff is that finance's question about which yogurt batches were written off, and when, becomes a query instead of a guess.
Likely follow-ups
The storefront shows 2 in stock but the pick fails. Is that a bug?
No, it's expected eventual consistency. The view lags the log, usually by under a second. The PickItem handler checks against the stream itself, so it is authoritative. I'd surface lag as a metric with an alert above 5 seconds, and have the app handle a 409 by refreshing availability.
How do you change an event's shape when you have millions of them stored?
Add a new schema version and an upcaster from the old one, deployed to readers before any writer emits the new version. I only consider copy-and-transform into a new stream for a major restructuring, and I'd keep the old stream for audit.
How big can a stream get before you need snapshots?
I'd measure rather than guess. With small JSON events, a few hundred is one cheap range read. The trigger is p99 load latency on the hottest streams, which for us are fast-moving produce SKUs with thousands of events a month.
How do you avoid double-counting a pick when the scanner retries?
Each pick carries orderId and line number as an idempotency key. Before appending, the handler checks whether that key already appears in the stream since the last snapshot, or it keeps a small dedup set in the folded state, and returns the original result if so.
Relations with other guides
Patterns it's often confused or combined with.
- CQRS: Separate Write and Read Models with Projections
Event sourcing almost always comes with CQRS. Commands append to streams, and every query is served by a projection. CQRS works without event sourcing, but event sourcing without separate read models is rarely practical.
- Transactional Outbox: Commit State and Events Together
With event sourcing the event table already acts as the outbox, because publishers tail it. Use a separate outbox only if you keep state-based tables and want events as a by-product.
- Change Data Capture: Stream Database Changes from the Log
CDC streams row changes from a state-based database. It gives you changes after the fact, but not business intent such as why stock dropped. Event sourcing records intent as the primary data.
- Memento Pattern: Save and Restore State Without Exposing It
A snapshot is a memento of an aggregate's folded state at a known version. It is used to skip replay and can always be thrown away and regenerated from the log.
- Idempotency Keys: Making Retried Writes Safe
Scanners retry on flaky Wi-Fi. Carrying an idempotency key such as orderId plus line in ItemPicked lets the handler detect a duplicate pick already in the stream and avoid appending it twice.
- Command Pattern: Turn Requests into Objects You Can Queue and Undo
Commands like PickItem express a request that may be rejected. Events like ItemPicked are facts that already happened. Keeping the two apart is central to a clean event-sourced design.
Common questions
Short answers to the usual doubts.
Is event sourcing the same as publishing events to Kafka?
No. Event sourcing means the events are the system of record and state is derived from them. Publishing events from a state-based service is event-driven architecture, where the database row is still the truth. Kafka is also a weak primary store for event sourcing, because it cannot reject an append when a stream's version has moved on. Larder keeps the log in Postgres and publishes from it.
How do I query 'all SKUs below 5 units' if state is only in streams?
You don't query the log for that. A projector maintains a table or index shaped for the question, for example a Postgres table keyed by store and SKU with on_hand indexed. Cross-stream queries always go to projections, which is why event sourcing and CQRS usually come together.
Do I ever edit or delete an event?
Not as routine. Mistakes are corrected with compensating events such as CountAdjusted or a reversal event, so the history shows both the error and the fix. The exceptions are legal erasure, usually handled by crypto-shredding, and very rare log migrations that copy the stream into a new, transformed stream.
When should I add snapshots?
When measured load time hurts, not on day one. With Larder's event sizes, replaying a few hundred events is a single index range scan of a few hundred kilobytes at most. Snapshots matter for streams that reach thousands of events, like fast-moving produce SKUs that see around 3,000 picks a month.
What goes in an event payload: the change or the resulting state?
The change and its intent, such as qty 3, orderId ord-5521, picker id. Do not store the resulting onHand in the event, because that duplicates derived state and becomes wrong if the fold logic is ever corrected. Include enough context that a future projector can answer questions you haven't thought of yet.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- An event platform for 10 teamsSolve the exercise