A trigger-guarded immutable event store, optimistic concurrency per stream, hybrid projections, and the race between transaction IDs and global_position that makes an async projection skip events forever
Published: November 21, 2026
Reading time: 17 min
Keywords: event sourcing postgresql, java event store, async projection, pg_current_xact_id, xid8, checkpoint
Payments Platform in practice series
The most common way to build an asynchronous projection on a relational event store goes like this: store the last processed global_position, read events with a higher position on every cycle, apply them and advance the checkpoint. It is simple, it passes every local test, and it has a defect that only shows up under real concurrency. A transaction that reserved position 50 can commit after another that reserved position 51. If the projection read 51 and moved the checkpoint, 50 later appears at a position the projection already considers done. The event raises no error, writes no log line and never reaches the projection. It is simply left out.
The Payments Platform has a whole ADR about this, ADR 0017, and an integration test that forces the commit order that causes the loss. This chapter starts with the event store, because the problem only makes sense once you know how events are written, and ends at the fence.
In chapter 2 I showed that the write repository rebuilds the aggregate from events. Now let's look at where those events come from. All code is from commit 5277f6c.
The project did not start with event sourcing. ADR 0004 turned it down for sensible reasons: rebuilding every payment from events would complicate idempotency and optimistic locking, and the product did not need an audit stream as the source of truth.
ADR 0016 changed the decision under a different context: the sample now needed replayable aggregate history and a payment history read model, while keeping its HTTP and RabbitMQ contracts unchanged. The storage choice is the part I find most interesting: PostgreSQL. The ADR rules out EventStoreDB and Kafka as the event store because they "add another stateful service without a need that PostgreSQL cannot meet for this sample".
That argument applies to many systems. Event sourcing is a data model, not a product. If you already run PostgreSQL, an append-only table with the right constraints covers most of what a dedicated event store offers, and keeps the local transaction with the outbox and the synchronous projections.
UPDATEThe event store is an ordinary table, created in the first migration:
-- src/main/resources/db/migration/V1__shared.sql:42-56
CREATE TABLE event_store (
global_position BIGSERIAL PRIMARY KEY,
stream_type VARCHAR(100) NOT NULL,
stream_id UUID NOT NULL,
stream_version BIGINT NOT NULL CHECK (stream_version > 0),
event_id UUID NOT NULL UNIQUE,
event_type VARCHAR(150) NOT NULL,
schema_version INT NOT NULL CHECK (schema_version > 0),
payload JSONB NOT NULL,
metadata JSONB NOT NULL,
occurred_at TIMESTAMPTZ NOT NULL,
recorded_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
transaction_id XID8 NOT NULL DEFAULT pg_current_xact_id(),
UNIQUE (stream_type, stream_id, stream_version)
);
Each column has a job:
global_position orders every event across every stream. It is what asynchronous projections use as a checkpoint.(stream_type, stream_id, stream_version) is unique. Two concurrent appends to the same payment cannot write the same version.schema_version travels with each event. The event contract is versioned from the first row written.transaction_id stores the XID of the transaction that wrote the row, as a 64-bit xid8. This column is the centerpiece of the fence.Immutability does not rely on a Java convention. The database refuses:
-- src/main/resources/db/migration/V1__shared.sql:75-85
CREATE FUNCTION reject_event_store_mutation() RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
RAISE EXCEPTION 'event_store rows are immutable' USING ERRCODE = '55000';
END;
$$;
CREATE TRIGGER event_store_immutable
BEFORE UPDATE OR DELETE ON event_store
FOR EACH ROW EXECUTE FUNCTION reject_event_store_mutation();
A hurried manual fix script, a misconfigured ORM or a generic cleanup job hits that trigger and fails. For a payments ledger, that guarantee is what justifies the model. Note the limit: TRUNCATE does not fire row-level triggers, and a superuser can disable the trigger. It protects against mistakes, not against whoever administers the database.
Appends happen in JdbcEventStore. The core of it:
// src/main/java/com/muse/payments/shared/infrastructure/eventstore/JdbcEventStore.java:69-77
lockStream(stream);
// Allocate the transaction ID before a sequence position can be reserved.
jdbcTemplate.queryForObject("SELECT pg_current_xact_id()::text", String.class);
long currentVersion = jdbcTemplate.queryForObject(SELECT_CURRENT_VERSION, Long.class,
stream.type(), stream.id());
if (currentVersion != expectedVersion) {
throw new OptimisticConcurrencyException("Expected stream version " + expectedVersion + " but found "
+ currentVersion + " for " + stream.type() + "/" + stream.id());
}
Three things happen in order.
Stream lock. lockStream runs SELECT pg_advisory_xact_lock(hashtextextended(?, 0)) keyed by stream_type:stream_id. It is a transaction-scoped advisory lock, released automatically on commit or rollback. It serializes appends to the same payment and lets different payments write in parallel. A global append lock would solve several problems in this chapter at once, and would kill throughput. ADR 0017 records the refusal explicitly: "No global append lock or new infrastructure is introduced".
XID allocation. The pg_current_xact_id() line looks like it does nothing, because the result is discarded. It forces PostgreSQL to assign a real transaction ID now, before any sequence position is reserved. Why that matters is explained in the fence section below.
Expected version. The aggregate knows which version it was loaded at. If the current version in the database differs, someone wrote in between, and the append fails with OptimisticConcurrencyException, which becomes a 409. If for some reason the advisory lock is not protecting the write (another write path, a bug), the UNIQUE (stream_type, stream_id, stream_version) constraint still turns the duplicate INSERT into a DuplicateKeyException, which the code also converts to a conflict (JdbcEventStore.java:95-98). Two layers for the same guarantee, and only one of them depends on the Java code being correct.
On the domain side, the EventSourcedAggregate base is small and plain Java:
// src/main/java/com/muse/payments/shared/domain/EventSourcedAggregate.java:16-21
protected final void raise(DomainEvent event) {
DomainEvent requiredEvent = Objects.requireNonNull(event, "Domain event cannot be null");
apply(requiredEvent);
registerEvent(requiredEvent);
version = Math.incrementExact(version);
}
A command calls raise, which applies the event to state, records it as pending and increments the version. On replay, the same apply runs for each historical event without recording anything as pending. Payment.apply is a pattern-matching switch over the aggregate's seven event types, ending in a default that throws for unknown events (Payment.java:202-266). A new event missing from the switch fails loudly on the first replay instead of being silently ignored.
The rule that keeps this correct: apply validates nothing; it only changes state. Validation lives in the command method (complete, cancel, settleFromProvider), before raise. A recorded event is a fact. If replay rejected an old fact because a business rule changed, the aggregate would become impossible to load.
Each event type is registered with a stable name and a schema version:
// src/main/java/com/muse/payments/payments/infrastructure/PaymentEventRegistryConfiguration.java:39-42
@Bean
EventTypeRegistration paymentCompletedRegistration() {
return new EventTypeRegistration("payments.payment-completed", 1, PaymentCompletedEvent.class);
}
There are 14 registrations in total: 7 for payments, 6 for identity and 1 for notifications. The name stored in the database is payments.payment-completed, not the Java class name. Renaming the class does not break the event store. Renaming the event type requires a new type, and compatible payload changes go through an EventUpcaster, an interface with supports(eventType, sourceSchemaVersion) and upcast(payloadJson).
ADR 0016 sums up the consequence in a sentence every team should read before adopting event sourcing: "Event names and payload schemas become durable contracts". As of the analyzed commit, every event is at version 1 and no concrete upcaster exists. The infrastructure is there and tested (EventSerializerTest), but the schema migration path has not yet been exercised with a real event.
Free and paid products to turn ideas into a foundation you can actually ship.
13 products availableContinue exploring similar topics
The same payment has two findById methods: one rebuilds the aggregate from events, the other reads an indexed projection. That is what CQRS means in the Payments Platform, with no second database.
A module boundary that only exists in a diagram does not exist. How the Payments Platform turns a forbidden dependency into a failing test, and when this design is the wrong call.
When the fraud provider goes down, the payment is held for review, never approved. How the Payments Platform fails closed, measures outbox and projection lag, and makes migrations and rebuilds verifiable.
A 47-point checklist to find bugs, security risks, and performance issues before launch.
Production-tested templates trusted by developers. Save weeks of setup on your next project.
ADR 0016 splits projections into two groups:
| Projection | Mode | Reason |
|---|---|---|
payments, users, refresh_tokens | Synchronous, in the append transaction | Read-after-write and uniqueness backstops (unique email, unique provider reference) |
notifications, payment_history | Asynchronous, with a durable checkpoint | Can lag without breaking the client contract |
The synchronous projection was covered in chapter 2. The asynchronous one runs in AsyncProjectionRunner, which every 250 ms (by default) reads a batch of events after the checkpoint, applies them and advances the checkpoint in the same transaction. The history projector is idempotent by construction: the INSERT into payment_history uses ON CONFLICT (payment_id, stream_version) DO NOTHING (PaymentHistoryProjector.java:25-29). Reapplying an already projected event does not duplicate a row.
That idempotency protects against processing twice. It does not protect against never processing. And never processing is exactly what a naive positional checkpoint does.
A relational event store has two orders that are easy to assume are the same:
global_position from the sequence.And there is a third order, the one that matters to readers: commit order. None of the three has to match the others. PostgreSQL sequences are not transactional: nextval hands out the next number immediately, and it is not returned on rollback. The position reflects when the INSERT happened, not when the commit happened.
ADR 0017 describes the scenario: "A transaction can acquire its XID before waiting, then append after a newer transaction has reserved a smaller global position. Filtering visible rows by transaction_id < snapshot.xmin alone could advance past an uncommitted lower position."
Here it is step by step, because this is exactly what the repository's test forces:
The transaction_id < pg_snapshot_xmin(pg_current_snapshot()) filter is the standard defense: only read rows from transactions older than the oldest active one, because those are certainly finished. In the scenario above, the filter is not enough. Transaction A has XID 100, below xmin (101), so its row passes. Position 50, from transaction B, is not visible yet. The projection processes 51, advances the checkpoint, and when B commits, 50 sits behind the checkpoint.
Nothing fails. The projection throws no exception, the event is in the event store and the aggregate rehydrates correctly. Only the read model is missing that row, and nobody notices until someone compares a payment's history with its stream.
The ADR 0017 fix has two parts, one in the append path and one in the reader.
In the append path, JdbcEventStore forces XID allocation before reserving a position (the SELECT pg_current_xact_id() line we saw earlier). PostgreSQL assigns XIDs lazily: a transaction only gets a real XID when it first writes. Without that line, a transaction could reserve a position with nextval and only receive its XID right after, when the row is written. Forcing the order creates a guarantee: every transaction holding a reserved position already had an XID before that reservation.
In the reader, AsyncProjectionRunner captures a horizon before processing:
// src/main/java/com/muse/payments/shared/infrastructure/eventstore/AsyncProjectionRunner.java:73-85
// XIDs may be allocated BEFORE a transaction appends. A bare xmin filter can
// therefore skip an invisible lower position while processing an older XID.
// Fence sequence allocation first, then wait for every transaction in that
// snapshot to finish before advancing a positional checkpoint past the fence.
private Horizon captureHorizon() {
long position = jdbcTemplate.queryForObject(
"SELECT CASE WHEN is_called THEN last_value ELSE 0 END FROM event_store_global_position_seq", Long.class);
// Allocate our own XID after reading the sequence: snapshot.xmax alone
// can equal an active newer XID when only an older transaction committed.
String boundary = jdbcTemplate.queryForObject(
"SELECT pg_current_xact_id()::text", String.class);
return new Horizon(position, boundary);
}
The horizon holds two values. position is the last number the sequence handed out (H). boundary is a fresh XID allocated after that read (F). Because these queries run outside an explicit transaction, each one is a short transaction that commits on its own.
Put the two parts together: any transaction that reserved a position up to H already had an XID before that reservation, and therefore before the reader allocated F. So its XID is lower than F. Once every transaction with an XID lower than F has finished, every position up to H is either committed or discarded. None is pending.
The runner waits for that condition before reading:
// src/main/java/com/muse/payments/shared/infrastructure/eventstore/AsyncProjectionRunner.java:116-123
public int poll(AsyncProjector projector) {
Horizon horizon = horizons.computeIfAbsent(projector.projectionName(), ignored -> captureHorizon());
Boolean settled = jdbcTemplate.queryForObject(
"SELECT pg_snapshot_xmin(pg_current_snapshot()) >= ?::xid8", Boolean.class,
horizon.transactionBoundary());
if (!Boolean.TRUE.equals(settled)) {
return 0;
}
If the current xmin has not reached the fence, some transaction older than the fence is still open, and the cycle ends without processing anything. Once xmin passes the fence, the runner processes batches, but only up to position H:
-- AsyncProjectionRunner.java:40-49 (SELECT_BATCH)
SELECT global_position, stream_type, stream_id, stream_version, event_id, event_type,
schema_version, payload::text AS payload_json, metadata::text AS metadata_json,
occurred_at, recorded_at, transaction_id::text AS transaction_id
FROM event_store
WHERE stream_type = ?
AND global_position > ?
AND global_position <= ?
AND transaction_id < pg_snapshot_xmin(pg_current_snapshot())
ORDER BY global_position
LIMIT ?
After consuming up to the horizon, it captures the next one. The checkpoint is read with FOR UPDATE SKIP LOCKED and updated in the same transaction that applies the events, so two runner instances do not process the same batch, and a crash mid-batch does not advance the checkpoint.
The comment about snapshot.xmax explains why the runner allocates its own XID instead of using the snapshot's xmax as the fence: xmax can equal the XID of a newer, still-active transaction when only an older one has committed. A freshly allocated XID is, by definition, higher than every XID that existed before it.
The argument above is subtle enough that I would not trust it without a test. AsyncProjectionIT uses CountDownLatch to coordinate two real transactions on PostgreSQL 16 in Testcontainers:
The test name already states the guarantee: olderXidWithLaterPositionCannotSkipUncommittedEarlierPosition. On November 21, 2026, I ran EventStoreIT, AsyncProjectionIT and ProjectionRebuildIT against PostgreSQL 16.15 in a container: 8 tests, 0 failures, 27.5 seconds.
ADR 0017 states the cost plainly: "Two short database queries per horizon and an extra XID are accepted for correctness. A long transaction delays asynchronous projections and raises observable lag."
The second sentence is the one that bites in production. The fence waits for every transaction with an XID lower than F to finish, not just the ones that wrote events. A report that opens a long transaction, a slow migration or a session left open in a SQL client holds back the whole database's xmin, and asynchronous projections stop advancing for as long as that lasts. The symptom shows up in the projection.lag metric and the ProjectionLagHigh alert, covered in chapter 5.
Two notes on that metric. First, a stuck xmin also hurts autovacuum, so a long transaction is already an operational problem with or without event sourcing. The fence just makes the effect visible sooner. Second, the gauge computes MAX(global_position) for the stream type minus the checkpoint. Because global_position is global and streams interleave, that number is a distance in positions, not an exact count of pending events of that type. It is a trend signal, not an exact queue length.
Sequence gaps from rollbacks are harmless, as the ADR notes. The checkpoint advances by positions read, not by positions expected.
Two mechanisms round out the event store.
Snapshots exist in the kernel (JdbcSnapshotStore) and are disposable by design. Loading filters by schema_version = ? with the version the code expects (JdbcSnapshotStore.java:21-23). If the state format changed, the old snapshot is simply not found and the aggregate replays from scratch. In practice, the production path does not yet use snapshots to speed up long streams. A payment has few events, so a full replay is cheap.
Rebuild reconstructs a projection from scratch using the event store. The process runs with APP_PROJECTION_REBUILD=<projection>, starts with no HTTP server, no consumers and no schedulers, resets the checkpoint, truncates the table, reprojects and exits. ProjectionRebuildRunner acquires the checkpoint before truncating, in the same lock order as the live runner (ProjectionRebuildRunner.java:73-75), which avoids deadlocking with a running instance. Independent rebuilds are why the foreign key between refresh_tokens and users was dropped in migration V7, as I described in chapter 1.
identity stream stores email and other personal data, and the table rejects UPDATE and DELETE. ADR 0016 says there is no erasure flow and that crypto-shredding (encrypting personal data with a per-subject key and destroying the key) must be decided before production use. Under GDPR or Brazil's LGPD, that is not a detail; it is a prerequisite.event_store. The table grows forever. Time partitioning or archiving closed streams is left for a future decision."Why does an asynchronous projection need an XID fence?" separates people who have read about event sourcing from people who have run it. The answer I would expect: sequence, XID and commit are three different orders; a positional checkpoint with an xmin filter can move past a lower position that has not committed yet; the fix is to allocate the XID before the position on append and, in the reader, only advance up to a sequence horizon once every transaction older than a fence XID has finished; the cost is that long transactions delay projections, which needs a metric and an alert.
The event store holds internal facts. They are not published directly to RabbitMQ. In chapter 4 I show the transactional outbox that bridges the two, idempotency leases in PostgreSQL, and the Stripe webhook that settles a payment exactly once even with at-least-once delivery on every hop.
If you are considering event sourcing for a production system and want to size the real cost before migrating, that is the kind of analysis I do at LEMON.DEV.
java-clean-arch-sample repository, commit 5277f6c (checked on November 21, 2026).AsyncProjectionIT.java.pg_current_xact_id, pg_current_snapshot, pg_snapshot_xmin).