Skip to content

This is the multi-page printable view of this section.

Return to the regular view of this page

Architecture

Components, request paths, tenants and persistent state in pgetcd.

pgetcd implements an etcd v3 service API protocol gateway over PostgreSQL. The Go process handles gRPC and tenant connections. The pg_etcd C extension owns storage semantics, and PostgreSQL stores all durable state.

Each gateway process serves one configured tenant on a fixed PostgreSQL primary. Multi-node high availability and automatic primary promotion are part of the post-MVP HA roadmap. See Status for current validation boundaries.

Components

ComponentResponsibility
Go gatewayDecode protobuf requests, check input limits, authenticate clients and translate SQL envelopes
Publisher (gateway component)Own SQL transactions and retain responses until synchronous COMMIT succeeds
Tenant Watch serviceRead committed event batches, track each Watch and enforce queue limits
pg_etcdEvaluate Txn, allocate revisions, store events, manage Lease state and compact history
pg_kvcoreInternal C helpers linked into pg_etcd; not a separate extension
PostgreSQLStore logged tables, serialize requests, maintain snapshots and commit WAL
Lease launcher and workersSupervise one background worker per allowed database and rebuild Lease deadlines

The C extension has no network listener or embedded Go runtime. The Go gateway has no independent revision allocator or Lease expiry clock.

Request path

etcd client
    │ gRPC with tenant mTLS
    ▼
Go gateway → Publisher → PostgreSQL transaction
                              │
                              ▼
                          pg_etcd
                    lock meta → fresh snapshot
                    validate → evaluate → certify
                              │
                              ▼
                       synchronous COMMIT
                              │
                              ▼
                     buffered gRPC response

Each logical request uses one READ COMMITTED transaction with synchronous_commit = on. The extension locks the tenant’s metadata row and takes a fresh snapshot after the lock wait finishes. Any response that observes state requires a logged change after that observation and a normal synchronous COMMIT before publication. Transactions and revisions explains this order.

Watch uses the same publication boundary. A per-tenant tailer reads complete committed revisions; PostgreSQL notifications wake the tailer, and periodic polling recovers missed notifications. Lease expiry also changes state through PostgreSQL transactions. See Watch, Lease and history.

Tenant boundary

A tenant has a fixed endpoint, database, SQL role and certificate policy. One gateway process serves one tenant. Two gateway processes can serve the same database with separate connection pools. Multiple tenants use separate process configurations and database bindings.

A client request cannot select a database. Key prefixes are an application convention, not an isolation boundary. Read Security before assigning credentials.

Persistent state

The seven core tables in the etcd schema are ordinary logged PostgreSQL tables. They hold current values, complete events, revision manifests, history anchors, Lease facts, logical identity and publication barriers. See Schema for table definitions and invariants.

PostgreSQL sequences do not allocate protocol revisions. A rolled-back request consumes no revision, and all actual KV changes in one request share a single revision.

Source map

Paths below are relative to the pgetcd repository:

PathMain content
cmd/pgetcd/main.goProcess modes, tenant startup, listeners and shutdown
internal/gateway/gRPC service adapters
internal/pgstore/, internal/pgflight/Publication and SQL transaction ownership
internal/watch/, internal/tenantservice/Watch delivery and tenant readiness
extension/pg_etcd.cSQL entry points and request execution
extension/pg_etcd--0.1.0.sqlSchema, SQL functions and privileges
extension/pg_kvcore/Revision budgets and Lease runtime

Architecture topics

  • Transactions and revisions — Post-lock snapshots, revision allocation, read barriers, and synchronous COMMIT publication.
  • Watch, Lease and history — Complete revision delivery, Lease facts and worker recovery, and baseline compaction.
  • Schema — The seven logged tables in the etcd schema, invariants, and the internal SQL ABI.
  • Security — Tenant mTLS, certificate URI SAN matching, database role boundaries, and admission limits.

1 - Transactions and revisions

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

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

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.

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

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

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

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 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

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

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.

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

2 - Watch, Lease and history

Event history, Watch delivery, lease expiry and logical compaction.

Watch, Lease and history share pgetcd’s transaction and revision model. The event log in etcd.events is durable. Watch cursors and Lease deadlines are runtime state derived from committed PostgreSQL facts.

Complete revisions

Each tenant gateway runs one Watch service with one concurrent tail operation. Tail v2 (etcd._tail_v2), the internal event-reading interface, reads metadata, events and the revision manifest from a single snapshot. It checks the event count and encoded-size budgets, then certifies the scanned high-watermark before delivering events.

The internal cursor is (revision, sub), where sub is the zero-based event sequence number within a revision. Delivery advances only across complete revisions. Client revisions can have gaps because a Watch can select a key range or filter event types.

In the rules below, R is the current revision and C is the logical compact revision:

RequestResult
start_revision = 0Start at R + 1, using the certified creation snapshot
Explicit start_revision > CInclude matching events at that revision and later revisions
0 < start_revision <= CCreate the watch, then immediately emit a canceled WatchResponse with compact_revision = C
start_revision > RWait for future commits; do not claim catch-up until R reaches that revision

A Created response confirms registration; it does not confirm that historical events have already been delivered. If a large revision is split across multiple WatchResponse fragments, only the final fragment completes that revision.

Progress and backpressure

WatchProgressRequest obtains a new certified revision R. The stream first delivers all matching events through R. It broadcasts a progress response with watch_id = -1 only when all active watches on the stream are caught up and their start_revision values permit that watermark. A future or lagging Watch on the same stream blocks the broadcast.

Automatic per-Watch progress (progress_notify = true) uses its configured interval (watch.progress_interval_ms). Progress always reflects a certified scan, even when filtering produces no events.

PostgreSQL LISTEN / NOTIFY messages are wake hints only; they carry no authority to advance a cursor. Periodic polling (watch.poll_interval_ms) recovers missed notifications. The implementation never substitutes a notification counter for the durable event log.

Per-watcher queues enforce message, byte and lag limits (watch.queue_capacity). A slow consumer receives an explicit ResourceExhausted termination; the service never silently drops events or mislabels queue pressure as compaction.

To reconnect after a stream break, resume from last_complete_revision + 1 or from a valid progress watermark header.revision + 1. Do not use a Created header or an unrelated Range header as evidence that earlier Watch events were delivered. Performing a full Range relist followed by Watch(start_revision = range_header.revision + 1) is also a valid recovery procedure.

Lease facts and deadlines

The logged etcd.leases row stores the Lease ID, a fresh 128-bit grant generation (grant_hi, grant_lo), the granted TTL, and the committed renewal sequence (renew_seq). Shared-memory runtime state stores the background worker generation, the last observed committed renew_seq, and a monotonic clock deadline. The 128-bit grant generation prevents a stale expiry task from revoking a newly granted Lease that reuses the same 64-bit Lease ID.

Any call that references a Lease locks etcd.meta and then locks the etcd.leases row. Before deciding whether the Lease has expired, it refreshes shared-memory runtime state from any newer committed renew_seq. The extension never holds a shared-memory spinlock or LWLock while waiting for a PostgreSQL row lock.

A successful LeaseKeepAlive renewal requires its own synchronous COMMIT. A rolled-back transaction never extends the runtime deadline. When a background worker observes a new committed renew_seq, it conservatively grants a full TTL starting from that observation timestamp.

Expiry re-verifies the Lease ID, grant generation, renew_seq and worker generation inside a transaction. It then revokes the Lease and deletes all attached keys atomically. If one or more attached keys are deleted, they share a single new revision R + 1; if no keys were attached, R does not advance.

The attachment ledger on etcd.leases bounds the eventual revoke cost before keys are attached (max_keys_per_lease = 4096, max_lease_revoke_bytes = 8388608). See Compatibility.

Worker recovery

When pg_etcd is loaded via shared_preload_libraries, its launcher supervises one connected background worker per database listed in pg_etcd.lease_databases (up to eight databases). A connected worker is bound to its target database and cannot switch databases at runtime.

On PostgreSQL restart or worker restart, tenant readiness closes while a new worker generation reconstructs runtime Lease state from etcd.leases and grants each surviving Lease a full granted_ttl_sec from the reconstruction timestamp. Tenant readiness reopens only after reconstruction succeeds. Missing worker slots, a missing extension, or an ABI mismatch keeps /readyz unready (503).

This conservative policy prevents premature Lease deletion across restarts at the cost of delayed expiry. A single restart can add up to one full granted_ttl_sec plus recovery time; repeated faults have no fixed upper bound on latest expiry. This differs from upstream etcd’s remaining-TTL checkpoint behavior.

Compaction and history

In etcd.meta, C is the logical compact revision and F is the physical history floor. Fresh state uses R = 1, C = -1, F = 0. After the first compaction, 0 <= F <= C <= R.

Compact advances C without consuming a KV revision. The synchronous implementation constructs a complete new anchor generation in etcd.history_anchor, publishes that generation, and sets F = C in the same transaction. It then deletes rows in etcd.events and etcd.revision_manifest strictly below F, along with older anchor generations.

The anchor stores a complete baseline of live keys at revision F. Historical Range at revision rev (C <= rev <= R) combines the baseline at F with events in (F, rev]. Events at revision F itself remain in etcd.events for Watch delivery, including deletion tombstones, so a tombstone at the boundary still hides an older value.

If anchor construction fails or rolls back, F and C remain unchanged. While Compact accepts the physical boolean field in protobuf requests, Compact(physical = true) is not claimed as a physical OS disk-space reclamation API; internal table cleanup runs transactionally inside PostgreSQL. See Schema and Compatibility.

Source: internal/watch/, extension/pg_etcd.c, extension/pg_kvcore/lease_worker.c, and extension/pg_kvcore/lease_runtime.c.

3 - Schema

The seven tables of the etcd schema and what each one holds.

pg_etcd installs the etcd schema in each tenant database. All seven persistent tables are regular WAL-logged PostgreSQL tables. The extension’s SQL installation file defines schema version 2, while the JSONB request envelope uses internal SQL ABI version 1.

Tables

TableContents and invariant
etcd.metaSingle serialization row (singleton = true). Stores current revision R, compact revision C, history floor F, active anchor_generation, cluster_id, member_id, and schema_version
etcd.kvLive binary key/value pairs (key, value, create_revision, mod_revision, version, lease_id)
etcd.eventsChange log ordered by (revision, sub). Stores event type (PUT or DELETE), current tuple fields, and complete previous tuple (prev_*)
etcd.revision_manifestPer-revision summary (revision, event_count, tail_bytes, watch_bytes) for one complete revision
etcd.history_anchorComplete live-key baseline at floor revision F, partitioned logically by generation
etcd.leasesDurable Lease facts (lease_id, 128-bit grant generation grant_hi/grant_lo, granted_ttl_sec, renew_seq, attached_keys, revoke_bytes)
etcd.publication_barrierSingle-row logged counter (singleton = true, seq) updated after state observations that require certification

Keys and values use bytea. Revision and Lease ID fields use bigint. Cluster and member IDs use 8-byte bytea values (cluster_id, member_id) so the full unsigned 64-bit etcd identity is preserved without signed-integer overflow.

The etcd.kv primary key uses PostgreSQL binary bytea ordering. Keys contain 1 to 2,048 bytes. A partial index on nonzero lease_id values (etcd_kv_lease_idx) supports Lease attachment lookups and revocation. The index etcd_events_key_rev_sub_idx on (key, revision DESC, sub DESC) supports historical Range reconstruction.

Revision and event invariants

Fresh metadata in etcd.meta starts at R = 1, C = -1, F = 0, and anchor_generation = 0. The metadata row serializes revision allocation; no PostgreSQL SEQUENCE or BIGSERIAL is used.

A mutation commits live state in etcd.kv, complete events in etcd.events, and its summary row in etcd.revision_manifest in the same transaction. The manifest row must match the exact event count and conservative Tail/Watch encoded byte budgets (<= 8 MiB). etcd._tail_v2 recomputes these values when reading a revision and rejects any mismatch.

A DELETE event in etcd.events records a tombstone (is_delete = true) at its deletion revision together with a complete previous tuple (prev_present = true, prev_create_revision, prev_mod_revision, prev_version, prev_lease_id, prev_value). Its new create_revision, version, and lease_id fields are 0. This allows historical Range reconstruction to hide an older baseline value while Watch still delivers the deletion event and optional prev_kv.

Triggers on etcd.kv (etcd_kv_lease_ledger_trg) and etcd.leases maintain exact attached_keys counts and revoke_bytes budgets for every writer. Protocol paths check these bounds before mutating rows, and table CHECK constraints provide a final guard if an invariant is violated.

SQL interface

The Go gateway calls the extension through a narrow internal SQL ABI:

Entry pointUse
etcd._abi()Return extension version, schema version (2), supported SQL ABI (1), Tail ABI (2), Lease worker status, and compiled limits
etcd._execute(req jsonb)Execute one KV, Lease, or diagnostic request envelope
etcd._tail_v2(after_rev bigint, max_events integer)Read the next complete revision batch under Tail ABI 2
etcd._publication_barrier()Advance etcd.publication_barrier.seq to certify controlled observations
etcd.get, etcd.put, etcd.delete_range, etcd.txn, etcd.compactSQL convenience wrappers over the same C request engine

Legacy etcd._tail and experimental etcd._lease_probe remain in the extension SQL file for frozen test inputs; they are not used by the active Watch and Lease RPC paths.

An etcd._execute request envelope has this shape:

{"abi":"1","method":"kv.put","request":{"key":"YQ==","value":"Yg==","lease":"0"}}

64-bit integers cross the JSONB envelope as canonical base-10 strings. Binary bytea fields use canonical RFC 4648 padded base64. Booleans retain JSON boolean types, and unknown JSON fields fail with an explicit error. This envelope is an internal gateway-to-extension ABI, not a public HTTP/JSON etcd endpoint. See SQL interface reference for full function signatures.

Receiving a row from etcd._execute does not complete publication; the caller must still complete a synchronous COMMIT without warnings. See Transactions and revisions.

Privileges and direct SQL

Installing the extension requires an existing pgetcd_owner role configured with NOLOGIN, NOSUPERUSER, NOCREATEDB, NOCREATEROLE, and NOREPLICATION. The extension script assigns ownership of all etcd tables and functions to pgetcd_owner and revokes PUBLIC access.

Protocol entry points run as SECURITY DEFINER with SET search_path = pg_catalog and schema-qualified table references. The gateway runtime role needs only USAGE on schema etcd and EXECUTE on the approved entry functions (_abi, _execute, _tail_v2, _publication_barrier). It must not own the extension, inherit pgetcd_owner, or have direct SELECT or DML privileges on the underlying tables.

Direct DML against etcd.* tables can bypass protocol preflight checks, revision ordering, and event manifest construction. Treat the seven tables as internal extension state. The SQL convenience wrappers (etcd.get, etcd.put, etc.) are development helpers subject to the same one-call-per-transaction rules, not a bulk data-import API.

Source: extension/pg_etcd--0.1.0.sql, extension/pg_etcd.c, and extension/pg_kvcore/revision_budget.c.

4 - Security

Tenant mTLS, certificate identities, database roles and grants.

A pgetcd gateway process authenticates one tenant principal over mTLS and connects to that tenant’s fixed PostgreSQL database using a restricted SQL role. It does not implement the etcd Auth service, RBAC roles, or per-key authorization.

Client to gateway

The gRPC listener requires TLS 1.2 or later and a verified client certificate (RequireAndVerifyClientCert). After X.509 chain verification against tls.client_ca_file, the gateway requires an exact URI Subject Alternative Name (SAN) match with the tenant’s configured tls.client_uri.

The standard URI format is spiffe://pgetcd/tenant/<tenant_id>. Trust in the same CA is not sufficient on its own: a valid certificate carrying another tenant’s URI SAN is rejected during the TLS handshake. If tls.server_name is configured, clients must also present that exact SNI hostname; connecting to an IP literal requires a matching IP SAN on the server certificate.

The operational HTTP listener (listen_http) enforces the exact same tenant mTLS policy. Its /livez, /readyz, /health, /metrics, and /version routes are not anonymous probes. Diagnostics use a separate HTTP/1.1 listener, while etcd application RPCs use gRPC over HTTP/2 on listen_grpc.

The internal -p0-fixture flag binds only to an explicit loopback IP (127.0.0.1 or ::1) using plaintext. It exists solely for local feasibility harnesses and does not provide tenant mTLS or the production Watch service.

Gateway to PostgreSQL

The tenant configuration file fixes db_name and role, and PGETCD_DSN must resolve to that exact pair. Client requests, gRPC metadata, and key prefixes cannot select a different database or role.

In production tenant mode, every PostgreSQL connection alternative in PGETCD_DSN must use sslmode=verify-full with certificate and hostname verification. Plaintext or unverified TLS fallbacks (disable, allow, prefer, require, verify-ca) are rejected unless -allow-insecure-pg-tls is explicitly passed for local development. The DSN is read from the environment and is never echoed in public diagnostics or error messages.

Gateway configuration checks do not grant or prove PostgreSQL privileges. Operators must provision two separate non-superuser roles in PostgreSQL:

  • pgetcd_owner (NOLOGIN): Owns the etcd schema, its seven tables, and its SECURITY DEFINER functions, without superuser, replication, or login privileges.
  • Gateway runtime role (LOGIN): Granted CONNECT on the tenant database, USAGE on schema etcd, and EXECUTE on etcd._abi(), etcd._execute(jsonb), etcd._tail_v2(bigint, integer), and etcd._publication_barrier(). It must not own the extension, inherit pgetcd_owner, or hold direct table privileges.

The extension installation script revokes PUBLIC access. Granting ALL on schema etcd or adding the gateway role to pgetcd_owner defeats this privilege boundary.

Resource admission

The gateway bounds concurrent TCP connections, gRPC message sizes (2 MiB input, 8 MiB output), publication flight slots (max_inflight = 64), Watch queues (queue_capacity = 128), and per-stream watcher counts (max_streams_per_conn = 256). Inside PostgreSQL, pg_etcd checks response and complete-revision byte budgets before committing mutations.

These limits operate at the request and stream layers; a response-size cap does not bound total PostgreSQL query memory, temporary disk spill, WAL growth, or overall OS memory. Attempts to bound cold-start Go runtime and Linux kernel memory accounting in the experimental native P3 line are documented in Frozen native line.

Graceful shutdown preserves resource ownership for in-flight work. A client cancellation or timeout never releases a PostgreSQL connection whose COMMIT is still in flight, and a Watch sender’s memory credit remains occupied until that sender goroutine exits.

Authority and isolation

Mutual TLS authenticates the peer identity, but it does not prove that the target PostgreSQL instance is the sole active primary. A SQL pg_is_in_recovery() check, a reachable TCP address, or a cached authority record cannot replace primary fencing during a network partition.

For multi-node deployments, primary authority verification, stale-route retirement, and split-brain fencing are tracked in the post-MVP HA roadmap.

Validation boundary

On v0.1.0-rc2 (commit 81691bc, Linux amd64, PostgreSQL 18.6, 2026-11-08), the internal/transport mTLS tests, including rejection of another tenant’s trust and SNI, passed, and the etcdctl probes confirmed that a valid certificate for another tenant is refused. The frozen P1 single-primary candidate (e37e197, 2026-10-08) verified tenant mTLS enforcement, cross-tenant URI SAN rejection, SNI checks and restricted database role boundaries in its integration suites.

Source: internal/transport/mtls.go, internal/tenant/config.go, internal/pgstore/tenant.go, cmd/pgetcd/main.go, and extension/pg_etcd--0.1.0.sql.