Video in progress

You want to build event sourcing on PostgreSQL. How do you design the event store table, optimistic concurrency and snapshots?

I write events to a single append-only table with a unique key on (stream_id, version). The insert goes in with the expected version: a unique violation means a conflict. For long streams there's a snapshot table, and for read models you need a global sequence number and outbox/CDC.

📖 Answer

CREATE TABLE event (
    global_seq  bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    stream_id   uuid        NOT NULL,
    version     int         NOT NULL,
    type        text        NOT NULL,
    payload     jsonb       NOT NULL,
    created_at  timestamptz NOT NULL DEFAULT now(),
    UNIQUE (stream_id, version)
);

Writing: if the version at the time the aggregate was loaded was 7, the new events are added as 8, 9. If another process has already written 8, you get a unique_violation, and that's an optimistic concurrency conflict. The application reloads the aggregate and executes the command again. No lock is needed.

Reading: WHERE stream_id = ? ORDER BY version is fast thanks to the unique index. When a stream grows past a few hundred events, use a snapshot:

CREATE TABLE snapshot (
    stream_id uuid PRIMARY KEY,
    version   int   NOT NULL,
    state     jsonb NOT NULL
);

You rebuild the aggregate from the snapshot and the events after it.

The hardest part is "reading all events in order" for projections. Reading by global_seq is dangerous: identity values are handed out in the order they're taken, not in commit order. If 101 has committed and 100 hasn't yet, the reader reads 101, moves on, and loses 100. The solutions: logical decoding/CDC (in commit order), or the reader reads only up to a boundary where "all older transactions have finished" (based on pg_snapshot_xmin).

The table only grows, so you need a plan: partition by time, or archive old streams. And I'll be upfront: I choose event sourcing only in domains where audit and point-in-time reconstruction are truly needed by the business; for plain CRUD it's a lot of complexity.