# Transactions and revisions

> How one etcd request becomes one PostgreSQL transaction with a single revision.

---

LLMS index: [llms.txt](/llms.txt)

---

The `pg_etcd` extension evaluates each request inside one PostgreSQL transaction. The Publisher is the gateway component that owns this transaction and holds its provisional response. It sends the response to the client only after synchronous `COMMIT` succeeds without a warning.

To certify an observation, the extension writes WAL after reading that state. The Publisher then waits for synchronous `COMMIT` before sending the result.

## Execution order {#algorithm}

The gateway binds the request to its configured tenant and checks input limits before execution:

1. Begin a `READ COMMITTED` transaction with `synchronous_commit = on`.
2. Lock the single `etcd.meta` row and finish the lock command.
3. Take a new snapshot after any lock wait.
4. Execute the request using that snapshot.
5. If the request has no suitable logged change after its observations, write a certification barrier.
6. Return the provisional response to the Publisher.
7. Commit synchronously.
{.steps}

The Publisher sends the response only after `COMMIT` succeeds without a warning. KV changes, events and the revision manifest commit in the same transaction.

A snapshot taken before the lock wait can miss the preceding transaction's commit. Because of this, the lock command and the snapshot acquisition are separate operations inside the C extension; combining them in one SQL CTE does not provide the required post-lock snapshot.

The implementation also locks reads on `etcd.meta`. This keeps a single ordering rule across reads and writes, at the cost of serializing requests within a tenant.

## Txn evaluation {#txn}

Before locking metadata, the extension validates every branch structure, including unselected branches. It then uses the fresh post-lock snapshot to evaluate `compare` predicates and select nested `Txn` branches. Before applying any mutation, it checks the selected state, Lease attachments, response size and complete-revision budgets.

All selected nested comparisons use that initial snapshot. The selected operations then run in order, so a later `Range` inside the same `Txn` can observe an earlier `Put` in the same request.

Within a single selected execution path, a duplicate `Put` on the same key or an overlapping `Put` and `DeleteRange` is rejected with `InvalidArgument`. Mutually exclusive branches (`success` vs. `failure`) may touch the same key. Overlapping `DeleteRange` operations on the same path are permitted.

Each child response retains the revision from its execution point. A nested `Txn` response has an empty header, matching the reference etcd server, while its child responses retain their own headers.

## Revision rules {#revision}

In `etcd.meta`, `R` is the current KV revision, `C` is the logical compact revision, and `F` is the oldest retained history baseline floor. Fresh state has `R = 1`, `C = -1`, and `F = 0`. The first `Put` produces revision `2`. A same-value `Put` still increments the global revision `R` and the key's `version`.

The first actual KV change in a request allocates `R + 1`. All further KV changes in that request share this single revision. Reads, empty deletes (`deleted = 0`), Lease-only operations (`LeaseGrant`, `LeaseKeepAlive`, `LeaseTimeToLive`, `LeaseLeases`, or `LeaseRevoke` with no attached keys), `Compact`, and rolled-back transactions do not consume a KV revision.

Top-level `Range` treats a nonpositive revision (`<= 0`) as the current revision. A negative revision inside `Txn` is checked against `C` before normalization: on a fresh database (`C = -1`), a `Txn` `Range` at `-1` succeeds, while `-2` returns `OutOfRange` (`ErrCompacted`). After `Compact(0)`, a `Txn` `Range` at `-1` also returns `OutOfRange`. Revision `0` always selects the current revision.

## Why reads write a barrier {#barrier}

PostgreSQL can make a transaction locally visible before its synchronous replication wait finishes. If that wait is canceled or interrupted, another backend on the same host can observe data that has not met the publication contract.

A read therefore captures state and then writes a logged barrier row to `etcd.publication_barrier`. A normal synchronous `COMMIT` of that later WAL record covers the earlier records that the read observed. A write request uses its own logged table changes. An empty transaction, plain `SELECT`, LSN read, unlogged write, or earlier barrier cannot certify a new observation.

This rule applies equally to false `Txn` comparisons, state-dependent errors (`ErrCompacted`, `ErrFutureRev`, `ErrLeaseNotFound`), Watch `Created` responses, progress notifications, `Status`, and compaction watermarks. A certified snapshot can serve multiple streams, but its certificate never authorizes a later snapshot. See [Certified publication](/docs/etcd/design/certified-publication/) for the design rationale.

The internal SQL envelope records `certification = "performed"` and `publication = "requires_commit"`. These fields describe SQL work already performed inside the transaction; they do not report a completed `COMMIT`.

## Errors and unknown outcomes {#unknown}

A static syntax, size, or unsupported-method rejection can return before observing storage state. A state-dependent error requires the same publication barrier and synchronous `COMMIT` checks as a successful read. An internal SQL error aborts the transaction.

The Publisher buffers DataRow output and retains its database connection and admission slot until `COMMIT` has a known outcome. A client disconnect does not cancel `COMMIT`. A failed or unknown `COMMIT` suppresses the gRPC response. Any PostgreSQL warning during `COMMIT`—including a canceled synchronous-replication warning—also suppresses publication.

Never automatically replay an unknown `COMMIT`. A missing success response does not prove that the transaction rolled back. Applications that retry after a transport failure or timeout must resolve ambiguity through their own idempotency keys or `Txn` comparisons.

Graceful shutdown closes new request admission first. Active operations retain ownership of their connections until they finish. If the shutdown drain timer expires while a `COMMIT` is still in flight, the outcome remains unknown and the connection is never returned to a reusable pool.

## Current constraints {#constraints}

The extension rejects protocol calls inside subtransactions (`SAVEPOINT`), multiple logical calls within one top-level SQL transaction, and two-phase commit (`PREPARE TRANSACTION`). It rechecks `synchronous_commit = on` before returning.

Multi-request batching, in-transaction Lease overlays, and mixed public SQL calls in one transaction are outside the MVP scope. End-to-end publication across failovers also requires primary fencing and route retirement; see the post-MVP [HA roadmap](/docs/etcd/design/ha-roadmap/).

Source: `extension/pg_etcd.c`, `internal/pgstore/publisher.go`, and `internal/pgflight/legacy_commit.go`.

---

Backlinks:

- [Architecture](/docs/etcd/architecture/)
- [Schema](/docs/etcd/architecture/schema/)
- [Certified publication](/docs/etcd/design/certified-publication/)
- [PostgreSQL as the authority](/docs/etcd/design/postgresql-authority/)
- [SQL ABI](/docs/etcd/reference/sql/)
