Skip to content

Event Sourcing & CQRS ​

“Capture all changes to an application state as a sequence of events.” — Martin Fowler, Event Sourcing

Summary: Event sourcing stores the facts that changed a system and derives state from them; CQRS separates the model that changes data from the model that answers questions. Focus: A correct event store (streams, expected version, commit-ordered global position, receipts), replay and snapshots, projections with checkpoints and safe rebuilds, versioning, and what brokers can and cannot do. Learning goal: Build and operate an event-sourced write model and its read models without losing, duplicating or misordering events, and know when neither pattern is worth its cost.

This chapter owns the event store and everything derived from it. Event-driven architecture owns the difference between event notification, event-carried state transfer and event sourcing as integration styles; the outbox pattern owns reliable publishing from ordinary tables; change data capture owns log-based capture; stream processing owns windows and watermarks. Here the database is the system of record and brokers are transport.

Page map ​

Looking forGo to
What an event store must guaranteeEvent store and streams
Why two writers cannot both append version 8Expected version
Why a bigserial cursor loses eventsGlobal position
Faster loading of long streamsReplay and snapshots
Read models, checkpoints and driftProjections
Rebuilding a read model without downtimeRebuilds
Changing an event's shape after it was storedVersioning and upcasting
CQRS on one database, without eventsCQRS
"I saved it, why is the list still old?"Read-your-writes
Retrying a command whose COMMIT timed outCommand receipts
Fixing a wrong eventCorrections
Deleting personal data from an immutable logPrivacy and erasure
Kafka compaction as an event storeLog compaction
RabbitMQ, Kafka, Redis Streams specificsBroker differences
When not to do any of thisChoosing

Everything in one minute ​

TermPlain wordsTiny exampleFailure if misunderstood
EventA fact in past tenseMoneyWithdrawn{amount: 30}Storing commands as events replays intentions, not outcomes
StreamAll events of one aggregateacc-42 versions 1..17Cross-stream invariants silently unchecked
Expected version"Append only if the stream is still at v"expected 17, store at 18: rejectTwo withdrawals both pass the balance check
Global positionOrder of all events in commit order811, 812, 813 with no gapsProjector skips an event that committed late
ReplayFold events from the start to rebuild state17 events → balance 70Replay triggers e-mails again
SnapshotCached fold up to a versionstate at v1000 + tailSnapshot of unsaved state becomes "truth"
ProjectionCode that turns events into a read modelaccount_balances rowsCheckpoint advances past a failed event
UpcasterConverts old event shapes on readv1 amount_cents → v2 amountOld events crash new code, or are misread
Command receiptStored answer for a command IDretry returns version 18 againTimeout + retry withdraws twice
Compensating eventA new fact that reverses an old oneWithdrawalReversedEditing history destroys the audit trail
PatternRequiresDoes not requireTypical cost
CQRSSeparate command and query modelsEvents, brokers, separate databases, eventual consistencyTwo models to keep consistent
Event sourcingEvents as the system of record, replayable foldCQRS, a broker, microservicesVersioning, projections, erasure design
Both togetherProjections build query models from the event storeKafkaAsynchronous read models and rebuild operations

Where it comes from ​

Martin Fowler's 2005 article names the pattern and lists what it buys: a complete rebuild of state by re-running the log, temporal queries ("what was the state on 5 December?"), and event replay to fix the past. The same article already warns about external systems: replay must not resend messages, so gateways must know when they are in replay mode, and results of external queries (an exchange rate on a given date) must be remembered for a faithful replay.

Greg Young's CQRS Documents (2010, his own class manual) describes CQRS as splitting one object into a command side and a query side, building on Bertrand Meyer's Command–Query Separation, and pairs it with event sourcing: an append-only event log, optimistic concurrency on the expected version of a stream, rolling snapshots as a loading heuristic, and reversal transactions instead of deletes. Fowler's 2011 CQRS bliki adds the caution that most systems fit a CRUD model and that CQRS should be used in specific bounded contexts, not across a whole system; it also notes that the command and query models may share one database.

Products followed: EventStoreDB, now KurrentDB, is a database built around streams with an expected-revision check on append; Marten turns PostgreSQL into a document and event store for .NET; Axon Framework provides aggregates, event processors and snapshotting on the JVM; spatie/laravel-event-sourcing brings aggregates, projectors and reactors to Laravel. None of them is required to apply the patterns; this chapter builds the store on PostgreSQL directly.

Why it exists ​

A current-state table answers "what is the balance?" cheaply and correctly. It cannot answer "why", "in which order", or "what did we believe last Tuesday", unless a separate audit trail is written and kept consistent with it.

Current-state storage (CRUD)Event sourcing
One row per entity, updated in placeOne immutable row per fact, appended
Simple queries, mature toolingQueries need projections or a fold
History is optional and can disagree with stateHistory is the state; current state is derived
A bug corrupts the row; the old value is goneA bug corrupts a projection; rebuild it from the log
Schema migration rewrites rowsOld events stay; readers upcast them
Deleting data is a DELETEErasure needs design (crypto-shredding, retention)

Everyday picture, reused below: a ledger book at a small shop. The clerk never rubs out a line; a mistake gets a new correcting line. The "balance" written at the bottom of a page is a convenience (a snapshot), and the weekly report pinned on the wall is a projection that can be rewritten from the book at any time. Two clerks writing in the same book need a rule: you may write line 18 only if the last line is still 17.

Three misunderstandings up front:

  1. CQRS does not imply event sourcing, a broker or eventual consistency. A query model can be a SQL view or a table updated in the same transaction.
  2. Event sourcing is not "publish events to Kafka". The store must check the expected version and give a gap-free order; a broker topic does neither for you.
  3. Immutable does not mean undeletable. Retention, key destruction and stream deletion exist; they must be designed, and they do not by themselves make a system compliant with any law.

What it is really about ​

Three functions and two guarantees. decide(state, command) → events checks invariants; evolve(state, event) → state folds facts deterministically; project(event) → read model change builds query models. The store guarantees that an append for stream s succeeds only at the expected version, and that every committed event gets a global position that readers can follow without ever missing one.

Write side (commands)Read side (queries)Clientcommand + command_idexpected_versionExecutelock allocatorreceipt? load, decidePostgreSQL event storefeed_allocator (1 row)streams (head version)events (append-only)command_receiptssnapshotsTXResultversion + position tokenRelay (at least once)checkpoint per brokerRabbitMQ / Kafka /Redis Streamstransport, not the storeProjectorcheckpoint FOR UPDATErows + checkpoint, one TXfeed by global_positionRead modelbalances_v1, balances_v2active_projectionsQueryatLeast = tokenelse staletokenCQRS without event sourcing replaces the event store with ordinary tables; the split of models stays.

The write path is one database transaction: lock the feed allocator, check the command receipt, fold the stream, decide, compare-and-set the stream head, insert events, advance the allocator, store the receipt, commit. The read path is asynchronous: a projector reads the feed after its checkpoint and updates rows and checkpoint in one transaction. Relays copy the same feed to brokers for other services.

Concept catalogue ​

Event store and streams Must-know ​

In plain words: An event store is an append-only table of facts, grouped into streams, where each stream is the history of one thing.

Common misunderstanding: "Any log is an event store." A log that cannot reject a conflicting append, or cannot be read per stream in order, is a transport, not a store of record.

Definition: A stream is an ordered sequence of events for one aggregate (an account, an order), numbered 1, 2, 3 without gaps. The event store provides atomic append of one or more events to one stream at an expected version, ordered reads of a stream, and an ordered read of all streams (the global feed). It is append-only: events are never updated; the PostgreSQL schema below enforces that with triggers.

text
1 Client -> Execute: withdraw 30 from acc-42, command_id c-77
2 Execute -> events: SELECT ... WHERE stream_id = 'acc-42' ORDER BY stream_version
3 Execute -> fold: v1 AccountOpened, v2 MoneyDeposited 100 -> balance 100
4 Execute -> decide: 30 <= 100 -> MoneyWithdrawn{30}
5 Execute -> events: INSERT stream_version 3, global_position 812

Real scenarios: a wallet whose disputes need the exact sequence of debits; an order whose state machine must be auditable; a booking system that must answer "who held seat 14C at 10:02"; a compliance team asking for what the system knew at a given time.

ProductStream conceptAppend checkGlobal order
PostgreSQL (this chapter)stream_id + stream_versionCAS on streams.version, UNIQUE (stream_id, stream_version)global_position assigned under a row lock
KurrentDB (EventStoreDB)Named stream with revisionstreamState: any, no_stream, stream_exists, or exact revision$all stream
Marten (PostgreSQL, .NET)Stream id + versionOptimistic version check on appendEvent sequence plus high water mark
Axon FrameworkAggregate event streamFramework-managed; not covered by the pages read hereTracking token for streaming event processors
KafkaKey within a partitionNonePer partition only
Redis StreamsOne key per streamExplicit IDs must increase; no version checkPer key only

How to use it: keep one stream per consistency boundary, keep streams short when you can (model time: one stream per account per year is a valid design), and put cross-stream rules in a saga or a dedicated stream. The schema:

sql
-- PostgreSQL event store, read model and checkpoints for the Go and Laravel snippets.
-- Run once in an empty schema. Amounts are integer minor units of one currency per account.

CREATE TABLE feed_allocator (
    id            smallint PRIMARY KEY CHECK (id = 1),
    next_position bigint   NOT NULL CHECK (next_position >= 1)
);
INSERT INTO feed_allocator (id, next_position) VALUES (1, 1);

CREATE TABLE streams (
    id      text   PRIMARY KEY,
    version bigint NOT NULL CHECK (version >= 1)
);

CREATE TABLE events (
    global_position bigint      PRIMARY KEY,              -- assigned under the allocator row lock
    event_id        text        NOT NULL UNIQUE,
    stream_id       text        NOT NULL REFERENCES streams (id),
    stream_version  bigint      NOT NULL CHECK (stream_version >= 1),
    type            text        NOT NULL,
    schema_version  int         NOT NULL CHECK (schema_version >= 1),
    data            jsonb       NOT NULL,
    command_id      text        NOT NULL,
    occurred_at     timestamptz NOT NULL,                 -- event time: when it happened in the business
    recorded_at     timestamptz NOT NULL DEFAULT now(),   -- processing time: when the store accepted it
    UNIQUE (stream_id, stream_version)                    -- backstop for the expected-version check
);

-- Append-only at the database level, not just by convention.
CREATE FUNCTION events_append_only() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
    RAISE EXCEPTION 'events is append-only' USING ERRCODE = 'insufficient_privilege';
END $$;
CREATE TRIGGER events_no_update BEFORE UPDATE OR DELETE ON events
    FOR EACH ROW EXECUTE FUNCTION events_append_only();
CREATE TRIGGER events_no_truncate BEFORE TRUNCATE ON events
    FOR EACH STATEMENT EXECUTE FUNCTION events_append_only();

-- One row per accepted command: answers retries whose first COMMIT outcome was unknown.
CREATE TABLE command_receipts (
    command_id     text        PRIMARY KEY,
    stream_id      text        NOT NULL,
    fingerprint    text        NOT NULL,                  -- SHA-256 of the command intent
    stream_version bigint      NOT NULL,
    last_position  bigint      NOT NULL,
    recorded_at    timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE snapshots (
    stream_id text        PRIMARY KEY REFERENCES streams (id),
    version   bigint      NOT NULL,
    format    int         NOT NULL,                       -- bump when the state shape or fold logic changes
    state     jsonb       NOT NULL,
    taken_at  timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE projection_checkpoints (
    projection text        PRIMARY KEY,                   -- e.g. balances_v1, balances_v2, relay:kafka
    position   bigint      NOT NULL DEFAULT 0,
    updated_at timestamptz NOT NULL DEFAULT now()
);

-- Several projection versions live side by side; readers follow active_projections.
CREATE TABLE account_balances (
    projection       text        NOT NULL REFERENCES projection_checkpoints (projection),
    account_id       text        NOT NULL,
    currency         char(3)     NOT NULL,
    balance          bigint      NOT NULL CHECK (balance >= 0),
    stream_version   bigint      NOT NULL,
    last_occurred_at timestamptz NOT NULL,
    PRIMARY KEY (projection, account_id)
);

CREATE TABLE active_projections (
    read_model text PRIMARY KEY,                          -- e.g. balances
    projection text NOT NULL REFERENCES projection_checkpoints (projection)
);

-- Crypto-shredding: deleting a subject's key makes its sealed fields unreadable.
CREATE TABLE subject_keys (
    subject_id text        PRIMARY KEY,
    data_key   bytea       NOT NULL CHECK (length(data_key) = 32),
    created_at timestamptz NOT NULL DEFAULT now()
);

Expected version and optimistic concurrency Must-know ​

In plain words: "I read version 17; store my event as 18 only if nobody else did first."

Common misunderstanding: "The UNIQUE constraint is enough." It stops two rows with version 18, but a writer that decided on stale state and computed version 19 after someone else's 18 would pass it. The check must compare the version the decision was based on.

Definition: Optimistic concurrency control on a stream: the append carries an expected version and fails if the stream head differs. Sentinels follow KurrentDB's stream states: AnyVersion (no check), NoStream (must not exist), or an exact number.

text
     Writer A (balance 100)                        Writer B (balance 100)
1    load acc-42 -> v2, balance 100
2                                                  load acc-42 -> v2, balance 100
3    decide withdraw 80 -> expected v2
4    UPDATE streams SET version = 3 WHERE version = 2   -- 1 row
5    COMMIT
6                                                  decide withdraw 80 -> expected v2
7                                                  UPDATE ... WHERE version = 2   -- 0 rows
8                                                  ErrWrongExpectedVersion: reload, decide again -> insufficient funds

Real scenarios: two ATMs withdrawing from one account; two support agents editing the same order; a mobile client sending an edit made on a screen loaded ten minutes ago (expected version from the client = optimistic UI); two instances of the same consumer both reacting to one event.

ProductFailure signal
PostgreSQL CAS (this chapter)UPDATE affects 0 rows; UNIQUE backstop raises SQLSTATE 23505
KurrentDB clientsAppend fails when the stream is not in the expected state (the error type differs per client)
NATS JetStreamPublish rejected when Nats-Expected-Last-Subject-Sequence does not match
Kafka, Redis Streams, RabbitMQNo per-key version check; the application must provide it elsewhere

How to use it: on ErrWrongExpectedVersion, reload, re-decide and retry with a new expected version but the same command ID. In the Go store the global allocator lock already serializes appends, so the CAS is a defence that still holds if another writer bypasses Execute.

Global position and commit order Must-know ​

In plain words: Projectors read "everything after position N". That only works if no event with a smaller number can still appear after you read past it.

Common misunderstanding: "bigserial gives the order." A sequence value is taken when the row is inserted, not when the transaction commits. PostgreSQL's sequence documentation states that values are not reclaimed when the transaction aborts and that sequences cannot be used for gapless numbering. Worse, a smaller value can become visible after a larger one.

Definition: A global position is a total order over committed events with two properties: no gaps, and commit order: if a reader sees position p, it already sees every position below p. This store gets both by holding a FOR UPDATE lock on a single feed_allocator row until COMMIT; PostgreSQL documents that row locks are held until the transaction ends, and that under Read Committed a waiting SELECT FOR UPDATE returns the updated row once the first transaction commits.

text
     T1 (bigserial)                    T2 (bigserial)                 Projector
1    INSERT -> position 41 (open)
2                                      INSERT -> position 42
3                                      COMMIT
4                                                                     SELECT > 40 -> [42]; checkpoint = 42
5    COMMIT
6                                                                     SELECT > 42 -> []   -- 41 never projected
bigserial cursor (unsafe)allocator row lock held to COMMIT (safe)T1nextval = 41, still openT2nextval = 42, COMMITProjectorreads > 40: sees 42, checkpoint 42T1COMMIT 41 laterProjectorreads > 42: 41 skipped foreverT1FOR UPDATE: next = 41T2FOR UPDATE: waitsT1insert 41, next = 42, COMMITT2gets 42 (re-read row), COMMITProjector42 visible only after 41: no skipCost of the safe side: appends to all streams are serialized; alternatives are gap detection (Marten high water mark) or log-based CDC.

Real scenarios: a balance read model missing one deposit forever; an integration relay that never publishes one order; a long transaction (a slow trigger, a lock wait) widening the window from microseconds to minutes. A "safety window" that waits a few seconds is not a fix: transactions can stay open arbitrarily long.

ApproachHow it guarantees orderCost
Allocator row lock (this chapter)Next appender waits until the previous commit is visibleAll appends serialized; throughput bounded by one transaction at a time
Gap detection (Marten async daemon)Advance a "high water mark" only below the first hole; skip a hole once no transaction could still fill itComplex; stalls behind long-running transactions
Log-based CDC (PostgreSQL logical decoding)Changes are emitted in commit orderReplication slot operations; see CDC
Database with a built-in $all order (KurrentDB)The store assigns itA separate database to run

How to use it: measure. One transaction per append, each holding the lock for a few milliseconds, gives hundreds of appends per second per database; batch several events per command and keep the transaction short (no network calls inside). Above that, move to gap detection or CDC rather than weakening the guarantee.

Replay and snapshots Important ​

In plain words: Replay rebuilds state by folding every event; a snapshot saves the folded state at version v so the next load folds only the tail.

Common misunderstanding: "Snapshot the aggregate I have in memory after handling the command." That object may contain decided but uncommitted events. A snapshot must be taken from committed history only.

Definition: Greg Young calls these rolling snapshots: a denormalization of an aggregate's state at a point in the stream, used as a heuristic to avoid loading the whole history. A snapshot is an optimization, never a source of truth: delete all snapshots and the system must still be correct.

text
1 SaveSnapshot(acc-42) -> REPEATABLE READ: head v1000, fold v1..v1000
2 SaveSnapshot -> UPSERT snapshots(v1000, format 1) only if stored version/format is older
3 Load(acc-42) -> snapshot v1000 valid (id, version <= head, format) -> fold v1001..v1004
4 Deploy changes fold rules -> SnapshotFormat = 2 -> old snapshots ignored, full replay

Real scenarios: an inventory item with years of stock movements; a long-lived subscription; an aggregate whose load time dominates command latency. Axon's snapshot documentation gives the same motivation (many events per long-lived aggregate) and triggers snapshots by thresholds; Spatie's snapshot stores the aggregate's public properties.

RuleWhy
Snapshot from committed events, inside one REPEATABLE READ transactionHead, snapshot and tail form one consistent view
Validate stream ID, version ≤ head and format version on loadA copied or stale snapshot must not be trusted
Bump the format when state shape or fold logic changesOld snapshots encode old rules
Never overwrite a newer snapshot with an older oneConcurrent snapshotters race
Make snapshots disposableRebuild is always possible from events

How to use it: snapshot asynchronously every N events or when load time exceeds a budget; SaveSnapshot in Go reloads committed state itself. A SQLSTATE 40001 from two concurrent snapshotters is safe to ignore.

Projections, read models and checkpoints Must-know ​

In plain words: A projection reads events in order and keeps a table shaped for one question; its checkpoint remembers the last event it handled.

Common misunderstanding: "If the projector cannot understand an event, skip it and continue." Skipping advances the checkpoint past a fact the read model never absorbed; the error is now permanent and invisible.

Definition: A read model is a query-optimized copy derived from events. A projection is the code that maintains it. A checkpoint is the last global position applied. Correctness needs three things: read-model rows and checkpoint commit in the same transaction; each row checks the per-stream version it expects (stream_version = v - 1) and the update must affect exactly one row; unknown event types or schema versions stop the projector (fail closed).

text
1 Projector -> INSERT checkpoint (balances_v1, 0) ON CONFLICT DO NOTHING
2 Projector -> SELECT position ... FOR UPDATE -> 811     -- second instance waits here
3 Projector -> SELECT events WHERE global_position > 811 LIMIT 500
4 Projector -> 812 MoneyWithdrawn acc-42 v3: UPDATE ... WHERE stream_version = 2 -> 1 row
5 Projector -> UPDATE checkpoint = 812; COMMIT

Real scenarios: an account list with balances; a "pending orders" dashboard; a search index; a monthly statement table. Marten offers three lifecycles: live aggregation (fold at query time), inline projections (updated in the same transaction as the append), and asynchronous projections run by its async daemon. Spatie's projectors receive events after the aggregate persists them; its docs recommend a queue that processes one job at a time to keep order.

LifecycleConsistency with the writeFailure mode
Live (fold on read)Always currentSlow for long streams
Inline (same transaction)ImmediateA projection bug fails the command
Async (checkpointed)Eventual consistency, lag measurableLag, drift if applied without version checks

How to use it: the Go Project inserts the checkpoint row with ON CONFLICT DO NOTHING and then locks it, so two first-time runners do not abort each other; it verifies global_position == checkpoint + 1 and fails on gaps. Projections must not cause external side effects; a projector that sends e-mails sends them again on every rebuild.

Rebuilds and blue/green projection versions Important ​

In plain words: To change a read model, build the new version next to the old one from position 0, then switch readers.

Common misunderstanding: "TRUNCATE the table, reset the checkpoint, replay." While it runs, readers see an empty or partial model, and the live projector may still write to the same table.

Definition: A projection version is a separate name (balances_v1, balances_v2) with its own rows and checkpoint. The new version catches up while the old one serves; an activation step points readers at the new version only after its checkpoint reached the head; the old version is dropped after a rollback window. Marten documents the same model: increment ProjectionVersion to write to separate tables and switch traffic after catch-up.

text
1 Deploy v2 code -> Project("balances_v2") from 0 while balances_v1 serves
2 v2 checkpoint 0 -> 400000 -> head (head keeps moving)
3 ActivateProjection("balances", "balances_v2", head) -> active_projections updated
4 Readers -> follow active_projections -> v2
5 After rollback window -> stop v1 projector, DELETE rows of balances_v1
Event feedpositions 1 .. headappend-onlybalances_v1 (blue)live, checkpoint = headserves readersbalances_v2 (green)new code, checkpoint 0catches up, no side effectsActivatev2 checkpoint>= head at cut-overReadersfollowactive_projectionsDrop v1after readersand rollback windowTRUNCATE-and-replay in place shows readers an empty or partial model and races the live projector.

Real scenarios: adding a column computed from history; fixing a projection bug that produced wrong totals; moving a read model to another database or search engine; adding a new event type that the old projector would reject.

StrategyReader impactRequirement
In-place truncate and replayEmpty or partial model during rebuildQuiesce writers, projectors and readers
Blue/green versionsNone until the switchSpace for two copies; activation step
Per-stream rebuildOnly one stream affectedThe model is partitioned by stream

How to use it: ActivateProjection refuses a version whose checkpoint is behind the position you pass (normally the head at cut-over). Gate side effects: Marten notes that a new version catching up over the whole history would re-emit side effects unless they are suppressed. Marten also has an option to let its daemon skip unknown event types, so an old projection version keeps running while new code introduces a new type; treat that as a deliberate exception for a version about to be retired, not as the default.

Event versioning and upcasting Must-know ​

In plain words: Events written years ago must still be readable. An upcaster converts an old shape into the current one when reading; the stored row never changes.

Common misunderstanding: "Use lenient JSON decoding and missing fields become zero." A withdrawal whose amount decodes as 0 because the field was renamed is not an old event; it is wrong data.

Definition: Event versioning gives every event a type and a schema version. Upcasting is a pure function (type, version, data) → (type, current version, data) applied between storage and the fold or projection. Marten documents upcasting as a transformation performed on the fly at read time, with functions as the simplest form; Axon Framework 5.0's documentation says upcasters are not yet available in 5.0 and are scheduled to return, recommending payload conversion meanwhile, a reminder to check the version you run.

text
1 2024 build -> stores MoneyWithdrawn v1 {"amount_cents": 1250}
2 2026 build -> current MoneyWithdrawn v2 {"amount": 1250, "reason": "..."}
3 Load -> Upcast(v1) -> v2 {"amount": 1250, "reason": "unspecified (v1)"}
4 Load -> MoneyWithdrawn v3 found, build knows only v2 -> ErrUnknownEvent, stop

Real scenarios: a renamed field; a split of one event into two; a new mandatory field with a documented default; a consumer that receives events from a newer producer during a rolling deployment.

TechniqueWhenLimitation
Additive optional fieldNew information, old readers ignore itOnly if readers tolerate unknown fields
Upcaster on readRename, restructure, default a fieldMust be pure; chain grows over time
New event typeMeaning changedOld type still needs a handler
Copy-and-transform into a new storeLarge structural changeA migration project, with its own cut-over

How to use it: decode strictly (DisallowUnknownFields in Go), keep upcasters next to the event definitions with tests per historical version, and fail closed on unknown types. For contract evolution between services, see message design and schema evolution.

CQRS, with or without event sourcing Must-know ​

In plain words: Use one model to change data and another to read it.

Common misunderstanding: "CQRS means two databases, a broker and eventual consistency." Fowler's bliki notes the two models may share the same database; nothing forces asynchrony.

Definition: Command Query Responsibility Segregation splits the model that validates and applies changes (commands, which return no domain data) from the model that answers queries (which change nothing). With event sourcing the query model is a projection; without it, the query model can be a SQL view, a materialized view, or a table updated in the same transaction as the write.

text
1 POST /accounts/42/withdraw -> command handler -> UPDATE accounts, INSERT ledger_lines; COMMIT
2 Same transaction -> UPDATE account_summary (query model)
3 GET /accounts/42/summary -> query handler -> SELECT FROM account_summary
4 No events stored, no broker, no lag: still CQRS

Real scenarios: a write model with rich validation and a flat reporting table; a list screen joining six tables replaced by one denormalized table; a search index fed from the write model; a reporting database (Fowler's ReportingDatabase) for analysts.

VariantQuery modelConsistency
Same model, separate interfacesSame tablesImmediate
Same database, separate tablesView, materialized view, or table in same TXImmediate or refresh-based
Separate store from eventsProjectionEventual consistency, tokens for read-your-writes

How to use it: start with separate handlers and query objects in a monolith; add a separate store only when a query shape or load justifies it. Fowler's warning applies: most systems fit CRUD, and CQRS belongs to specific bounded contexts.

Read-your-writes tokens Important ​

In plain words: After a write the client gets a position; a query answers only if the read model has reached it.

Common misunderstanding: "Sleep 200 ms before redirecting." Lag is unbounded under load and during rebuilds.

Definition: Execute returns LastPosition. QueryBalance(account, atLeast) reads the active projection's checkpoint in the same statement as the row; if the checkpoint is below the token it returns ErrStale, and the caller waits (WaitForPosition), shows "updating", or answers from the write model (Load).

text
1 Client -> Execute(withdraw) -> {version 3, position 812}
2 Client -> GET /balance?atLeast=812
3 Query -> checkpoint 805 < 812 -> ErrStale
4 Query -> WaitForPosition(812, 50 ms ticks, 2 s deadline) -> checkpoint 812
5 Query -> balance 70, AsOf 812

Real scenarios: "my new order is missing from my orders page"; a balance shown before a just-made transfer; a test that asserts a projection right after a command. Marten exposes WaitForNonStaleProjectionDataAsync for tests with the same idea.

OptionFreshnessCost
Token + waitGuaranteed own writesAdded latency under lag
Token + fall back to write modelGuaranteedLoad on the write side
Inline projectionImmediateProjection failure fails the command
No tokenEventual consistencyConfused users

How to use it: carry the token in a response header or cookie; for replicas, the same idea applies to replication positions, see replication and failover.

Command idempotency and receipts Must-know ​

In plain words: If the answer to "withdraw 30" was lost, the client sends the same command again with the same ID; the store answers from its receipt instead of withdrawing twice.

Common misunderstanding: "Expected version makes retries safe." A retry after a lost COMMIT acknowledgement carries expected version 2 while the store is at 3: the CAS rejects it, the client reloads, sees balance 70, and withdraws again. CAS prevents concurrent overwrite, not repeated intent.

Definition: A command receipt stores the command ID, a fingerprint (SHA-256 of the intent) and the result, in the same transaction as the events. On a retry with the same ID and fingerprint, the stored result returns with Duplicate=true; the same ID with a different fingerprint is ErrCommandIDReused.

text
1 Client -> Execute(c-77, withdraw 30, expected v2) -> COMMIT succeeds
2 Network -> response lost; client sees ErrCommitUnknown or a timeout
3 Client -> Execute(c-77, withdraw 30, expected v2) again
4 Execute -> receipt c-77 found, fingerprint equal -> {v3, 812, Duplicate}
5 Client -> Execute(c-77, withdraw 50) -> ErrCommandIDReused

Real scenarios: an HTTP client timeout; a queue worker that crashed after committing and before acknowledging its message; a payment provider webhook delivered twice.

LayerMechanismCovers
Command sideCommand receipt in the append transactionRetried commands
ProjectionCheckpoint + per-stream version checkReplayed batches
Downstream consumerInbox keyed by event ID or stream versionBroker redelivery; see idempotent consumers
Broker producerKafka idempotent producer, RabbitMQ Streams deduplication, SQS FIFO deduplicationProducer retries within the broker's scope

How to use it: let the client generate the command ID (a UUID per user intent, reused on every retry); keep receipts at least as long as clients may retry; decide whether rejected commands also get receipts.

Event time, processing time, corrections and compensating events Important ​

In plain words: An event records when something happened (event time) and when the system learned it (processing time); a wrong fact is corrected by a new fact, not by editing the old one.

Common misunderstanding: "Order by occurred_at." Late events (an offline card terminal syncing tomorrow) have old event times and new positions. Position orders processing; event time is data.

Definition: occurred_at is event time, supplied by the business or device; recorded_at is processing time, assigned by the store. A compensating event (Greg Young's reversal transaction) such as WithdrawalReversed references the original event and undoes its effect while leaving the trail. Fowler's article discusses retroactive events and bi-temporal designs for the harder case of changing what was believed in the past.

text
1 Day 1 10:00 -> MoneyWithdrawn e-55 {30}, occurred 10:00, recorded 10:00
2 Day 2 09:00 -> dispute: duplicate card charge
3 Day 2 09:05 -> WithdrawalReversed {withdrawal_event_id: e-55, amount: 30}, recorded day 2
4 Statement for day 1 (event time) -> shows the withdrawal; balance today (position order) -> restored

Real scenarios: chargebacks; a price entered with a wrong decimal; a shipment scanned twice; a late sensor reading. Windowing by event time belongs to stream processing.

NeedMechanism
Undo an effectCompensating event referencing the original
Correct a valueCorrection event with the new value and a reason
Report "as known at"Filter by recorded_at / position
Report "as happened at"Filter by occurred_at

How to use it: the Go Decide accepts a reversal only for an existing, not yet reversed withdrawal with the same amount; reversing twice fails.

Privacy and erasure in an immutable log Important ​

In plain words: Do not store personal data in plain text in events you can never change; encrypt it with a per-person key and destroy the key when the data must go.

Common misunderstanding: "Crypto-shredding makes us compliant." It removes readability of sealed fields in this store; backups of the key table, replicas, logs, caches, read models, search indexes and broker topics that received plaintext are separate copies. Legal requirements need legal review.

Definition: Crypto-shredding: sensitive fields are sealed (here AES-256-GCM, subject ID as associated data) with a key held per data subject; deleting the key (ForgetSubject) makes every sealed value unreadable while event rows stay. A tombstone is a marker that something is deleted: KurrentDB's hard delete appends a $streamDeleted tombstone and prevents reuse of the stream, while soft delete sets TruncateBefore and scavenging later removes events; in Kafka a tombstone is a record with a key and a null value, which compaction uses to drop earlier values for that key.

text
1 Open account -> SubjectKey(sub-9) -> Seal("Ada Example") -> AccountOpened.owner_name_sealed
2 Read -> RevealOwnerName -> key found -> "Ada Example"
3 Erasure request -> ForgetSubject(sub-9) -> DELETE subject_keys
4 Read -> ErrShredded; fold still works (no balance data was sealed)
5 Read models / search index -> must delete their plaintext copies separately

Real scenarios: an erasure request for a closed customer; a retention rule for KYC documents; a support tool that should never show names to most staff.

StoreErasure primitiveCaveat
PostgreSQL event tableCrypto-shredding; or a reviewed DELETE with the trigger disabledBackups and replicas keep old pages
KurrentDBSoft delete (TruncateBefore) or hard delete (tombstone) + scavenging$all readers see unscavenged events
KafkaCompaction tombstone, retentionConsumers and copies outside Kafka
Redis StreamsXDEL, XTRIMAOF/RDB files and replicas

How to use it: seal only what must be erasable; keep the fold independent of sealed fields; wrap data keys with a KMS in production; inventory every copy. Deeper treatment: messaging security.

Kafka log compaction and its limits Important ​

In plain words: Compaction keeps the newest record per key and throws away the older ones. That is a snapshot of latest values, not a history.

Common misunderstanding: "A compacted topic keyed by account ID is our event store." After compaction only the last event per account survives; a deposit followed by a withdrawal becomes just the withdrawal.

Definition: Kafka's design documentation guarantees that compaction retains at least the last known value for each key in a partition, never reorders, never changes offsets, and that a consumer starting from the beginning sees the final state of each key; delete.retention.ms bounds how long tombstones stay visible and min.compaction.lag.ms how long the head stays uncompacted. cleanup.policy is delete by default.

text
1 account-events (cleanup.policy=compact), key A: 0 opened, 2 +100, 3 -30, 5 +30
2 Log cleaner runs -> key A keeps offset 5 (+30) only
3 New projector replays from offset 0 -> sees "+30" for A -> balance 30, truth 100
Partition records for keys A and B (offsets 0..5)0: Aopened1: Bopened2: A+1003: A-304: B+55: A+30cleanup.policy=delete (until retention.ms)0: A opened1: B opened2: A +1003: A -304: B +55: A +30cleanup.policy=compact (after the cleaner runs)0: removed1: removed2: removed3: removed4: B +55: A +30Full history:replay worksLast value per key:events are not state;balance unrecoverable

Real scenarios: a compacted "latest balance per account" topic (event-carried state) is a good fit; a compacted "account events" topic is not; a unique-event-ID key avoids loss but then compaction removes nothing, so it is just a topic with unbounded retention.

Topic purposecleanup.policyReplay from start gives
Event transport, database is the storedelete with retentionRecent events only
Latest state per keycompactFinal value per key, tombstones within delete.retention.ms
Bothdelete,compactCompacted segments until retention deletes them

How to use it: keep history in the event store; use a compacted topic for state; the Go kafkarelay package defines both configurations explicitly.

Mechanics and exact controls ​

The append transaction step by step Must-know ​

sql
BEGIN;                                                        -- READ COMMITTED
SELECT next_position FROM feed_allocator WHERE id = 1 FOR UPDATE;   -- 812, held to COMMIT
SELECT fingerprint, stream_version, last_position
  FROM command_receipts WHERE command_id = 'c-77';            -- no row: new command
SELECT version FROM streams WHERE id = 'acc-42';              -- 2
SELECT version, format, state FROM snapshots WHERE stream_id = 'acc-42';
SELECT ... FROM events WHERE stream_id = 'acc-42' AND stream_version > 0 ORDER BY stream_version;
UPDATE streams SET version = 3 WHERE id = 'acc-42' AND version = 2;      -- must be 1 row
INSERT INTO events (global_position, event_id, stream_id, stream_version, type,
                    schema_version, data, command_id, occurred_at)
VALUES (812, 'c-77/0', 'acc-42', 3, 'MoneyWithdrawn', 2,
        '{"amount":30,"reason":"atm"}', 'c-77', '2026-11-26T10:00:00Z');
UPDATE feed_allocator SET next_position = 813 WHERE id = 1;
INSERT INTO command_receipts VALUES ('c-77', 'acc-42', '9f2c...', 3, 812, now());
COMMIT;
Control or signalMeaning
FOR UPDATE on feed_allocatorSerializes appends; lock released at COMMIT or ROLLBACK
UPDATE ... WHERE version = $expected = 0 rowsWrong expected version
SQLSTATE 23505 unique_violationUNIQUE (stream_id, stream_version) or event_id backstop fired
SQLSTATE 40001 serialization_failureREPEATABLE READ snapshot writer raced; retry or skip
SQLSTATE 40P01 deadlock_detectedShould not occur with one lock order; investigate
Trigger events_append_onlyUPDATE, DELETE, TRUNCATE on events raise an error
ErrCommitUnknownCOMMIT returned an error; retry with the same command ID
lock_timeout / statement_timeoutBound waits on the allocator during incidents

Loading, snapshots and projections under isolation Important ​

Load uses a read-only REPEATABLE READ transaction: PostgreSQL documents that this level sees only data committed before the transaction began, so streams.version, the snapshot and the tail are one consistent view even while appends continue. Inside Execute, the allocator lock already prevents appends, so Read Committed suffices. Projectors run Read Committed and rely on the allocator's commit order: any position they can see has no smaller invisible neighbour. See isolation levels for the anomalies behind these choices.

OperationIsolationLocksFailure to expect
ExecuteRead CommittedAllocator row FOR UPDATEWrong expected version, domain error, unknown commit
LoadRepeatable Read, read onlyNoneCorrupt history (ErrCorruptHistory)
SaveSnapshotRepeatable ReadSnapshot row on upsert40001 from a concurrent snapshot
ProjectRead CommittedCheckpoint row FOR UPDATEFeed gap, drift, unknown event
ActivateProjectionRead CommittedCheckpoint FOR SHARENot caught up

Solving classic problems ​

Concurrent writers on one stream ​

SolutionHowAdvantageCost / limitation
Expected-version CASUPDATE streams ... WHERE version = vNo locks held while deciding outside the storeRetries under contention
Pessimistic stream lockSELECT ... FROM streams FOR UPDATE before decidingNo retriesLock waits; deadlocks across streams
Single writer per streamRoute commands for a key to one workerSimple, orderedRouting and failover design
Global allocator lock (this store)One appender at a timeCommit-ordered feed for freeSerialized appends

Projections that never lose or double-apply ​

SolutionHowAdvantageCost / limitation
Rows + checkpoint in one transactionSame database for model and checkpointExactly-once effect on the modelModel must live in the same database
Idempotent upsert by stream versionWHERE stream_version = v - 1Works across databasesNeeds a version per row
Inbox of event IDsInsert event ID before applyingGenericTable growth, cleanup
Fail closedStop on unknown/gap/driftErrors stay visibleLag until fixed

Unknown commit outcome and retries ​

SolutionHowAdvantageCost / limitation
Command receipt + fingerprintStore result with the eventsExact answer on retryReceipt retention
Deterministic event IDscommand_id/index + UNIQUE (event_id)Duplicate insert failsDoes not return the original result
Natural idempotencyCommands like "set address to X"No storageRarely true for money

Integrating other services ​

An event store is not automatically a reliable integration outbox: relays must follow the commit-ordered feed with a checkpoint, publish with broker confirmation, and map internal events to stable public contracts instead of leaking every internal field. RelayOnce advances its checkpoint only to the last confirmed event and stops at the first failure or gap; delivery is at least once.

Choosing ​

SituationRecommendationExtra techniqueReason
CRUD admin screens, simple rulesNeither patternAudit table if neededLowest cost; Fowler's warning
Complex queries over simple writesCQRS without event sourcingViews or same-transaction summary tablesQuery model without event machinery
Audit, disputes, "why is it so"Event sourcing for that bounded contextReceipts, compensating eventsHistory is the requirement
Many read shapes from one historyEvent sourcing + async projectionsBlue/green rebuilds, tokensRebuildable models
Strong per-entity invariants, high contention on one entityEvent sourcing only if contention fits retriesSingle writer per streamCAS retries can dominate
Large personal-data payloadsAvoid putting them in eventsCrypto-shredding, referencesErasure stays possible
Throughput beyond one serialized appenderKurrentDB, Marten-style gap detection, or CDCMeasure firstAllocator lock is a ceiling
Team new to the patternStart with one contextInline projections firstOperational learning curve

When NOT to do it: the domain has no meaningful history; reports need ad-hoc SQL over current state; nobody will operate projections and rebuilds; regulatory deletion of most data is frequent; or the team wants it for the CV. Event sourcing is a per-context decision, not an architecture for a whole company.

Go ​

Before ​

A plain balance update. It is atomic and prevents overdrafts, but history, reasons and order are gone after COMMIT.

go
// Package before keeps only the current balance. It works, and it is the
// right design for many systems, but it cannot answer "how did we get here?".
package before

import (
	"context"
	"database/sql"
	"errors"
)

var ErrInsufficientFunds = errors.New("insufficient funds")

// Withdraw overwrites the balance in place. The previous value, the reason
// and the order of changes are gone after COMMIT; an audit log written
// separately can disagree with this row, and a mistaken withdrawal can only
// be "fixed" by editing the number again.
func Withdraw(ctx context.Context, db *sql.DB, accountID string, amount int64) error {
	res, err := db.ExecContext(ctx,
		`UPDATE accounts SET balance = balance - $2, updated_at = now()
		 WHERE id = $1 AND balance >= $2 AND $2 > 0`, accountID, amount)
	if err != nil {
		return err
	}
	if n, err := res.RowsAffected(); err != nil {
		return err
	} else if n != 1 {
		return ErrInsufficientFunds
	}
	return nil
}

After ​

The domain: strict decoding, positive amounts, overflow checks, state guards, compensating reversals, and a deterministic Apply that fails on inconsistent history.

go
package es

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"math"
	"regexp"
	"time"
)

// Domain errors. They reject a command; nothing is appended.
var (
	ErrInvalidCommand    = errors.New("invalid command")
	ErrInvalidAmount     = errors.New("amount must be positive")
	ErrOverflow          = errors.New("balance would overflow")
	ErrAlreadyOpen       = errors.New("account already open")
	ErrNotOpen           = errors.New("account not open")
	ErrInsufficientFunds = errors.New("insufficient funds")
	ErrUnknownWithdrawal = errors.New("withdrawal unknown or already reversed")
)

// ErrCorruptHistory means stored events contradict each other. Loading stops.
var ErrCorruptHistory = errors.New("corrupt or inconsistent history")

// Account is the write-side state folded from one stream. It is also the
// snapshot shape, so a change here must bump SnapshotFormat.
type Account struct {
	ID          string           `json:"id"`
	Version     int64            `json:"version"`
	Opened      bool             `json:"opened"`
	Currency    string           `json:"currency"`
	Balance     int64            `json:"balance"`
	Withdrawals map[string]int64 `json:"withdrawals"` // reversible, by event ID
}

// NewAccount is the empty state before the first event.
func NewAccount(id string) Account {
	return Account{ID: id, Withdrawals: map[string]int64{}}
}

// Apply folds one upcast event. It is deterministic and performs no I/O; it
// fails only when history is inconsistent or unsupported.
func (a *Account) Apply(e Event) error {
	if e.StreamID != a.ID || e.StreamVersion != a.Version+1 {
		return fmt.Errorf("%w: %s v%d after v%d", ErrCorruptHistory, e.StreamID, e.StreamVersion, a.Version)
	}
	if (e.Type == TypeAccountOpened) == a.Opened {
		return fmt.Errorf("%w: %s at v%d", ErrCorruptHistory, e.Type, e.StreamVersion)
	}
	switch e.Type {
	case TypeAccountOpened:
		var p AccountOpened
		if err := decodeStrict(e.Data, &p); err != nil || !currencyCode.MatchString(p.Currency) {
			return fmt.Errorf("%w: bad AccountOpened %s", ErrCorruptHistory, e.EventID)
		}
		a.Opened, a.Currency = true, p.Currency
	case TypeMoneyDeposited:
		var p MoneyDeposited
		if err := decodeStrict(e.Data, &p); err != nil {
			return fmt.Errorf("%w: %v", ErrCorruptHistory, err)
		}
		if err := a.credit(p.Amount); err != nil {
			return fmt.Errorf("%w: %v", ErrCorruptHistory, err)
		}
	case TypeMoneyWithdrawn:
		var p MoneyWithdrawn
		if err := decodeStrict(e.Data, &p); err != nil {
			return fmt.Errorf("%w: %v", ErrCorruptHistory, err)
		}
		if p.Amount <= 0 || p.Amount > a.Balance {
			return fmt.Errorf("%w: withdrawal %d with balance %d", ErrCorruptHistory, p.Amount, a.Balance)
		}
		a.Balance -= p.Amount
		a.Withdrawals[e.EventID] = p.Amount
	case TypeWithdrawalReversed:
		var p WithdrawalReversed
		if err := decodeStrict(e.Data, &p); err != nil {
			return fmt.Errorf("%w: %v", ErrCorruptHistory, err)
		}
		if amt, ok := a.Withdrawals[p.WithdrawalEventID]; !ok || amt != p.Amount {
			return fmt.Errorf("%w: reversal of %s", ErrCorruptHistory, p.WithdrawalEventID)
		}
		if err := a.credit(p.Amount); err != nil {
			return fmt.Errorf("%w: %v", ErrCorruptHistory, err)
		}
		delete(a.Withdrawals, p.WithdrawalEventID)
	default:
		return fmt.Errorf("%w: %s", ErrUnknownEvent, e.Type)
	}
	a.Version = e.StreamVersion
	return nil
}

func (a *Account) credit(amount int64) error {
	if amount <= 0 {
		return ErrInvalidAmount
	}
	if a.Balance > math.MaxInt64-amount {
		return ErrOverflow
	}
	a.Balance += amount
	return nil
}

// Command kinds.
const (
	KindOpen     = "open"
	KindDeposit  = "deposit"
	KindWithdraw = "withdraw"
	KindReverse  = "reverse"
)

// Expected-version sentinels, in the style of KurrentDB's stream states.
const (
	AnyVersion int64 = -1 // no concurrency check
	NoStream   int64 = 0  // the stream must not exist yet
)

// Command is an intent. CommandID is chosen by the client and reused on every
// retry of the same intent.
type Command struct {
	CommandID       string    `json:"-"`
	StreamID        string    `json:"stream_id"`
	ExpectedVersion int64     `json:"expected_version"`
	Kind            string    `json:"kind"`
	Amount          int64     `json:"amount,omitempty"`
	Currency        string    `json:"currency,omitempty"`
	Reason          string    `json:"reason,omitempty"`
	TargetEventID   string    `json:"target_event_id,omitempty"`
	SubjectID       string    `json:"subject_id,omitempty"`
	OwnerNameSealed []byte    `json:"owner_name_sealed,omitempty"`
	OccurredAt      time.Time `json:"occurred_at"`
}

var currencyCode = regexp.MustCompile(`^[A-Z]{3}$`)

// Fingerprint hashes everything except the command ID. Reusing an ID with a
// different intent is a client bug, not a retry.
func (c Command) Fingerprint() (string, error) {
	b, err := json.Marshal(c)
	if err != nil {
		return "", err
	}
	sum := sha256.Sum256(b)
	return hex.EncodeToString(sum[:]), nil
}

func (c Command) validate() error {
	if c.CommandID == "" || c.StreamID == "" || c.OccurredAt.IsZero() || c.ExpectedVersion < AnyVersion {
		return fmt.Errorf("%w: id, stream, occurred_at and expected version are required", ErrInvalidCommand)
	}
	return nil
}

// Pending is an event decided but not yet stored.
type Pending struct {
	Type       string
	Data       json.RawMessage
	OccurredAt time.Time
}

// Decide checks a command against current state and returns the events to
// append. It is pure: same state and command, same answer.
func Decide(a Account, c Command) ([]Pending, error) {
	if err := c.validate(); err != nil {
		return nil, err
	}
	var payload any
	var typ string
	switch c.Kind {
	case KindOpen:
		if a.Opened {
			return nil, ErrAlreadyOpen
		}
		if !currencyCode.MatchString(c.Currency) || c.SubjectID == "" {
			return nil, fmt.Errorf("%w: currency and subject are required", ErrInvalidCommand)
		}
		typ, payload = TypeAccountOpened, AccountOpened{Currency: c.Currency, SubjectID: c.SubjectID, OwnerNameSealed: c.OwnerNameSealed}
	case KindDeposit, KindWithdraw, KindReverse:
		if !a.Opened {
			return nil, ErrNotOpen
		}
		if c.Amount <= 0 {
			return nil, ErrInvalidAmount
		}
		switch c.Kind {
		case KindDeposit:
			if a.Balance > math.MaxInt64-c.Amount {
				return nil, ErrOverflow
			}
			typ, payload = TypeMoneyDeposited, MoneyDeposited{Amount: c.Amount}
		case KindWithdraw:
			if c.Amount > a.Balance {
				return nil, ErrInsufficientFunds
			}
			typ, payload = TypeMoneyWithdrawn, MoneyWithdrawn{Amount: c.Amount, Reason: c.Reason}
		default:
			if amt, ok := a.Withdrawals[c.TargetEventID]; !ok || amt != c.Amount {
				return nil, ErrUnknownWithdrawal
			}
			if a.Balance > math.MaxInt64-c.Amount {
				return nil, ErrOverflow
			}
			typ, payload = TypeWithdrawalReversed, WithdrawalReversed{WithdrawalEventID: c.TargetEventID, Amount: c.Amount, Reason: c.Reason}
		}
	default:
		return nil, fmt.Errorf("%w: kind %q", ErrInvalidCommand, c.Kind)
	}
	data, err := json.Marshal(payload)
	if err != nil {
		return nil, err
	}
	return []Pending{{Type: typ, Data: data, OccurredAt: c.OccurredAt}}, nil
}

Events, schema versions and the upcaster that fails closed:

go
// Package es is a small PostgreSQL event store built only on database/sql.
// The host program opens *sql.DB with a PostgreSQL driver (for example the
// pgx stdlib adapter) and applies ../sql/schema.sql first.
package es

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"time"
)

// Event is one stored fact. StreamVersion orders a single stream;
// GlobalPosition orders the whole store in commit order without gaps.
type Event struct {
	EventID        string
	StreamID       string
	StreamVersion  int64
	GlobalPosition int64
	Type           string
	SchemaVersion  int
	Data           json.RawMessage
	CommandID      string
	OccurredAt     time.Time // event time, supplied by the business
	RecordedAt     time.Time // processing time, assigned by the store
}

// Event types and their current schema versions.
const (
	TypeAccountOpened      = "AccountOpened"
	TypeMoneyDeposited     = "MoneyDeposited"
	TypeMoneyWithdrawn     = "MoneyWithdrawn"
	TypeWithdrawalReversed = "WithdrawalReversed"
)

var currentSchema = map[string]int{
	TypeAccountOpened:      1,
	TypeMoneyDeposited:     1,
	TypeMoneyWithdrawn:     2,
	TypeWithdrawalReversed: 1,
}

// ErrUnknownEvent is returned for a type or schema version this build cannot
// interpret. Readers stop instead of skipping, so nothing is silently lost.
var ErrUnknownEvent = errors.New("unknown event type or schema version")

// Payloads of the current schema versions.
type AccountOpened struct {
	Currency        string `json:"currency"`
	SubjectID       string `json:"subject_id"`
	OwnerNameSealed []byte `json:"owner_name_sealed"` // see shred.go
}

type MoneyDeposited struct {
	Amount int64 `json:"amount"`
}

type MoneyWithdrawn struct {
	Amount int64  `json:"amount"`
	Reason string `json:"reason"`
}

type WithdrawalReversed struct {
	WithdrawalEventID string `json:"withdrawal_event_id"`
	Amount            int64  `json:"amount"`
	Reason            string `json:"reason"`
}

// moneyWithdrawnV1 is the historical shape: no reason, differently named amount.
type moneyWithdrawnV1 struct {
	AmountCents int64 `json:"amount_cents"`
}

// Upcast converts a stored event to the current schema version on read.
// Stored rows are never rewritten.
func Upcast(e Event) (Event, error) {
	want, known := currentSchema[e.Type]
	if !known {
		return Event{}, fmt.Errorf("%w: %s v%d", ErrUnknownEvent, e.Type, e.SchemaVersion)
	}
	if e.Type == TypeMoneyWithdrawn && e.SchemaVersion == 1 {
		var old moneyWithdrawnV1
		if err := decodeStrict(e.Data, &old); err != nil {
			return Event{}, fmt.Errorf("upcast %s: %w", e.EventID, err)
		}
		data, err := json.Marshal(MoneyWithdrawn{Amount: old.AmountCents, Reason: "unspecified (v1)"})
		if err != nil {
			return Event{}, err
		}
		e.Data, e.SchemaVersion = data, 2
		return e, nil
	}
	if e.SchemaVersion != want {
		return Event{}, fmt.Errorf("%w: %s v%d", ErrUnknownEvent, e.Type, e.SchemaVersion)
	}
	return e, nil
}

// decodeStrict rejects unknown fields and trailing data, so a payload from a
// newer producer is not half-read by an older consumer.
func decodeStrict(data []byte, v any) error {
	dec := json.NewDecoder(bytes.NewReader(data))
	dec.DisallowUnknownFields()
	if err := dec.Decode(v); err != nil {
		return err
	}
	if dec.More() {
		return errors.New("trailing data after JSON value")
	}
	return nil
}

The store: allocator lock, receipt, CAS, append, snapshot validation.

go
package es

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
)

// Store errors.
var (
	// ErrWrongExpectedVersion: the stream moved since the caller read it.
	// Reload, decide again, retry with a NEW expected version but the SAME command ID.
	ErrWrongExpectedVersion = errors.New("wrong expected version")
	// ErrCommandIDReused: the ID was already used for a different intent.
	ErrCommandIDReused = errors.New("command ID reused with a different intent")
	// ErrCommitUnknown: COMMIT returned an error; the append may or may not
	// exist. Retry the same command; its receipt reveals the outcome.
	ErrCommitUnknown = errors.New("commit outcome unknown")
)

// SnapshotFormat versions the Account JSON and the fold rules behind it.
// Snapshots with another format are ignored and the stream is replayed.
const SnapshotFormat = 1

// Result is returned for a stored command and for its retries.
type Result struct {
	StreamVersion int64
	LastPosition  int64 // read-your-writes token for the query side
	Duplicate     bool  // answered from the command receipt
}

// Store is safe for concurrent use; all appends go through Execute.
type Store struct{ db *sql.DB }

func NewStore(db *sql.DB) *Store { return &Store{db: db} }

type querier interface {
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

// Execute decides and appends atomically: allocator lock, receipt check,
// expected-version CAS, events, allocator advance, receipt, COMMIT.
func (s *Store) Execute(ctx context.Context, cmd Command) (Result, error) {
	if err := cmd.validate(); err != nil {
		return Result{}, err
	}
	fp, err := cmd.Fingerprint()
	if err != nil {
		return Result{}, err
	}
	tx, err := s.db.BeginTx(ctx, nil) // READ COMMITTED
	if err != nil {
		return Result{}, err
	}
	defer tx.Rollback()

	// The row lock is held until COMMIT. The next appender cannot read
	// next_position before this transaction is visible, so positions become
	// visible in allocation order and an aborted append leaves no gap.
	// Cost: appends to ALL streams are serialized.
	var next int64
	if err := tx.QueryRowContext(ctx,
		`SELECT next_position FROM feed_allocator WHERE id = 1 FOR UPDATE`).Scan(&next); err != nil {
		return Result{}, fmt.Errorf("lock feed allocator: %w", err)
	}

	// Safe without races: no other append runs while we hold the lock.
	var prevFP string
	var r Result
	err = tx.QueryRowContext(ctx,
		`SELECT fingerprint, stream_version, last_position FROM command_receipts WHERE command_id = $1`,
		cmd.CommandID).Scan(&prevFP, &r.StreamVersion, &r.LastPosition)
	switch {
	case err == nil && prevFP == fp:
		r.Duplicate = true
		return r, nil
	case err == nil:
		return Result{}, ErrCommandIDReused
	case !errors.Is(err, sql.ErrNoRows):
		return Result{}, err
	}

	acc, err := load(ctx, tx, cmd.StreamID)
	if err != nil {
		return Result{}, err
	}
	if cmd.ExpectedVersion != AnyVersion && acc.Version != cmd.ExpectedVersion {
		return Result{}, fmt.Errorf("%w: expected %d, stream at %d", ErrWrongExpectedVersion, cmd.ExpectedVersion, acc.Version)
	}
	pending, err := Decide(acc, cmd)
	if err != nil {
		return Result{}, err
	}
	newVersion := acc.Version + int64(len(pending))

	// Compare-and-set on the stream head. Redundant while every writer takes
	// the allocator lock, but it keeps the invariant if one does not.
	var res sql.Result
	if acc.Version == 0 {
		res, err = tx.ExecContext(ctx,
			`INSERT INTO streams (id, version) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING`, cmd.StreamID, newVersion)
	} else {
		res, err = tx.ExecContext(ctx,
			`UPDATE streams SET version = $2 WHERE id = $1 AND version = $3`, cmd.StreamID, newVersion, acc.Version)
	}
	if err := oneRow(res, err); err != nil {
		return Result{}, fmt.Errorf("%w: stream head moved: %v", ErrWrongExpectedVersion, err)
	}

	for i, p := range pending {
		e := Event{
			EventID:        fmt.Sprintf("%s/%d", cmd.CommandID, i),
			StreamID:       cmd.StreamID,
			StreamVersion:  acc.Version + 1 + int64(i),
			GlobalPosition: next + int64(i),
			Type:           p.Type,
			SchemaVersion:  currentSchema[p.Type],
			Data:           p.Data,
			OccurredAt:     p.OccurredAt,
		}
		// Fold the new event too: Decide and Apply must agree.
		if err := acc.Apply(e); err != nil {
			return Result{}, fmt.Errorf("decided event does not fold: %w", err)
		}
		if _, err := tx.ExecContext(ctx, `INSERT INTO events
			(global_position, event_id, stream_id, stream_version, type, schema_version, data, command_id, occurred_at)
			VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
			e.GlobalPosition, e.EventID, e.StreamID, e.StreamVersion, e.Type, e.SchemaVersion,
			[]byte(e.Data), cmd.CommandID, e.OccurredAt); err != nil {
			return Result{}, err
		}
	}
	last := next + int64(len(pending)) - 1
	if err := oneRow(tx.ExecContext(ctx,
		`UPDATE feed_allocator SET next_position = $1 WHERE id = 1`, last+1)); err != nil {
		return Result{}, err
	}
	if _, err := tx.ExecContext(ctx, `INSERT INTO command_receipts
		(command_id, stream_id, fingerprint, stream_version, last_position) VALUES ($1, $2, $3, $4, $5)`,
		cmd.CommandID, cmd.StreamID, fp, newVersion, last); err != nil {
		return Result{}, err
	}
	if err := tx.Commit(); err != nil {
		return Result{}, fmt.Errorf("%w: %v", ErrCommitUnknown, err)
	}
	return Result{StreamVersion: newVersion, LastPosition: last}, nil
}

// Load folds a stream from its latest usable snapshot plus the tail. The
// REPEATABLE READ, read-only transaction makes head, snapshot and tail one view.
func (s *Store) Load(ctx context.Context, streamID string) (Account, error) {
	tx, err := s.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
	if err != nil {
		return Account{}, err
	}
	defer tx.Rollback()
	acc, err := load(ctx, tx, streamID)
	if err != nil {
		return Account{}, err
	}
	return acc, tx.Commit()
}

func load(ctx context.Context, q querier, streamID string) (Account, error) {
	var head int64
	err := q.QueryRowContext(ctx, `SELECT version FROM streams WHERE id = $1`, streamID).Scan(&head)
	if errors.Is(err, sql.ErrNoRows) {
		return NewAccount(streamID), nil
	}
	if err != nil {
		return Account{}, err
	}

	acc := NewAccount(streamID)
	var snapVersion int64
	var format int
	var state []byte
	err = q.QueryRowContext(ctx,
		`SELECT version, format, state FROM snapshots WHERE stream_id = $1`, streamID).Scan(&snapVersion, &format, &state)
	switch {
	case err == nil:
		if restored, ok := RestoreSnapshot(streamID, snapVersion, format, state, head); ok {
			acc = restored
		}
	case !errors.Is(err, sql.ErrNoRows):
		return Account{}, err
	}

	rows, err := q.QueryContext(ctx, `SELECT event_id, stream_version, global_position, type,
		schema_version, data, command_id, occurred_at, recorded_at
		FROM events WHERE stream_id = $1 AND stream_version > $2 ORDER BY stream_version`, streamID, acc.Version)
	if err != nil {
		return Account{}, err
	}
	defer rows.Close()
	for rows.Next() {
		e := Event{StreamID: streamID}
		var data []byte // *[]byte makes database/sql copy the driver's buffer
		if err := rows.Scan(&e.EventID, &e.StreamVersion, &e.GlobalPosition, &e.Type,
			&e.SchemaVersion, &data, &e.CommandID, &e.OccurredAt, &e.RecordedAt); err != nil {
			return Account{}, err
		}
		e.Data = data
		up, err := Upcast(e)
		if err != nil {
			return Account{}, err
		}
		if err := acc.Apply(up); err != nil {
			return Account{}, err
		}
	}
	if err := rows.Err(); err != nil {
		return Account{}, err
	}
	if acc.Version != head {
		return Account{}, fmt.Errorf("%w: folded v%d, head v%d", ErrCorruptHistory, acc.Version, head)
	}
	return acc, nil
}

// RestoreSnapshot trusts a snapshot only if format, identity and version
// agree with the stream; otherwise the caller replays from version 0.
func RestoreSnapshot(streamID string, version int64, format int, state []byte, head int64) (Account, bool) {
	if format != SnapshotFormat || version < 1 || version > head {
		return Account{}, false
	}
	var a Account
	if err := decodeStrict(state, &a); err != nil || a.ID != streamID || a.Version != version || !a.Opened {
		return Account{}, false
	}
	if a.Withdrawals == nil {
		a.Withdrawals = map[string]int64{}
	}
	return a, true
}

// SaveSnapshot folds COMMITTED history itself (never caller-held state with
// unsaved changes) and only replaces an older snapshot. Under REPEATABLE READ
// a concurrent snapshot writer can make this fail with SQLSTATE 40001;
// the caller may simply skip, because snapshots are an optimization.
func (s *Store) SaveSnapshot(ctx context.Context, streamID string) error {
	tx, err := s.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead})
	if err != nil {
		return err
	}
	defer tx.Rollback()
	acc, err := load(ctx, tx, streamID)
	if err != nil || acc.Version == 0 {
		return err
	}
	state, err := json.Marshal(acc)
	if err != nil {
		return err
	}
	if _, err := tx.ExecContext(ctx, `INSERT INTO snapshots (stream_id, version, format, state)
		VALUES ($1, $2, $3, $4)
		ON CONFLICT (stream_id) DO UPDATE
		SET version = EXCLUDED.version, format = EXCLUDED.format, state = EXCLUDED.state, taken_at = now()
		WHERE snapshots.format < EXCLUDED.format
		   OR (snapshots.format = EXCLUDED.format AND snapshots.version < EXCLUDED.version)`,
		streamID, acc.Version, SnapshotFormat, state); err != nil {
		return err
	}
	return tx.Commit()
}

func oneRow(res sql.Result, err error) error {
	if err != nil {
		return err
	}
	n, err := res.RowsAffected()
	if err != nil {
		return err
	}
	if n != 1 {
		return fmt.Errorf("affected %d rows, want 1", n)
	}
	return nil
}

Projections, checkpoints, blue/green activation and read-your-writes queries:

go
package es

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"time"
)

// Projection errors. Each one stops the projector without moving its checkpoint.
var (
	ErrFeedGap          = errors.New("global feed gap")
	ErrProjectionDrift  = errors.New("read model does not match the event stream")
	ErrNotCaughtUp      = errors.New("projection has not reached the required position")
	ErrStale            = errors.New("read model older than the read-your-writes token")
	ErrCheckpointMoved  = errors.New("checkpoint moved concurrently")
	ErrUnknownReadModel = errors.New("no active projection for read model")
)

// Project applies up to limit events after the checkpoint of one projection
// version (for example "balances_v2"). Read-model rows and checkpoint commit
// together, so a crash replays the batch instead of double-applying it.
func (s *Store) Project(ctx context.Context, projection string, limit int) (int, error) {
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return 0, err
	}
	defer tx.Rollback()

	// Insert-if-missing, then lock: two first-time runners do not abort each other.
	if _, err := tx.ExecContext(ctx, `INSERT INTO projection_checkpoints (projection, position)
		VALUES ($1, 0) ON CONFLICT (projection) DO NOTHING`, projection); err != nil {
		return 0, err
	}
	var pos int64
	if err := tx.QueryRowContext(ctx, `SELECT position FROM projection_checkpoints
		WHERE projection = $1 FOR UPDATE`, projection).Scan(&pos); err != nil {
		return 0, err
	}
	batch, err := readFeed(ctx, tx, pos, limit) // fully read before the next statement
	if err != nil {
		return 0, err
	}
	for _, e := range batch {
		if e.GlobalPosition != pos+1 {
			return 0, fmt.Errorf("%w: want %d, got %d", ErrFeedGap, pos+1, e.GlobalPosition)
		}
		up, err := Upcast(e)
		if err != nil {
			return 0, err // fail closed: deploy a build that understands it, then rerun
		}
		if err := applyBalance(ctx, tx, projection, up); err != nil {
			return 0, err
		}
		pos = e.GlobalPosition
	}
	if len(batch) == 0 {
		return 0, nil
	}
	if err := oneRow(tx.ExecContext(ctx, `UPDATE projection_checkpoints SET position = $2, updated_at = now()
		WHERE projection = $1`, projection, pos)); err != nil {
		return 0, err
	}
	return len(batch), tx.Commit()
}

// applyBalance checks the per-stream version on every row it touches, so a
// missing, duplicated or reordered event is detected instead of absorbed.
func applyBalance(ctx context.Context, tx *sql.Tx, projection string, e Event) error {
	var delta int64
	switch e.Type {
	case TypeAccountOpened:
		var p AccountOpened
		if err := json.Unmarshal(e.Data, &p); err != nil {
			return err
		}
		res, err := tx.ExecContext(ctx, `INSERT INTO account_balances
			(projection, account_id, currency, balance, stream_version, last_occurred_at)
			VALUES ($1, $2, $3, 0, $4, $5) ON CONFLICT DO NOTHING`,
			projection, e.StreamID, p.Currency, e.StreamVersion, e.OccurredAt)
		if err := oneRow(res, err); err != nil {
			return fmt.Errorf("%w: open %s: %v", ErrProjectionDrift, e.StreamID, err)
		}
		return nil
	case TypeMoneyDeposited:
		var p MoneyDeposited
		if err := json.Unmarshal(e.Data, &p); err != nil {
			return err
		}
		delta = p.Amount
	case TypeMoneyWithdrawn:
		var p MoneyWithdrawn
		if err := json.Unmarshal(e.Data, &p); err != nil {
			return err
		}
		delta = -p.Amount
	case TypeWithdrawalReversed:
		var p WithdrawalReversed
		if err := json.Unmarshal(e.Data, &p); err != nil {
			return err
		}
		delta = p.Amount
	default:
		return fmt.Errorf("%w: %s", ErrUnknownEvent, e.Type)
	}
	res, err := tx.ExecContext(ctx, `UPDATE account_balances
		SET balance = balance + $3, stream_version = $4, last_occurred_at = $5
		WHERE projection = $1 AND account_id = $2 AND stream_version = $4 - 1`,
		projection, e.StreamID, delta, e.StreamVersion, e.OccurredAt)
	if err := oneRow(res, err); err != nil {
		return fmt.Errorf("%w: %s v%d: %v", ErrProjectionDrift, e.StreamID, e.StreamVersion, err)
	}
	return nil
}

// Head is the last committed global position.
func (s *Store) Head(ctx context.Context) (int64, error) {
	var next int64
	err := s.db.QueryRowContext(ctx, `SELECT next_position FROM feed_allocator WHERE id = 1`).Scan(&next)
	return next - 1, err
}

// ActivateProjection points readers of readModel at a projection version
// once it has caught up to minPosition (normally Head at cut-over time).
// The old version keeps running until nobody reads it, then is dropped.
func (s *Store) ActivateProjection(ctx context.Context, readModel, projection string, minPosition int64) error {
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()
	var pos int64
	if err := tx.QueryRowContext(ctx, `SELECT position FROM projection_checkpoints
		WHERE projection = $1 FOR SHARE`, projection).Scan(&pos); err != nil {
		return err
	}
	if pos < minPosition {
		return fmt.Errorf("%w: %s at %d, need %d", ErrNotCaughtUp, projection, pos, minPosition)
	}
	if _, err := tx.ExecContext(ctx, `INSERT INTO active_projections (read_model, projection) VALUES ($1, $2)
		ON CONFLICT (read_model) DO UPDATE SET projection = EXCLUDED.projection`, readModel, projection); err != nil {
		return err
	}
	return tx.Commit()
}

// Balance is a query-side answer with the position it reflects.
type Balance struct {
	AccountID string
	Currency  string
	Balance   int64
	AsOf      int64 // checkpoint of the projection that answered
}

// QueryBalance reads the active projection. If its checkpoint is older than
// atLeast (the LastPosition a client got from Execute), it returns ErrStale so
// the caller can wait, retry, or read the write model instead.
func (s *Store) QueryBalance(ctx context.Context, accountID string, atLeast int64) (Balance, error) {
	var b Balance
	err := s.db.QueryRowContext(ctx, `SELECT c.position, b.account_id, b.currency, b.balance
		FROM active_projections a
		JOIN projection_checkpoints c ON c.projection = a.projection
		LEFT JOIN account_balances b ON b.projection = a.projection AND b.account_id = $1
		WHERE a.read_model = 'balances'`, accountID).Scan(&b.AsOf, nullString{&b.AccountID}, nullString{&b.Currency}, nullInt{&b.Balance})
	if errors.Is(err, sql.ErrNoRows) {
		return Balance{}, ErrUnknownReadModel
	}
	if err != nil {
		return Balance{}, err
	}
	if b.AsOf < atLeast {
		return Balance{}, fmt.Errorf("%w: at %d, token %d", ErrStale, b.AsOf, atLeast)
	}
	if b.AccountID == "" {
		return Balance{}, sql.ErrNoRows
	}
	return b, nil
}

// WaitForPosition polls until a projection reaches token or ctx ends.
func (s *Store) WaitForPosition(ctx context.Context, projection string, token int64, every time.Duration) error {
	t := time.NewTicker(every)
	defer t.Stop()
	for {
		var pos int64
		err := s.db.QueryRowContext(ctx, `SELECT position FROM projection_checkpoints
			WHERE projection = $1`, projection).Scan(&pos)
		if err != nil && !errors.Is(err, sql.ErrNoRows) {
			return err
		}
		if pos >= token {
			return nil
		}
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-t.C:
		}
	}
}

// Checkpoint returns a consumer's position, creating it at 0 if missing.
func (s *Store) Checkpoint(ctx context.Context, name string) (int64, error) {
	var pos int64
	err := s.db.QueryRowContext(ctx, `INSERT INTO projection_checkpoints (projection, position) VALUES ($1, 0)
		ON CONFLICT (projection) DO UPDATE SET projection = EXCLUDED.projection
		RETURNING position`, name).Scan(&pos)
	return pos, err
}

// AdvanceCheckpoint moves a relay checkpoint from -> to, or fails if another
// relay instance moved it first.
func (s *Store) AdvanceCheckpoint(ctx context.Context, name string, from, to int64) error {
	err := oneRow(s.db.ExecContext(ctx, `UPDATE projection_checkpoints SET position = $3, updated_at = now()
		WHERE projection = $1 AND position = $2`, name, from, to))
	if err != nil {
		return fmt.Errorf("%w: %s: %v", ErrCheckpointMoved, name, err)
	}
	return nil
}

// ReadFeed returns committed events after a global position, in order.
func (s *Store) ReadFeed(ctx context.Context, after int64, limit int) ([]Event, error) {
	return readFeed(ctx, s.db, after, limit)
}

func readFeed(ctx context.Context, q querier, after int64, limit int) ([]Event, error) {
	rows, err := q.QueryContext(ctx, `SELECT event_id, stream_id, stream_version, global_position, type,
		schema_version, data, command_id, occurred_at, recorded_at
		FROM events WHERE global_position > $1 ORDER BY global_position LIMIT $2`, after, limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []Event
	for rows.Next() {
		var e Event
		var data []byte
		if err := rows.Scan(&e.EventID, &e.StreamID, &e.StreamVersion, &e.GlobalPosition, &e.Type,
			&e.SchemaVersion, &data, &e.CommandID, &e.OccurredAt, &e.RecordedAt); err != nil {
			return nil, err
		}
		e.Data = data
		out = append(out, e)
	}
	return out, rows.Err()
}

type nullString struct{ dst *string }

func (n nullString) Scan(v any) error {
	var s sql.NullString
	if err := s.Scan(v); err != nil {
		return err
	}
	*n.dst = s.String
	return nil
}

type nullInt struct{ dst *int64 }

func (n nullInt) Scan(v any) error {
	var i sql.NullInt64
	if err := i.Scan(v); err != nil {
		return err
	}
	*n.dst = i.Int64
	return nil
}

Crypto-shredding helpers:

go
package es

import (
	"context"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"database/sql"
	"errors"
	"fmt"
)

// ErrShredded means the subject's key is gone: the sealed value is
// permanently unreadable, while the event row itself stays in place.
var ErrShredded = errors.New("subject key deleted")

// SubjectKey returns the subject's 256-bit data key, creating it once.
// Production systems usually wrap this key with a KMS key instead of storing
// it in plain bytea next to the data.
func (s *Store) SubjectKey(ctx context.Context, subjectID string) ([]byte, error) {
	fresh := make([]byte, 32)
	if _, err := rand.Read(fresh); err != nil {
		return nil, err
	}
	if _, err := s.db.ExecContext(ctx, `INSERT INTO subject_keys (subject_id, data_key) VALUES ($1, $2)
		ON CONFLICT (subject_id) DO NOTHING`, subjectID, fresh); err != nil {
		return nil, err
	}
	return s.existingKey(ctx, subjectID)
}

func (s *Store) existingKey(ctx context.Context, subjectID string) ([]byte, error) {
	var key []byte
	err := s.db.QueryRowContext(ctx, `SELECT data_key FROM subject_keys WHERE subject_id = $1`, subjectID).Scan(&key)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, ErrShredded
	}
	return key, err
}

// ForgetSubject deletes the key. Copies in backups, replicas, logs, caches,
// read models and broker topics are NOT affected by this statement.
func (s *Store) ForgetSubject(ctx context.Context, subjectID string) error {
	_, err := s.db.ExecContext(ctx, `DELETE FROM subject_keys WHERE subject_id = $1`, subjectID)
	return err
}

// RevealOwnerName decrypts the sealed field of an AccountOpened payload.
func (s *Store) RevealOwnerName(ctx context.Context, p AccountOpened) (string, error) {
	key, err := s.existingKey(ctx, p.SubjectID)
	if err != nil {
		return "", err
	}
	plain, err := Open(key, p.SubjectID, p.OwnerNameSealed)
	return string(plain), err
}

// Seal encrypts with AES-256-GCM; the subject ID is bound as associated data
// so a sealed value cannot be moved to another subject.
func Seal(key []byte, subjectID string, plaintext []byte) ([]byte, error) {
	gcm, err := newGCM(key)
	if err != nil {
		return nil, err
	}
	nonce := make([]byte, gcm.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		return nil, err
	}
	return gcm.Seal(nonce, nonce, plaintext, []byte(subjectID)), nil
}

// Open reverses Seal.
func Open(key []byte, subjectID string, sealed []byte) ([]byte, error) {
	gcm, err := newGCM(key)
	if err != nil {
		return nil, err
	}
	if len(sealed) < gcm.NonceSize() {
		return nil, errors.New("sealed value too short")
	}
	nonce, body := sealed[:gcm.NonceSize()], sealed[gcm.NonceSize():]
	return gcm.Open(nil, nonce, body, []byte(subjectID))
}

func newGCM(key []byte) (cipher.AEAD, error) {
	if len(key) != 32 {
		return nil, fmt.Errorf("want 32-byte key, got %d", len(key))
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	return cipher.NewGCM(block)
}

The Go angle ​

The library uses only database/sql, encoding/json, crypto/* and context; the host program supplies a *sql.DB opened with a PostgreSQL driver (for example the pgx stdlib adapter) and applies the schema. BeginTx with sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true} gives the consistent load view; defer tx.Rollback() after Commit is harmless (sql.ErrTxDone). Rows are fully read before the next statement in a transaction, because some drivers cannot run a statement while a result set is open on the same connection. jsonb is scanned into []byte, which database/sql copies, rather than into json.RawMessage, which would alias driver memory. The tests (go test ./...) cover invariants, upcasting, fingerprints, snapshot validation, sealing and relay ordering without a database; SQL behaviour itself is exercised in the lab.

go
package es

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"math"
	"testing"
	"time"
)

var t0 = time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC)

// fold runs Decide and Apply the way Execute does, without a database.
func fold(t *testing.T, a *Account, c Command) error {
	t.Helper()
	c.StreamID, c.OccurredAt = a.ID, t0
	if c.CommandID == "" {
		c.CommandID = "cmd-" + c.Kind
	}
	pending, err := Decide(*a, c)
	if err != nil {
		return err
	}
	for i, p := range pending {
		e := Event{EventID: c.CommandID, StreamID: a.ID, StreamVersion: a.Version + 1 + int64(i),
			Type: p.Type, SchemaVersion: currentSchema[p.Type], Data: p.Data, OccurredAt: p.OccurredAt}
		if err := a.Apply(e); err != nil {
			t.Fatalf("decided event does not fold: %v", err)
		}
	}
	return nil
}

func opened(t *testing.T) Account {
	a := NewAccount("acc-1")
	if err := fold(t, &a, Command{Kind: KindOpen, Currency: "EUR", SubjectID: "sub-1"}); err != nil {
		t.Fatal(err)
	}
	return a
}

func TestDecideRejectsInvalidMoney(t *testing.T) {
	a := opened(t)
	for _, amt := range []int64{0, -1, math.MinInt64} {
		if err := fold(t, &a, Command{Kind: KindDeposit, Amount: amt}); !errors.Is(err, ErrInvalidAmount) {
			t.Errorf("deposit %d: got %v", amt, err)
		}
		if err := fold(t, &a, Command{Kind: KindWithdraw, Amount: amt}); !errors.Is(err, ErrInvalidAmount) {
			t.Errorf("withdraw %d: got %v", amt, err)
		}
	}
	if err := fold(t, &a, Command{Kind: KindDeposit, Amount: math.MaxInt64}); err != nil {
		t.Fatal(err)
	}
	if err := fold(t, &a, Command{Kind: KindDeposit, Amount: 1}); !errors.Is(err, ErrOverflow) {
		t.Errorf("overflow: got %v", err)
	}
}

func TestStateGuards(t *testing.T) {
	a := NewAccount("acc-1")
	if err := fold(t, &a, Command{Kind: KindDeposit, Amount: 5}); !errors.Is(err, ErrNotOpen) {
		t.Errorf("deposit before open: %v", err)
	}
	if err := fold(t, &a, Command{Kind: KindOpen, Currency: "eur", SubjectID: "s"}); !errors.Is(err, ErrInvalidCommand) {
		t.Errorf("bad currency: %v", err)
	}
	a = opened(t)
	if err := fold(t, &a, Command{Kind: KindOpen, Currency: "EUR", SubjectID: "s"}); !errors.Is(err, ErrAlreadyOpen) {
		t.Errorf("open twice: %v", err)
	}
	if err := fold(t, &a, Command{Kind: KindWithdraw, Amount: 1}); !errors.Is(err, ErrInsufficientFunds) {
		t.Errorf("overdraft: %v", err)
	}
}

func TestCompensatingReversalOnlyOnce(t *testing.T) {
	a := opened(t)
	_ = fold(t, &a, Command{Kind: KindDeposit, Amount: 100})
	if err := fold(t, &a, Command{CommandID: "w1", Kind: KindWithdraw, Amount: 30, Reason: "atm"}); err != nil {
		t.Fatal(err)
	}
	rev := Command{CommandID: "r1", Kind: KindReverse, Amount: 30, TargetEventID: "w1", Reason: "duplicate charge"}
	if err := fold(t, &a, rev); err != nil {
		t.Fatal(err)
	}
	if a.Balance != 100 || a.Version != 4 {
		t.Fatalf("balance %d version %d", a.Balance, a.Version)
	}
	rev.CommandID = "r2"
	if err := fold(t, &a, rev); !errors.Is(err, ErrUnknownWithdrawal) {
		t.Errorf("second reversal: %v", err)
	}
}

func TestApplyRejectsGapsAndForeignStreams(t *testing.T) {
	a := opened(t)
	dep := json.RawMessage(`{"amount":5}`)
	if err := a.Apply(Event{StreamID: "acc-1", StreamVersion: 3, Type: TypeMoneyDeposited, Data: dep}); !errors.Is(err, ErrCorruptHistory) {
		t.Errorf("gap: %v", err)
	}
	if err := a.Apply(Event{StreamID: "acc-2", StreamVersion: 2, Type: TypeMoneyDeposited, Data: dep}); !errors.Is(err, ErrCorruptHistory) {
		t.Errorf("foreign stream: %v", err)
	}
	if err := a.Apply(Event{StreamID: "acc-1", StreamVersion: 2, Type: TypeMoneyWithdrawn, Data: json.RawMessage(`{"amount":5,"reason":""}`)}); !errors.Is(err, ErrCorruptHistory) {
		t.Errorf("history overdraft: %v", err)
	}
}

func TestUpcastWithdrawalV1(t *testing.T) {
	old := Event{EventID: "e1", Type: TypeMoneyWithdrawn, SchemaVersion: 1, Data: json.RawMessage(`{"amount_cents":1250}`)}
	up, err := Upcast(old)
	if err != nil {
		t.Fatal(err)
	}
	var p MoneyWithdrawn
	if err := decodeStrict(up.Data, &p); err != nil || up.SchemaVersion != 2 || p.Amount != 1250 {
		t.Fatalf("got %+v %+v %v", up, p, err)
	}
	if !bytes.Equal(old.Data, []byte(`{"amount_cents":1250}`)) {
		t.Fatal("upcast must not mutate the stored payload")
	}
}

func TestUpcastFailsClosed(t *testing.T) {
	cases := []Event{
		{Type: "AccountFrozen", SchemaVersion: 1},
		{Type: TypeMoneyWithdrawn, SchemaVersion: 3},
		{Type: TypeMoneyDeposited, SchemaVersion: 2},
	}
	for _, e := range cases {
		if _, err := Upcast(e); !errors.Is(err, ErrUnknownEvent) {
			t.Errorf("%s v%d: %v", e.Type, e.SchemaVersion, err)
		}
	}
	if _, err := Upcast(Event{Type: TypeMoneyWithdrawn, SchemaVersion: 1, Data: json.RawMessage(`{"amount_cents":1,"extra":1}`)}); err == nil {
		t.Error("unknown field accepted")
	}
}

func TestFingerprint(t *testing.T) {
	c := Command{CommandID: "c1", StreamID: "acc-1", Kind: KindWithdraw, Amount: 10, ExpectedVersion: 4, OccurredAt: t0}
	retry := c
	retry.CommandID = "c1-retry-id-is-not-hashed"
	other := c
	other.Amount = 11
	f1, _ := c.Fingerprint()
	f2, _ := retry.Fingerprint()
	f3, _ := other.Fingerprint()
	if f1 != f2 || f1 == f3 {
		t.Fatalf("fingerprints %s %s %s", f1, f2, f3)
	}
}

func TestRestoreSnapshotValidates(t *testing.T) {
	a := opened(t)
	state, _ := json.Marshal(a)
	if _, ok := RestoreSnapshot("acc-1", 1, SnapshotFormat, state, 1); !ok {
		t.Fatal("valid snapshot rejected")
	}
	bad := []struct {
		id      string
		version int64
		format  int
		head    int64
	}{
		{"acc-2", 1, SnapshotFormat, 1},     // other stream
		{"acc-1", 1, SnapshotFormat + 1, 1}, // unknown format
		{"acc-1", 2, SnapshotFormat, 1},     // ahead of committed head
	}
	for _, b := range bad {
		if _, ok := RestoreSnapshot(b.id, b.version, b.format, state, b.head); ok {
			t.Errorf("accepted %+v", b)
		}
	}
}

func TestSealOpenAndShred(t *testing.T) {
	key := bytes.Repeat([]byte{7}, 32)
	sealed, err := Seal(key, "sub-1", []byte("Ada Example"))
	if err != nil {
		t.Fatal(err)
	}
	if plain, err := Open(key, "sub-1", sealed); err != nil || string(plain) != "Ada Example" {
		t.Fatalf("open: %q %v", plain, err)
	}
	if _, err := Open(key, "sub-2", sealed); err == nil {
		t.Error("sealed value moved to another subject")
	}
	if _, err := Open(bytes.Repeat([]byte{8}, 32), "sub-1", sealed); err == nil {
		t.Error("wrong key accepted")
	}
}

type fakeFeed struct {
	pos    int64
	events []Event
}

func (f *fakeFeed) Checkpoint(context.Context, string) (int64, error) { return f.pos, nil }
func (f *fakeFeed) ReadFeed(_ context.Context, after int64, limit int) ([]Event, error) {
	var out []Event
	for _, e := range f.events {
		if e.GlobalPosition > after && len(out) < limit {
			out = append(out, e)
		}
	}
	return out, nil
}
func (f *fakeFeed) AdvanceCheckpoint(_ context.Context, _ string, from, to int64) error {
	if f.pos != from {
		return ErrCheckpointMoved
	}
	f.pos = to
	return nil
}

func TestRelayStopsAtFirstFailure(t *testing.T) {
	f := &fakeFeed{events: []Event{{GlobalPosition: 1}, {GlobalPosition: 2}, {GlobalPosition: 3}}}
	boom := errors.New("broker unavailable")
	n, err := RelayOnce(context.Background(), f, "relay:test", 10, func(_ context.Context, e Event) error {
		if e.GlobalPosition == 3 {
			return boom
		}
		return nil
	})
	if !errors.Is(err, boom) || n != 2 || f.pos != 2 {
		t.Fatalf("n=%d pos=%d err=%v", n, f.pos, err)
	}
}

func TestRelayRefusesFeedGap(t *testing.T) {
	f := &fakeFeed{events: []Event{{GlobalPosition: 1}, {GlobalPosition: 3}}}
	n, err := RelayOnce(context.Background(), f, "relay:test", 10, func(context.Context, Event) error { return nil })
	if !errors.Is(err, ErrFeedGap) || n != 1 || f.pos != 1 {
		t.Fatalf("n=%d pos=%d err=%v", n, f.pos, err)
	}
}

Laravel ​

Before ​

The same balance update through the Query Builder: correct for CRUD, without history.

php
<?php

namespace App\Accounts\Before;

use DomainException;
use Illuminate\Support\Facades\DB;

final class AccountBalanceService
{
    // Correct for a CRUD system: atomic, no overdraft. But only the latest
    // number survives; why and when it changed is lost unless an audit table
    // is written separately (and can then disagree with this row).
    public function withdraw(string $accountId, int $amount): void
    {
        if ($amount <= 0) {
            throw new DomainException('Amount must be positive.');
        }

        $updated = DB::table('accounts')
            ->where('id', $accountId)
            ->where('balance', '>=', $amount)
            ->decrement('balance', $amount);

        if ($updated !== 1) {
            throw new DomainException('Insufficient funds.');
        }
    }
}

After ​

The aggregate with upcasting, fold and decision, in its own PSR-4 file:

php
<?php

namespace App\Accounts;

use DomainException;
use InvalidArgumentException;
use UnexpectedValueException;

/**
 * Write-side state folded from one stream. Amounts are integer minor units of
 * the account currency; PHP int is 64-bit on the supported platforms.
 */
final class Account
{
    public bool $opened = false;

    public string $currency = '';

    public int $balance = 0;

    public int $version = 0;

    /** @var array<string, int> reversible withdrawals by event id */
    public array $withdrawals = [];

    public function __construct(public readonly string $id) {}

    /** Converts a stored payload to the current schema; unknown versions fail closed. */
    public static function upcast(string $type, int $schemaVersion, array $data): array
    {
        return match (true) {
            $type === 'MoneyWithdrawn' && $schemaVersion === 1 => [
                'amount' => self::positive($data['amount_cents'] ?? null),
                'reason' => 'unspecified (v1)',
            ],
            $type === 'MoneyWithdrawn' && $schemaVersion === 2,
            in_array($type, ['AccountOpened', 'MoneyDeposited', 'WithdrawalReversed'], true) && $schemaVersion === 1 => $data,
            default => throw new UnexpectedValueException("Unknown event {$type} v{$schemaVersion}."),
        };
    }

    /** Folds one upcast event; deterministic, no I/O. Throws on inconsistent history. */
    public function apply(string $eventId, int $streamVersion, string $type, array $data): void
    {
        if ($streamVersion !== $this->version + 1 || ($type === 'AccountOpened') === $this->opened) {
            throw new UnexpectedValueException("Corrupt history at {$this->id} v{$streamVersion}.");
        }

        switch ($type) {
            case 'AccountOpened':
                $this->opened = true;
                $this->currency = (string) $data['currency'];
                break;
            case 'MoneyDeposited':
                $this->credit(self::positive($data['amount'] ?? null));
                break;
            case 'MoneyWithdrawn':
                $amount = self::positive($data['amount'] ?? null);
                if ($amount > $this->balance) {
                    throw new UnexpectedValueException("Overdraft in history at {$this->id} v{$streamVersion}.");
                }
                $this->balance -= $amount;
                $this->withdrawals[$eventId] = $amount;
                break;
            case 'WithdrawalReversed':
                $target = (string) $data['withdrawal_event_id'];
                $amount = self::positive($data['amount'] ?? null);
                if (($this->withdrawals[$target] ?? null) !== $amount) {
                    throw new UnexpectedValueException("Reversal of unknown withdrawal {$target}.");
                }
                $this->credit($amount);
                unset($this->withdrawals[$target]);
                break;
            default:
                throw new UnexpectedValueException("Unknown event {$type}.");
        }

        $this->version = $streamVersion;
    }

    /**
     * Pure decision: the event to append, or a DomainException.
     *
     * @return array{type: string, data: array<string, mixed>}
     */
    public function decide(array $command): array
    {
        $kind = $command['kind'] ?? '';

        if ($kind === 'open') {
            if ($this->opened) {
                throw new DomainException('Account already open.');
            }
            if (! preg_match('/^[A-Z]{3}$/', (string) ($command['currency'] ?? '')) || empty($command['subject_id'])) {
                throw new InvalidArgumentException('Currency and subject are required.');
            }

            return ['type' => 'AccountOpened', 'data' => [
                'currency' => $command['currency'],
                'subject_id' => $command['subject_id'],
            ]];
        }

        if (! $this->opened) {
            throw new DomainException('Account not open.');
        }
        $amount = $command['amount'] ?? null;
        if (! is_int($amount) || $amount <= 0) {
            throw new InvalidArgumentException('Amount must be a positive integer.');
        }

        return match ($kind) {
            'deposit' => $this->guardCredit($amount, ['type' => 'MoneyDeposited', 'data' => ['amount' => $amount]]),
            'withdraw' => $amount > $this->balance
                ? throw new DomainException('Insufficient funds.')
                : ['type' => 'MoneyWithdrawn', 'data' => ['amount' => $amount, 'reason' => (string) ($command['reason'] ?? '')]],
            'reverse' => ($this->withdrawals[$command['target_event_id'] ?? ''] ?? null) !== $amount
                ? throw new DomainException('Withdrawal unknown or already reversed.')
                : $this->guardCredit($amount, ['type' => 'WithdrawalReversed', 'data' => [
                    'withdrawal_event_id' => $command['target_event_id'],
                    'amount' => $amount,
                    'reason' => (string) ($command['reason'] ?? ''),
                ]]),
            default => throw new InvalidArgumentException("Unknown command {$kind}."),
        };
    }

    private function guardCredit(int $amount, array $event): array
    {
        if ($this->balance > PHP_INT_MAX - $amount) {
            throw new DomainException('Balance would overflow.');
        }

        return $event;
    }

    private function credit(int $amount): void
    {
        $this->guardCredit($amount, []);
        $this->balance += $amount;
    }

    private static function positive(mixed $value): int
    {
        if (! is_int($value) || $value <= 0) {
            throw new UnexpectedValueException('Stored amount must be a positive integer.');
        }

        return $value;
    }
}

The event store on one explicit connection, using DB::transaction semantics through the connection's transaction(), lockForUpdate(), insertOrIgnore() and affected-row counts:

php
<?php

namespace App\EventSourcing;

use App\Accounts\Account;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use UnexpectedValueException;

final class EventStore
{
    public const ANY_VERSION = -1;

    private ConnectionInterface $db;

    public function __construct(DatabaseManager $databases)
    {
        // One explicit connection for the lock, the reads, the writes and COMMIT.
        $this->db = $databases->connection('pgsql');
    }

    /**
     * Decide and append one event atomically; retries with the same command ID
     * and the same intent return the stored result instead of appending again.
     *
     * @return array{stream_version: int, last_position: int, duplicate: bool}
     */
    public function execute(string $commandId, string $streamId, int $expectedVersion, array $command): array
    {
        $fingerprint = hash('sha256', json_encode([$streamId, $expectedVersion, $command], JSON_THROW_ON_ERROR));

        return $this->db->transaction(function () use ($commandId, $streamId, $expectedVersion, $command, $fingerprint): array {
            // Held until COMMIT: positions become visible in order, without gaps.
            $next = (int) $this->db->table('feed_allocator')->where('id', 1)->lockForUpdate()->value('next_position');

            $receipt = $this->db->table('command_receipts')->where('command_id', $commandId)->first();
            if ($receipt !== null) {
                if (! hash_equals($receipt->fingerprint, $fingerprint)) {
                    throw new CommandIdReused($commandId);
                }

                return [
                    'stream_version' => (int) $receipt->stream_version,
                    'last_position' => (int) $receipt->last_position,
                    'duplicate' => true,
                ];
            }

            $account = $this->fold($streamId);
            if ($expectedVersion !== self::ANY_VERSION && $account->version !== $expectedVersion) {
                throw new WrongExpectedVersion($streamId, $expectedVersion, $account->version);
            }

            $event = $account->decide($command);
            $eventId = $commandId.'/0';
            $version = $account->version + 1;
            $account->apply($eventId, $version, $event['type'], $event['data']);

            $moved = $version === 1
                ? $this->db->table('streams')->insertOrIgnore(['id' => $streamId, 'version' => 1])
                : $this->db->table('streams')->where('id', $streamId)->where('version', $version - 1)->update(['version' => $version]);
            if ($moved !== 1) {
                throw new WrongExpectedVersion($streamId, $version - 1, -1);
            }

            $this->db->table('events')->insert([
                'global_position' => $next,
                'event_id' => $eventId,
                'stream_id' => $streamId,
                'stream_version' => $version,
                'type' => $event['type'],
                'schema_version' => $event['type'] === 'MoneyWithdrawn' ? 2 : 1,
                'data' => json_encode($event['data'], JSON_THROW_ON_ERROR),
                'command_id' => $commandId,
                'occurred_at' => $command['occurred_at'],
            ]);
            $this->db->table('feed_allocator')->where('id', 1)->update(['next_position' => $next + 1]);
            $this->db->table('command_receipts')->insert([
                'command_id' => $commandId,
                'stream_id' => $streamId,
                'fingerprint' => $fingerprint,
                'stream_version' => $version,
                'last_position' => $next,
            ]);

            return ['stream_version' => $version, 'last_position' => $next, 'duplicate' => false];
        }, 1);
    }

    /** Folds the stream inside one REPEATABLE READ, read-only snapshot. */
    public function load(string $streamId): Account
    {
        return $this->db->transaction(function () use ($streamId): Account {
            $this->db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');

            return $this->fold($streamId);
        });
    }

    private function fold(string $streamId): Account
    {
        $account = new Account($streamId);
        $head = (int) ($this->db->table('streams')->where('id', $streamId)->value('version') ?? 0);

        $rows = $this->db->table('events')
            ->where('stream_id', $streamId)
            ->orderBy('stream_version')
            ->get(['event_id', 'stream_version', 'type', 'schema_version', 'data']);

        foreach ($rows as $row) {
            $data = Account::upcast($row->type, (int) $row->schema_version, json_decode($row->data, true, 512, JSON_THROW_ON_ERROR));
            $account->apply($row->event_id, (int) $row->stream_version, $row->type, $data);
        }

        if ($account->version !== $head) {
            throw new UnexpectedValueException("Folded v{$account->version}, head v{$head} for {$streamId}.");
        }

        return $account;
    }
}
php
<?php

namespace App\EventSourcing;

use RuntimeException;

final class WrongExpectedVersion extends RuntimeException
{
    public function __construct(string $streamId, int $expected, int $actual)
    {
        parent::__construct("Stream {$streamId} is at version {$actual}, expected {$expected}.");
    }
}
php
<?php

namespace App\EventSourcing;

use RuntimeException;

final class CommandIdReused extends RuntimeException
{
    public function __construct(string $commandId)
    {
        parent::__construct("Command ID {$commandId} was already used for a different intent.");
    }
}

The projector with checkpoint and version checks in the same transaction:

php
<?php

namespace App\Accounts;

use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use UnexpectedValueException;

/**
 * Projects the global feed into account_balances for one projection version
 * (balances_v1, balances_v2 ...). Rows and checkpoint commit together.
 */
final class BalanceProjector
{
    private ConnectionInterface $db;

    public function __construct(DatabaseManager $databases)
    {
        $this->db = $databases->connection('pgsql');
    }

    public function project(string $projection, int $limit = 500): int
    {
        return $this->db->transaction(function () use ($projection, $limit): int {
            $this->db->table('projection_checkpoints')->insertOrIgnore(['projection' => $projection, 'position' => 0]);
            $position = (int) $this->db->table('projection_checkpoints')
                ->where('projection', $projection)->lockForUpdate()->value('position');

            $events = $this->db->table('events')
                ->where('global_position', '>', $position)
                ->orderBy('global_position')
                ->limit($limit)
                ->get();

            foreach ($events as $event) {
                if ((int) $event->global_position !== $position + 1) {
                    throw new UnexpectedValueException("Feed gap after {$position}.");
                }
                $data = Account::upcast($event->type, (int) $event->schema_version, json_decode($event->data, true, 512, JSON_THROW_ON_ERROR));
                $this->apply($projection, $event, $data);
                $position = (int) $event->global_position;
            }

            if ($events->isNotEmpty()) {
                $this->db->table('projection_checkpoints')
                    ->where('projection', $projection)
                    ->update(['position' => $position, 'updated_at' => now()]);
            }

            return $events->count();
        }, 1);
    }

    private function apply(string $projection, object $event, array $data): void
    {
        $version = (int) $event->stream_version;

        if ($event->type === 'AccountOpened') {
            $inserted = $this->db->table('account_balances')->insertOrIgnore([
                'projection' => $projection,
                'account_id' => $event->stream_id,
                'currency' => $data['currency'],
                'balance' => 0,
                'stream_version' => $version,
                'last_occurred_at' => $event->occurred_at,
            ]);
            if ($inserted !== 1) {
                throw new UnexpectedValueException("Account {$event->stream_id} already projected.");
            }

            return;
        }

        $delta = match ($event->type) {
            'MoneyDeposited', 'WithdrawalReversed' => $data['amount'],
            'MoneyWithdrawn' => -$data['amount'],
        };

        $updated = $this->db->table('account_balances')
            ->where('projection', $projection)
            ->where('account_id', $event->stream_id)
            ->where('stream_version', $version - 1)
            ->update([
                'balance' => $this->db->raw('balance + '.(int) $delta),
                'stream_version' => $version,
                'last_occurred_at' => $event->occurred_at,
            ]);

        if ($updated !== 1) {
            throw new UnexpectedValueException("Projection drift at {$event->stream_id} v{$version}.");
        }
    }
}

The Laravel angle ​

Laravel 13's DB::transaction rolls back and rethrows on an exception and accepts a number of attempts for deadlocks; the store passes 1 so a retry is the caller's decision (with the same command ID). lockForUpdate() emits FOR UPDATE; insertOrIgnore() and update() return affected-row counts, which the store checks. Every statement goes through the connection resolved once in the constructor, so the lock, reads, writes and COMMIT share one PDO connection; mixing DB::table() on the default connection with another connection would silently split the transaction. SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY is the first statement of load()'s transaction, which PostgreSQL requires.

spatie/laravel-event-sourcing (v7 docs read for this chapter) provides aggregate roots (retrieve($uuid), recordThat(), persist()), projectors and reactors, snapshots that store an aggregate's public properties, and php artisan event-sourcing:replay. Its documentation states limits worth knowing: reactors are never called during replay; --from skips resetState, and the package does not track which events each projector already handled; it recommends a queue that processes one job at a time so projectors receive events in order; replaying with model timestamps produces replay-time timestamps unless you copy the event's. Persisting an aggregate passes new events to projectors and reactors, but a reactor sending to a broker is still a dual write: use an outbox for reliable publication. Verify its concurrency behaviour against the package version you install.

Broker differences ​

The database is the event store in every variant below. Brokers carry copies of the committed feed to other services, through the generic RelayOnce loop:

go
package es

import (
	"context"
	"fmt"
)

// Feed is the part of Store a broker relay needs; tests use a fake.
type Feed interface {
	Checkpoint(ctx context.Context, name string) (int64, error)
	ReadFeed(ctx context.Context, after int64, limit int) ([]Event, error)
	AdvanceCheckpoint(ctx context.Context, name string, from, to int64) error
}

// PublishFunc must return nil only after the broker durably accepted e.
type PublishFunc func(ctx context.Context, e Event) error

// RelayOnce copies the next batch of the committed feed to a broker. It is at
// least once: a crash after publish and before AdvanceCheckpoint republishes,
// so consumers deduplicate by EventID or by (StreamID, StreamVersion).
func RelayOnce(ctx context.Context, feed Feed, name string, limit int, publish PublishFunc) (int, error) {
	from, err := feed.Checkpoint(ctx, name)
	if err != nil {
		return 0, err
	}
	batch, err := feed.ReadFeed(ctx, from, limit)
	if err != nil {
		return 0, err
	}
	done := from
	var pubErr error
	for _, e := range batch {
		if e.GlobalPosition != done+1 {
			pubErr = fmt.Errorf("%w: want %d, got %d", ErrFeedGap, done+1, e.GlobalPosition)
			break
		}
		if pubErr = publish(ctx, e); pubErr != nil {
			break
		}
		done = e.GlobalPosition
	}
	if done > from {
		if err := feed.AdvanceCheckpoint(ctx, name, from, done); err != nil {
			return 0, err
		}
	}
	return int(done - from), pubErr
}

RabbitMQ ​

Classic and quorum queues are destructive: a consumed and acknowledged message is gone, so a queue cannot replay history to a new subscriber. RabbitMQ Streams (x-queue-type: stream) are an append-only log with non-destructive reads; consumers attach at an offset with x-stream-offset (first, last, next, a number or a timestamp), need a per-consumer prefetch, and retention (x-max-age, x-max-length-bytes) discards whole old segments. Streams also offer publisher-side deduplication by producer name and publishing ID in clients that support it. None of this checks a stream version.

Publishing must use publisher confirms and mandatory=true: RabbitMQ confirms an unroutable message too, and only a mandatory publish produces a basic.return, which the broker sends before the basic.ack. The publisher below treats a return as failure, so a missing binding cannot advance the relay checkpoint.

go
// Package rabbitrelay publishes the committed event feed to RabbitMQ.
// PostgreSQL remains the event store; RabbitMQ is transport. A RabbitMQ
// stream adds a replayable, retention-bounded copy for subscribers.
package rabbitrelay

import (
	"context"
	"errors"
	"fmt"

	amqp "github.com/rabbitmq/amqp091-go"

	"academy/event-sourcing-cqrs/es"
)

var (
	ErrNacked     = errors.New("broker nacked the publish")
	ErrUnroutable = errors.New("message returned as unroutable")
)

// DeclareStream declares a durable RabbitMQ stream (not a classic or quorum
// queue): reading does not remove messages. Retention discards whole old
// segments, so rebuilds read PostgreSQL, never this stream.
func DeclareStream(ch *amqp.Channel, name, maxAge string) error {
	_, err := ch.QueueDeclare(name, true, false, false, false, amqp.Table{
		"x-queue-type": "stream",
		"x-max-age":    maxAge, // for example "7D"
	})
	return err
}

// Publisher sends one message at a time with publisher confirms and
// mandatory=true, so "unroutable" cannot masquerade as "confirmed".
type Publisher struct {
	ch       *amqp.Channel
	returns  chan amqp.Return
	exchange string
}

func NewPublisher(ch *amqp.Channel, exchange string) (*Publisher, error) {
	if err := ch.Confirm(false); err != nil {
		return nil, fmt.Errorf("enable confirms: %w", err)
	}
	// The broker sends basic.return before basic.ack for a mandatory
	// unroutable message, and the client enqueues it before resolving the ack.
	returns := ch.NotifyReturn(make(chan amqp.Return, 1))
	return &Publisher{ch: ch, returns: returns, exchange: exchange}, nil
}

// Publish satisfies es.PublishFunc.
func (p *Publisher) Publish(ctx context.Context, e es.Event) error {
	dc, err := p.ch.PublishWithDeferredConfirmWithContext(ctx, p.exchange, RoutingKey(e), true, false, Message(e))
	if err != nil {
		return err
	}
	acked, err := dc.WaitContext(ctx)
	if err != nil {
		return fmt.Errorf("confirm outcome unknown for %s: %w", e.EventID, err)
	}
	select {
	case r := <-p.returns:
		return fmt.Errorf("%w: %s %d %s", ErrUnroutable, r.MessageId, r.ReplyCode, r.ReplyText)
	default:
	}
	if !acked {
		return fmt.Errorf("%w: %s", ErrNacked, e.EventID)
	}
	return nil
}

// RoutingKey lets topic bindings select by event type, e.g. "account.MoneyWithdrawn".
func RoutingKey(e es.Event) string { return "account." + e.Type }

// Message maps an event to AMQP properties. MessageId carries the stable
// event ID that consumers deduplicate on; headers carry both positions.
func Message(e es.Event) amqp.Publishing {
	return amqp.Publishing{
		ContentType:  "application/json",
		DeliveryMode: amqp.Persistent,
		MessageId:    e.EventID,
		Type:         e.Type,
		Timestamp:    e.OccurredAt,
		Headers: amqp.Table{
			"stream_id":       e.StreamID,
			"stream_version":  e.StreamVersion,
			"global_position": e.GlobalPosition,
			"schema_version":  int32(e.SchemaVersion),
		},
		Body: e.Data,
	}
}

// StreamConsumerArgs attaches a consumer to a RabbitMQ stream at an offset
// spec: "first", "last", "next", a numeric offset or a timestamp. Streams
// require a per-consumer prefetch (ch.Qos) and manual acknowledgements.
func StreamConsumerArgs(offset any) amqp.Table {
	return amqp.Table{"x-stream-offset": offset}
}
go
package rabbitrelay

import (
	"testing"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"

	"academy/event-sourcing-cqrs/es"
)

func TestMessageCarriesIdentityAndPositions(t *testing.T) {
	e := es.Event{EventID: "cmd-9/0", StreamID: "acc-1", StreamVersion: 4, GlobalPosition: 812,
		Type: es.TypeMoneyWithdrawn, SchemaVersion: 2, Data: []byte(`{"amount":30,"reason":"atm"}`),
		OccurredAt: time.Unix(1, 0)}
	m := Message(e)
	if m.MessageId != "cmd-9/0" || m.DeliveryMode != amqp.Persistent || string(m.Body) != string(e.Data) {
		t.Fatalf("message %+v", m)
	}
	if m.Headers["stream_version"] != int64(4) || m.Headers["global_position"] != int64(812) {
		t.Fatalf("headers %+v", m.Headers)
	}
	if err := m.Headers.Validate(); err != nil {
		t.Fatalf("headers not AMQP-encodable: %v", err)
	}
	if RoutingKey(e) != "account.MoneyWithdrawn" {
		t.Fatal(RoutingKey(e))
	}
}
NeedRabbitMQ primitiveMissing
Replayable fan-outStream + x-stream-offsetPer-key version check
Durable acceptancePublisher confirms, persistent messagesAtomicity with the database
Unroutable detectionmandatory + basic.returnNothing if mandatory=false (default)
Rebuild from position 0Not reliable with retentionUse the event store

Kafka ​

Keying records by stream ID keeps one account's events in order inside a partition. Kafka has no conditional append on the latest offset of a key, so it cannot enforce expected version: two producers can both publish "version 8". Consumers check stream_version headers and stop on gaps (CheckVersion). Compaction keeps the latest value per key and therefore breaks history replay for event topics (see Log compaction); use cleanup.policy=delete for event transport and compact for latest-state topics, and check per-topic error codes when creating topics.

Kafka transactions make writes to several Kafka partitions atomic and, in consume-transform-produce loops, include consumer offsets; they do not include the PostgreSQL relay checkpoint, so the relay stays at least once. The franz-go idempotent producer (on by default) removes duplicates from the client's internal retries, not from a relay that restarts and republishes.

go
// Package kafkarelay publishes the committed event feed to Kafka. Kafka is
// transport and a replay buffer here: it has no per-key expected-version
// check, so it cannot be the system of record for these streams.
package kafkarelay

import (
	"context"
	"errors"
	"fmt"
	"strconv"

	"github.com/twmb/franz-go/pkg/kerr"
	"github.com/twmb/franz-go/pkg/kgo"
	"github.com/twmb/franz-go/pkg/kmsg"

	"academy/event-sourcing-cqrs/es"
)

// Topic configurations. Values are strings, as Kafka expects.
var (
	// Every event, keyed by stream ID. "delete" keeps all records until
	// retention: compaction here would keep only the LAST event per account
	// and destroy the history a consumer would replay.
	EventTopicConfig = map[string]string{
		"cleanup.policy": "delete",
		"retention.ms":   "604800000", // 7 days; PostgreSQL holds the full history
	}
	// Latest balance per account (event-carried state). Compaction fits:
	// only the newest value per key matters. A null value is a tombstone.
	LatestStateTopicConfig = map[string]string{
		"cleanup.policy":        "compact",
		"min.compaction.lag.ms": "3600000",  // keep at least 1 h of uncompacted head
		"delete.retention.ms":   "86400000", // tombstones visible for 1 day
	}
)

var ErrTopicExists = errors.New("topic already exists: verify its configuration")

// CreateTopic creates one topic and checks the per-topic error code, which a
// successful request can still carry.
func CreateTopic(ctx context.Context, cl *kgo.Client, name string, partitions int32, rf int16, cfg map[string]string) error {
	req := kmsg.NewPtrCreateTopicsRequest()
	req.TimeoutMillis = 30000
	t := kmsg.NewCreateTopicsRequestTopic()
	t.Topic, t.NumPartitions, t.ReplicationFactor = name, partitions, rf
	for k, v := range cfg {
		c := kmsg.NewCreateTopicsRequestTopicConfig()
		c.Name, c.Value = k, kmsg.StringPtr(v)
		t.Configs = append(t.Configs, c)
	}
	req.Topics = append(req.Topics, t)
	resp, err := req.RequestWith(ctx, cl)
	if err != nil {
		return err
	}
	if len(resp.Topics) != 1 {
		return fmt.Errorf("create %s: %d topic results", name, len(resp.Topics))
	}
	switch err := kerr.ErrorForCode(resp.Topics[0].ErrorCode); {
	case err == nil:
		return nil
	case errors.Is(err, kerr.TopicAlreadyExists):
		return fmt.Errorf("%w: %s", ErrTopicExists, name)
	default:
		return fmt.Errorf("create %s: %w", name, err)
	}
}

// Record keys by stream ID: one account's events share a partition and keep
// their order. Headers carry what consumers need to detect gaps and duplicates.
func Record(topic string, e es.Event) *kgo.Record {
	return &kgo.Record{
		Topic: topic,
		Key:   []byte(e.StreamID),
		Value: e.Data,
		Headers: []kgo.RecordHeader{
			{Key: "event_id", Value: []byte(e.EventID)},
			{Key: "event_type", Value: []byte(e.Type)},
			{Key: "schema_version", Value: []byte(strconv.Itoa(e.SchemaVersion))},
			{Key: "stream_version", Value: []byte(strconv.FormatInt(e.StreamVersion, 10))},
			{Key: "global_position", Value: []byte(strconv.FormatInt(e.GlobalPosition, 10))},
		},
		Timestamp: e.OccurredAt,
	}
}

// Publisher returns an es.PublishFunc. franz-go enables the idempotent
// producer by default, which removes broker-side duplicates from internal
// retries; it does not dedupe a relay that restarts and republishes.
func Publisher(cl *kgo.Client, topic string) es.PublishFunc {
	return func(ctx context.Context, e es.Event) error {
		return cl.ProduceSync(ctx, Record(topic, e)).FirstErr()
	}
}

// PublishWithState writes the event and the new latest-state value in one
// Kafka transaction (client built with kgo.TransactionalID). Atomic for the
// two Kafka topics only; the PostgreSQL relay checkpoint is a separate write.
func PublishWithState(ctx context.Context, cl *kgo.Client, eventTopic, stateTopic string, e es.Event, state []byte) error {
	if err := cl.BeginTransaction(); err != nil {
		return err
	}
	st := &kgo.Record{Topic: stateTopic, Key: []byte(e.StreamID), Value: state}
	if err := cl.ProduceSync(ctx, Record(eventTopic, e), st).FirstErr(); err != nil {
		if abortErr := cl.EndTransaction(ctx, kgo.TryAbort); abortErr != nil {
			return errors.Join(err, abortErr)
		}
		return err
	}
	return cl.EndTransaction(ctx, kgo.TryCommit)
}

// ErrVersionGap means a consumer saw stream_version n+2 after n: resync
// that stream from the event store instead of guessing.
var ErrVersionGap = errors.New("stream version gap")

// Decision is what a consumer should do with one record.
type Decision int

const (
	Apply     Decision = iota
	Duplicate          // already applied: acknowledge and skip
)

// CheckVersion compares a record's stream_version with the last version the
// consumer applied for that key (stored next to its read model).
func CheckVersion(lastApplied int64, rec *kgo.Record) (Decision, int64, error) {
	var v int64 = -1
	for _, h := range rec.Headers {
		if h.Key == "stream_version" {
			parsed, err := strconv.ParseInt(string(h.Value), 10, 64)
			if err != nil {
				return 0, 0, err
			}
			v = parsed
		}
	}
	switch {
	case v < 1:
		return 0, 0, errors.New("missing stream_version header")
	case v <= lastApplied:
		return Duplicate, v, nil
	case v == lastApplied+1:
		return Apply, v, nil
	default:
		return 0, v, fmt.Errorf("%w: key %s last %d got %d", ErrVersionGap, rec.Key, lastApplied, v)
	}
}
go
package kafkarelay

import (
	"errors"
	"testing"

	"academy/event-sourcing-cqrs/es"
)

func TestRecordAndVersionCheck(t *testing.T) {
	e := es.Event{EventID: "c/0", StreamID: "acc-1", StreamVersion: 5, GlobalPosition: 99,
		Type: es.TypeMoneyDeposited, SchemaVersion: 1, Data: []byte(`{"amount":7}`)}
	rec := Record("account-events", e)
	if string(rec.Key) != "acc-1" {
		t.Fatalf("key %q", rec.Key)
	}
	cases := []struct {
		last int64
		want Decision
		gap  bool
	}{{4, Apply, false}, {5, Duplicate, false}, {9, Duplicate, false}, {3, 0, true}}
	for _, c := range cases {
		d, v, err := CheckVersion(c.last, rec)
		if c.gap != errors.Is(err, ErrVersionGap) || (!c.gap && (d != c.want || v != 5)) {
			t.Errorf("last=%d: d=%v v=%d err=%v", c.last, d, v, err)
		}
	}
}

func TestConfigsMatchPurpose(t *testing.T) {
	if EventTopicConfig["cleanup.policy"] != "delete" {
		t.Error("event history topic must not be compacted")
	}
	if LatestStateTopicConfig["cleanup.policy"] != "compact" {
		t.Error("latest-state topic should be compacted")
	}
}
NeedKafka primitiveMissing
Per-stream orderKey → partitionOrder across partitions
Expected versionNoneMust be checked in the store
Latest statecleanup.policy=compact, tombstonesFull history
Atomic multi-topic writeTransactions (transactional.id)External database in the same transaction

Redis Streams ​

XADD with an explicit ID requires an ID greater than the stream's top entry and otherwise fails with "The ID specified in XADD is equal or smaller than the target stream top item". Using the global position as the ID (812-0) makes the relay ordered and its retries detectable: after that error the relay reads the entry with XRANGE and accepts it only if the stored event_id matches, because the error alone does not prove the ID exists. This is not a CAS on an account's stream version; two writers of different accounts' events would both succeed. Replay uses exclusive ranges (XRANGE key (812-0 +, Redis 6.2+). Do not trim with MAXLEN or MINID if any consumer relies on full history, and remember durability depends on AOF/RDB settings (appendfsync everysec can lose about a second of writes).

go
// Package redisrelay copies the committed event feed into a Redis stream
// whose entry IDs equal the PostgreSQL global position. Explicit IDs make the
// relay idempotent and ordered; they are NOT an expected-version check for an
// account stream, which only PostgreSQL performs.
package redisrelay

import (
	"context"
	"errors"
	"fmt"
	"strconv"
	"strings"

	"github.com/redis/go-redis/v9"

	"academy/event-sourcing-cqrs/es"
)

var ErrDiverged = errors.New("redis stream holds a different entry at this ID")

// EntryID maps global position p to "p-0". XADD requires each explicit ID to
// be greater than the stream's top ID, so the feed order is enforced by Redis.
func EntryID(e es.Event) string { return strconv.FormatInt(e.GlobalPosition, 10) + "-0" }

// Values are flat field/value pairs; Data stays the raw JSON payload.
func Values(e es.Event) map[string]any {
	return map[string]any{
		"event_id":       e.EventID,
		"stream_id":      e.StreamID,
		"stream_version": e.StreamVersion,
		"type":           e.Type,
		"schema_version": e.SchemaVersion,
		"data":           string(e.Data),
	}
}

// Publisher returns an es.PublishFunc. There is deliberately no MAXLEN or
// MINID: a consumer that replays this stream would silently miss trimmed
// history. If you trim, consumers must resync from PostgreSQL instead.
func Publisher(rdb *redis.Client, key string) es.PublishFunc {
	return func(ctx context.Context, e es.Event) error {
		err := rdb.XAdd(ctx, &redis.XAddArgs{Stream: key, ID: EntryID(e), Values: Values(e)}).Err()
		if err == nil || !IDTooSmall(err) {
			return err
		}
		// Retry after a lost reply, or a second relay: the ID may already be
		// there. "Equal or smaller" alone does not prove it is OUR entry.
		got, rerr := rdb.XRange(ctx, key, EntryID(e), EntryID(e)).Result()
		if rerr != nil {
			return errors.Join(err, rerr)
		}
		return SameEntry(got, e)
	}
}

// IDTooSmall recognises Redis's rejection of a non-increasing explicit ID.
func IDTooSmall(err error) bool {
	return err != nil && strings.Contains(err.Error(), "equal or smaller than the target stream top item")
}

// SameEntry accepts a duplicate only when the stored entry has our event ID.
func SameEntry(got []redis.XMessage, e es.Event) error {
	if len(got) == 1 && got[0].ID == EntryID(e) && got[0].Values["event_id"] == e.EventID {
		return nil
	}
	return fmt.Errorf("%w: %s", ErrDiverged, EntryID(e))
}

// ReadAfter replays entries strictly after lastID, using the exclusive "("
// range prefix (Redis 6.2+). Use "0-0" to start from the beginning.
func ReadAfter(ctx context.Context, rdb *redis.Client, key, lastID string, count int64) ([]redis.XMessage, error) {
	return rdb.XRangeN(ctx, key, "("+lastID, "+", count).Result()
}
go
package redisrelay

import (
	"errors"
	"testing"

	"github.com/redis/go-redis/v9"

	"academy/event-sourcing-cqrs/es"
)

func TestEntryIDAndDuplicateResolution(t *testing.T) {
	e := es.Event{EventID: "c/0", StreamID: "acc-1", GlobalPosition: 812}
	if EntryID(e) != "812-0" {
		t.Fatal(EntryID(e))
	}
	ours := []redis.XMessage{{ID: "812-0", Values: map[string]any{"event_id": "c/0"}}}
	if err := SameEntry(ours, e); err != nil {
		t.Fatalf("own duplicate rejected: %v", err)
	}
	theirs := []redis.XMessage{{ID: "812-0", Values: map[string]any{"event_id": "other/0"}}}
	if err := SameEntry(theirs, e); !errors.Is(err, ErrDiverged) {
		t.Fatalf("foreign entry accepted: %v", err)
	}
	if err := SameEntry(nil, e); !errors.Is(err, ErrDiverged) {
		t.Fatal("missing entry accepted: top ID is larger but 812-0 was never written")
	}
	if !IDTooSmall(errors.New("ERR The ID specified in XADD is equal or smaller than the target stream top item")) {
		t.Fatal("redis error not recognised")
	}
}
NeedRedis primitiveMissing
Ordered relayExplicit increasing IDsVersion check per aggregate
ReplayXRANGE / XREAD from an IDHistory after trimming
Consumer groupsXREADGROUP, XACKRebuild semantics
DurabilityAOF appendfsync policySynchronous replication by default

Other products ​

ProductRelevant primitiveEvent-store fit
KurrentDB (EventStoreDB)Streams, expected revision, $all, $maxAge / $maxCountPurpose-built store
NATS JetStreamNats-Expected-Last-Subject-Sequence, Nats-Msg-Id deduplication windowPer-subject optimistic concurrency exists
Apache PulsarTopic compaction distinct from retention, respects retentionSame compaction caveat as Kafka
Amazon SQS FIFO5-minute deduplication intervalQueue, not a store

In production systems ​

  • PostgreSQL documents that nextval values are never rolled back and that sequences cannot provide gapless numbering; that fact is why a bigserial cursor is unsafe for projections.
  • Marten's async daemon documentation describes the high water mark, which stops below holes in the event sequence and skips a hole only once no running transaction could still fill it, and the QuickAppend mode that makes gaps less likely.
  • KurrentDB's stream documentation describes soft delete via TruncateBefore, hard delete with a $streamDeleted tombstone, $maxAge/$maxCount, and scavenging that physically removes events.
  • Kafka's design documentation lists the compaction guarantees and the delete.retention.ms bound for tombstones; the topic configuration reference lists cleanup.policy default delete.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

Start with the store, one projection inline or asynchronous in the same process, and read-your-writes through the token. Example: a wallet module in a Laravel monolith uses EventStore::execute from controllers and runs BalanceProjector::project('balances_v1') from a scheduled command every second; the balance page passes atLeast from the last response.

Modular monolith: explicit owners ​

Each module owns its streams and projections; other modules read public read models or subscribe to the feed through an internal relay, never query another module's events rows directly. Example: payments owns acc-* streams; reporting owns monthly_statements_v3 built from the shared feed, and a new statement layout is rolled out as v4 blue/green.

Microservices: what survives the boundary ​

The event store and its expected-version check stay inside one service. Other services receive integration events through a relay with confirms, deduplicate by event ID, and cannot assume a global order across services. Example: wallet appends MoneyWithdrawn, relays an AccountDebited contract to Kafka keyed by account; fraud consumes it, checks stream_version per key, and stores its own state; a disputed charge becomes WithdrawalReversed in wallet and a separate AccountCredited integration event. Cross-service consistency uses sagas, not a shared event store.

Distributed data: replicas, shards and regions ​

A read replica lags: a projector reading from a replica sees commit order, but later; read-your-writes tokens must compare against the replica's projection checkpoint, not the primary's head. Sharding streams across databases gives one feed per shard; consumers merge per-shard positions and never get a total order. Multi-region active-active appends to the same stream need consensus or a single home region per stream; asynchronous multi-master replication cannot enforce expected version.

Scaling path ​

LoadDesign
1× (tens of appends/s)One PostgreSQL, allocator lock, async projector in-process
10× (hundreds/s)Batch events per command, short transactions, projector per read model, snapshots for long streams, measure allocator wait
100× (thousands/s)Replace the allocator with gap detection or logical-decoding CDC, shard streams by key, or a purpose-built store; projections scale by partitioning on stream ID

Lab ​

Expected, not run for every database and broker step: no Docker, database or broker was started. Use a disposable PostgreSQL where you have one; the Go unit tests run without it.

1. Run the pure tests ​

bash
cd docs/snippets/messaging/event-sourcing-cqrs/go
go test ./...
# ok  academy/event-sourcing-cqrs/es
# ok  academy/event-sourcing-cqrs/brokers/kafka  (rabbitmq, redisstreams likewise)

2. Watch the allocator serialize two appends ​

text
1 psql A -> BEGIN; SELECT next_position FROM feed_allocator WHERE id = 1 FOR UPDATE;   -- 1
2 psql B -> BEGIN; SELECT next_position FROM feed_allocator WHERE id = 1 FOR UPDATE;   -- waits
3 psql A -> UPDATE feed_allocator SET next_position = 2 WHERE id = 1; COMMIT;
4 psql B -> returns 2 (the updated row, Read Committed re-check)

Expected, not run. Repeat with ROLLBACK in step 3: B returns 1 and no gap exists.

3. Reproduce the bigserial skip (in a scratch table) ​

sql
CREATE TABLE seq_demo (pos bigserial PRIMARY KEY, note text);
-- psql A: BEGIN; INSERT INTO seq_demo (note) VALUES ('slow') RETURNING pos;   -- 1, keep open
-- psql B: INSERT INTO seq_demo (note) VALUES ('fast') RETURNING pos;          -- 2, autocommit
-- psql C: SELECT pos FROM seq_demo WHERE pos > 0 ORDER BY pos;                -- 2 only
-- psql A: COMMIT;   a reader that stored checkpoint 2 never reads pos 1

4. Retry a command after an unknown commit ​

Call Execute twice with the same CommandID and intent: expected {StreamVersion: 3, LastPosition: 812, Duplicate: true} the second time and one row in events. Change the amount and keep the ID: expected ErrCommandIDReused. Expected, not run.

5. Blue/green rebuild ​

text
1 Project("balances_v2", 500) in a loop until it returns 0
2 head := Head(); ActivateProjection("balances", "balances_v2", head)
3 QueryBalance("acc-42", token) -> AsOf >= token
4 Insert an AccountFrozen v1 row by hand in a scratch DB -> Project returns ErrUnknownEvent, checkpoint unchanged

6. Broker checks ​

bash
kafka-configs.sh --bootstrap-server localhost:9092 --describe --entity-type topics --entity-name account-events
# expected, not run: cleanup.policy=delete
redis-cli XADD acct-feed 812-0 event_id c-77/0
redis-cli XADD acct-feed 812-0 event_id c-77/0
# expected, not run: (error) ERR The ID specified in XADD is equal or smaller than the target stream top item
rabbitmqctl list_queues name type messages
# expected, not run: account-feed  stream  ...

Common misconceptions ​

BeliefReality
CQRS requires event sourcingCQRS splits models; the query model can be a view in the same database
CQRS means eventual consistencySame-transaction query models are immediately consistent
Event sourcing needs KafkaThe store needs expected-version appends and a gap-free order; PostgreSQL can provide both
bigserial orders the feedValues are assigned before commit and can become visible out of order
Expected version makes retries idempotentIt stops concurrent writes; retries need command receipts
Snapshots are the truthThey are disposable caches of committed history
A projector should skip unknown eventsSkipping loses facts permanently; fail closed
Rebuild = truncate + replayReaders see partial data; use versioned projections
A compacted topic is an event storeCompaction keeps only the latest record per key
Redis explicit IDs give optimistic concurrencyThey enforce increasing IDs per key, not per-aggregate versions
Immutable logs cannot erase dataCrypto-shredding, retention and deletes exist, with copies to track
Crypto-shredding guarantees legal complianceIt addresses one store; compliance needs a full data inventory and legal review
Banks keep no balances, only eventsSome ledgers work that way; it is an analogy, not a universal fact

Cheat sheet ​

TopicRemember
AppendLock allocator → receipt → fold → decide → CAS → insert → advance → receipt → COMMIT
Expected versionAnyVersion, NoStream, exact; retry with new version, same command ID
Global positionNo gaps, commit order; allocator lock, gap detection or CDC
LoadREPEATABLE READ read-only; snapshot validated; final version = head
SnapshotFrom committed history; format version; never overwrite newer
ProjectionRows + checkpoint in one TX; stream_version = v - 1; affected = 1
Unknown eventStop; deploy a reader; rerun
RebuildNew projection version, catch up, activate at head, drop old later
UpcastingPure, on read, strict decode, tested per version
Read-your-writesReturn position; query with atLeast; wait or fall back
CorrectionsCompensating events; event time vs processing time
PrivacySeal per subject; destroy key; inventory all copies
KafkaKey = stream; no CAS; delete for events, compact for state
RabbitMQStreams for replay; confirms + mandatory
Redis StreamsExplicit IDs = ordered relay, not CAS; no trimming if replay relies on history

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does a bigserial cursor lose events even without rollbacks? Important ​

Answer

Answer: The value is assigned at insert time. A transaction with a smaller value can commit after one with a larger value; a reader that saw the larger one and stored it as checkpoint never reads the smaller one.

2 — What does the allocator lock cost, and what are the alternatives? Good to know ​

Answer

Answer: All appends are serialized behind one row lock. Alternatives are gap detection with a high water mark (as in Marten) or reading committed changes through logical-decoding CDC.

3 — Why is expected version not enough for a client retry? Important ​

Answer

Answer: If the first attempt committed but the reply was lost, the retry fails the CAS, the client reloads and may decide the same intent again. A command receipt returns the stored result instead.

4 — When may a snapshot be trusted on load? Important ​

Answer

Answer: When its format matches the current code, its stream ID matches, its version is at most the committed head, and it was produced from committed events. Otherwise replay from the start.

5 — Why must a projection update its rows and checkpoint in one transaction? Must-know ​

Answer

Answer: Otherwise a crash between them either skips the batch (checkpoint first) or applies it twice (rows first) on restart.

6 — A projector meets MoneyWithdrawn v3 but knows v2. What should it do? Good to know ​

Answer

Answer: Stop without moving the checkpoint, alert, deploy a build that understands v3, and rerun. Skipping would lose the event.

7 — Is a system that uses separate command and query handlers on one PostgreSQL database CQRS? Must-know ​

Answer

Answer: Yes. CQRS is the separation of models; events, brokers, separate databases and eventual consistency are optional.

8 — How do you rebuild a read model without showing users a half-empty table? Important ​

Answer

Answer: Build a new projection version with its own rows and checkpoint, let it catch up, activate it once its checkpoint reaches the head, and drop the old version later.

9 — Why can a compacted Kafka topic not replace the event store? Must-know ​

Answer

Answer: Compaction keeps only the latest record per key, so replay from the start returns final values, not the sequence of facts. Kafka also has no expected-version check.

10 — What does deleting a subject key achieve, and what does it not? Good to know ​

Answer

Answer: Sealed fields for that subject become unreadable in every event row. Plaintext copies in read models, logs, caches, search indexes, broker topics and backups of the key table are not affected.

11 — Why does the Redis relay read the entry back after an "equal or smaller" error? Good to know ​

Answer

Answer: The error says only that the ID is not greater than the stream's top. The entry may be ours (a retried publish) or never written; only an XRANGE check of the event_id tells which.

Glossary ​

TermMeaning
EventImmutable fact in past tense
Event sourcingStoring events as the system of record and deriving state by folding them
Event storeDatabase for streams with expected-version appends and ordered reads
StreamOrdered events of one aggregate, versions 1..n
AggregateConsistency boundary whose invariants one stream protects
Append-onlyRows are inserted, never updated or deleted in normal operation
Expected versionVersion the append requires the stream to be at
Optimistic concurrencyDetect conflicting writes at commit time instead of locking while deciding
Global positionGap-free, commit-ordered number across all streams
Feed allocatorSingle locked row that assigns global positions in this store
High water markMarten's highest position below which all events are known committed
Decide / evolve (fold)Pure decision function / pure state transition per event
ReplayRe-running events to rebuild state or a read model
Snapshot (rolling snapshot)Cached state at a stream version, used to shorten loads
ProjectionCode that turns events into a read model
Read modelQuery-optimized data derived from events
CheckpointLast global position a projection or relay has processed
Live / inline / async projectionFold at read time / same transaction / background with checkpoint
RebuildRecomputing a read model from the event history
Blue/green projectionNew projection version built beside the old, then switched
Fail closedStop processing on unknown or inconsistent input
Event versioningType + schema version on every event
Upcaster / upcastingRead-time conversion of an old event shape to the current one
CQRSSeparate command and query models
CommandRequest to change state; may be rejected
QueryRequest for data that changes nothing
Eventual consistencyRead model converges after a delay
Read-your-writesA client sees its own completed writes
Read-your-writes tokenPosition returned by a write and required by a read
IdempotencyRepeating an operation has no additional effect
Command receiptStored command ID, fingerprint and result
FingerprintHash of a command's intent, excluding its ID
Event time / processing timeWhen it happened / when the system recorded it
Compensating eventNew event that reverses the effect of an earlier one
Retroactive event / bi-temporalFowler's terms for changing past facts and modelling two time axes
Crypto-shreddingDestroying a per-subject key to make sealed data unreadable
TombstoneDeletion marker: Kafka null-value record, KurrentDB $streamDeleted
TruncateBefore / scavengingKurrentDB soft-delete metadata / physical removal process
Log compactionKafka retention keeping the latest record per key
cleanup.policyKafka topic setting: delete, compact, or both
delete.retention.ms / min.compaction.lag.msTombstone visibility bound / minimum uncompacted age
Kafka transactionsAtomic writes across Kafka partitions, optionally with consumer offsets
Idempotent producerKafka producer feature removing duplicates from internal retries
RabbitMQ StreamsAppend-only, non-destructive RabbitMQ queue type
x-stream-offset / x-max-ageStream consumer start position / stream retention
Publisher confirmsBroker acknowledgement that a published message was accepted
mandatory / basic.returnPublish flag / broker's return of an unroutable message
XADD / XRANGERedis append with optional explicit ID / range read
MAXLEN / MINIDRedis stream trimming options
Nats-Expected-Last-Subject-SequenceNATS JetStream per-subject optimistic concurrency header
EventStoreDB/KurrentKurrentDB, formerly EventStoreDB, a database built for event streams
Marten.NET library turning PostgreSQL into a document and event store
AxonAxon Framework, JVM framework for CQRS and event sourcing
spatie/laravel-event-sourcingLaravel package with aggregates, projectors and reactors
ReactorSpatie handler for side effects, not called during replay
OutboxTable-based reliable publication, see the outbox chapter
FowlerMartin Fowler, author of the Event Sourcing article and CQRS bliki
Greg YoungAuthor of the CQRS Documents who popularized CQRS with event sourcing
SQLSTATE 40001 / 23505PostgreSQL serialization failure / unique violation

References ​

Built by Morteza Negahi