How to Implement Event Sourcing Tables
Model event sourcing in SQL: append immutable events, derive current state by replay, version aggregates, and snapshot to bound replay cost.
On this page
Introduction
Event sourcing stores the history of changes instead of only the current state. Every change is an immutable event appended to a log, and the current state is derived by folding those events in order. The benefit is a complete, auditable history and the ability to rebuild any past state or add a new projection after the fact. The cost is that reads must replay events, which requires care as an aggregate’s history grows.
This tutorial implements event sourcing in SQL: an append-only events table, folding events to state, a version guard for concurrency, and snapshots to bound replay. The examples use PostgreSQL and SQL, but the model is storage-level and applies to any database.
Append immutable events
The events table is append-only: rows are inserted and never updated or deleted. Each row records the aggregate it belongs to, a monotonically increasing version within that aggregate, the event type, a payload describing what happened, and metadata such as when it was appended. The payload should describe the change in domain terms, not the resulting row, so a projection can interpret it without guessing at intent.
Make the event log the source of truth and treat any derived table as a cache that can be rebuilt. Resist updating an event to fix a mistake; instead append a compensating event, because an immutable log means the correction is part of the history too. This append-only discipline is what makes the log auditable and what makes replay reproducible.
CREATE TABLE account_events (
id bigint GENERATED ALWAYS AS IDENTITY,
account_id bigint NOT NULL,
version int NOT NULL,
type text NOT NULL, -- e.g. 'deposited', 'withdrawn'
payload jsonb NOT NULL,
recorded_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (account_id, version) -- also the version guard
);
CREATE INDEX idx_account_events_account ON account_events (account_id, version);
Derive state by folding events
Current state is a fold: start from an initial value and apply each event in version order. For an account, the state is a balance that rises on a deposit and falls on a withdrawal. The same events can feed different projections, such as a balance, a statement, or a risk score, each folding the events differently without changing the log.
Expose the derived state through a view or a materialized projection so queries do not replay on every read. A view computes state on demand; a materialized projection stores it and is refreshed when new events arrive. Choose the projection for hot reads and the view for occasional ones. The log remains the truth, and any projection can be dropped and rebuilt if the folding logic changes.
-- fold deposits and withdrawals into a balance per account
SELECT account_id,
sum((payload->>'amount')::numeric
* CASE WHEN type = 'deposited' THEN 1 ELSE -1 END) AS balance
FROM account_events
GROUP BY account_id;
Guard the aggregate version
The version column is both an ordering key and a concurrency guard. A unique constraint on (account_id, version) means two writers that both compute the next version as the same number cannot both insert; one succeeds and the other fails, and the loser reloads the current version and retries. This is optimistic concurrency at the aggregate level, and it prevents two events from being silently recorded at the same version and losing their relative order.
Append the event and update any read projection in the same transaction so the projection never reflects an event that was not committed, and so a projection update race cannot diverge from the log. Where the projection is eventually consistent by design, record the last applied version with the projection so a consumer can resume from exactly where it stopped.
-- optimistic append: fail if another writer took this version
INSERT INTO account_events (account_id, version, type, payload)
VALUES ($1, (SELECT coalesce(max(version),0)+1 FROM account_events WHERE account_id=$1),
$2, $3)
RETURNING version;
-- on unique violation, reload the aggregate and retry
Snapshot to bound replay cost
Replaying an aggregate’s entire history on every read is expensive once the history is long. A snapshot records the state at a version, and rebuild starts from the snapshot and folds only the events after it. Take a snapshot periodically, such as every hundred events, and store it alongside the version it covers. Then rebuilding a thousand-event aggregate folds at most the events since the last snapshot, a bounded number.
Snapshots are a cache, not the truth, so they must be rebuildable from the events and must never be the only copy of a state that cannot be recomputed. If the folding logic changes, discard the snapshots and rebuild them. Store the snapshot with its version so a rebuild knows exactly which events to replay after it, and test that replay-from-snapshot produces the same state as replay-from-scratch.
CREATE TABLE account_snapshots (
account_id bigint NOT NULL,
version int NOT NULL,
state jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (account_id, version)
);
-- rebuild: load latest snapshot, then fold events with version > snapshot.version
Test replay, concurrency, and snapshots
Test that folding all events for an aggregate yields the expected state. Test that two concurrent appends at the same computed version result in one success and one retry, not two rows at the same version, which the unique constraint should enforce. Test that replaying from a snapshot plus the subsequent events equals replaying from scratch. These three tests cover the fold, the concurrency guard, and the snapshot’s correctness.
psql -d app <<'SQL'
-- rebuild from snapshot and compare to full replay
SELECT balance FROM account_state_snapshot_replay(1); -- from snapshot + tail
SELECT balance FROM account_state_full_replay(1); -- from scratch; must be equal
SQL
Common pitfalls
Updating or deleting events, omitting the aggregate version so concurrent writes collide silently, replaying full history on every read without snapshots, treating a snapshot as the source of truth, and deriving projections outside the append transaction so they can diverge are the recurring mistakes. An append-only table, a version guard, snapshots, and transactional projection updates address them.
Conclusion
Event sourcing stores an immutable event log as the truth and derives state by folding it. Append events with a version guard, fold them into projections, snapshot to bound replay cost, and keep projections rebuildable. Self-check by asserting replay-from-snapshot equals replay-from-scratch and that concurrent appends cannot share a version. With the log as truth, any past state or new projection can be rebuilt from the events alone.
Sources: Martin Fowler: Event sourcing, PostgreSQL: INSERT and ON CONFLICT, PostgreSQL: Window functions for sequencing.
FAQ
- Is event sourcing the same as event streaming?
- No. Event sourcing is a persistence model where the event log is the source of truth for an aggregate's state. Event streaming is a transport for events between systems. They pair well, but event sourcing is about how you store state, not how you move it.
- Why add an aggregate version?
- The version orders events for one aggregate and enforces optimistic concurrency: a unique constraint on (aggregate_id, version) makes two writers appending at the same version race, and the loser must reload and retry. It also detects a gap in the stream.
Report a problem with this articleOpens a pre-filled issue on GitHub.