Skip to content

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

Return to the regular view of this page

etcd

etcd v3 gRPC through the pgetcd gateway, with revisions and leases in tables.

etcd v3 clients such as etcdctl and clientv3 connect to the pgetcd gateway over gRPC with mutual TLS. The gateway evaluates each request in the pg_etcd extension. Keys, revisions, the event history and leases live in PostgreSQL tables, and a response is sent only after a synchronous commit.

Status
Release candidate. v0.1.0-rc2 (commit 81691bc) is a local tag; the repository has no remote and nothing is published. Production high availability is post-MVP work.
Ports
gRPC with mTLS on 2379 (listen); diagnostics HTTPS on 2381 in examples (diagnostics_listen). Both settings are required.
Gateway
pgetcd, Go, etcd API 3.7.2, static binary; one process per tenant
Extension
pg_etcd, C; schema etcd with 7 tables; one Lease worker per database, at most 8
Kernel patch
none; runs on stock PostgreSQL 18
Licence
Apache-2.0; the etcd API and client are used as dependencies

How etcd maps onto PostgreSQL

  • Each request is one READ COMMITTED transaction. It locks the single etcd.meta row, takes a fresh snapshot and evaluates.
  • Revisions are a counter in the meta row, not a sequence. All changes in one request share one revision; a rollback uses none.
  • Reads also write a logged publication barrier, so a read response, like a write, leaves only after a synchronous commit. An unknown commit outcome is never replayed.
  • Watch streams complete revisions from the events table. NOTIFY is only a wake-up hint; polling recovers missed notifications.
  • Leases are rows. After a restart every lease gets a full TTL again: a fault can delay expiry, never cause an early one.
  • Compact is logical. MemberList and Status report one logical member.

Supported API

Range, Put, DeleteRange, Txn, Compact (logical), LeaseGrant, LeaseRevoke, LeaseTimeToLive, LeaseLeases, LeaseKeepAlive, Watch, MemberList and Status.

Not implemented: Auth, User and Role RPCs, member changes, other Maintenance RPCs, Lock and Election, and the HTTP/JSON gateway. Without the HTTP/JSON gateway, Patroni cannot use pgetcd as its DCS yet.

Source and credit

pgetcd is developed by PGSTY and pgetcd contributors. etcd is a project of the Cloud Native Computing Foundation; Mimus is not affiliated with the etcd project.

Pages in this section adapt the pgetcd companion documentation, © PGSTY and pgetcd contributors, CC BY 4.0; see Licence and attribution.

1 - Quick start

Build the gateway and extension, create a tenant, start pgetcd and check readiness.

This procedure builds pgetcd and pg_etcd from source and starts one tenant on an isolated PostgreSQL 18 primary with mutual TLS. For the supported RPCs and operating limits, see Compatibility.

Prerequisites

Prepare the pgetcd source checkout, Go 1.27.3, a C compiler, and PostgreSQL 18.6 with its server headers and PGXS files (pg_config). You also need psql, curl, and permission to install extensions into the PostgreSQL instance.

Configure PostgreSQL TLS and authentication before starting:

  • The PostgreSQL server certificate must match the host or IP address in PGETCD_DSN, and the gateway must trust its root CA.
  • pg_hba.conf must allow the role pgetcd_demo_gateway to authenticate over TLS.
  • Obtain the following mTLS certificates for the gateway and client (SAN is the certificate Subject Alternative Name):
FileRequirementUsed by
server.crt, server.keyGateway server certificate and private key; SAN includes the endpoint IP or DNS nameTenant JSON: tls.certificate, tls.private_key
client-ca.crtCA that issued the tenant client certificateTenant JSON: tls.client_ca
tenant-client.crt, tenant-client.keyClient certificate and private key; URI SAN is spiffe://pgetcd/tenant/democurl and etcd clients
server-ca.crtCA that issued the gateway server certificatecurl --cacert and client CA flags

Keep private keys and generated credentials outside version control.

Build the gateway and extension

Run these commands from the pgetcd checkout with PG_CONFIG pointing to your PostgreSQL 18 installation:

export PG_CONFIG=/path/to/postgresql/bin/pg_config
"$PG_CONFIG" --version
go version
mkdir -p .cache/docs-dev
go build -o .cache/docs-dev/pgetcd ./cmd/pgetcd
make -C extension PG_CONFIG="$PG_CONFIG"
make -C extension PG_CONFIG="$PG_CONFIG" install
.cache/docs-dev/pgetcd --version

The gateway binary is written to .cache/docs-dev/pgetcd. The extension installs pg_etcd.so, pg_etcd.control, and pg_etcd--0.1.0.sql into the directories selected by PG_CONFIG.

Configure PostgreSQL

Add pg_etcd to shared_preload_libraries in postgresql.conf and register the tenant database:

shared_preload_libraries = 'pg_etcd'
pg_etcd.databases = 'pgetcd_demo'
synchronous_commit = on

Keep fsync and full_page_writes enabled. Restart PostgreSQL so the pg_etcd preload launcher starts.

Create the tenant database

Connect to PostgreSQL as an administrator, create the owner and gateway roles, install the extension, and grant access only to the four public SQL ABI functions:

CREATE ROLE pgetcd_owner NOLOGIN NOSUPERUSER;
CREATE ROLE pgetcd_demo_gateway LOGIN NOSUPERUSER
  NOCREATEDB NOCREATEROLE NOREPLICATION;
CREATE DATABASE pgetcd_demo;
\connect pgetcd_demo
CREATE EXTENSION pg_etcd;
REVOKE ALL ON DATABASE pgetcd_demo FROM PUBLIC;
GRANT CONNECT ON DATABASE pgetcd_demo
  TO pgetcd_owner, pgetcd_demo_gateway;
GRANT USAGE ON SCHEMA etcd TO pgetcd_demo_gateway;
GRANT EXECUTE ON FUNCTION
  etcd._abi(), etcd._execute(jsonb),
  etcd._tail_v2(bigint, integer), etcd._publication_barrier()
  TO pgetcd_demo_gateway;

Configure authentication for pgetcd_demo_gateway according to your instance policy (for example, client certificate authentication or \password pgetcd_demo_gateway in psql).

In the same session, read the database identity and readiness status:

BEGIN ISOLATION LEVEL READ COMMITTED;
SET LOCAL synchronous_commit = on;
SELECT etcd._execute(
  '{"abi":"1","method":"diag.status","request":{}}'::jsonb
);
COMMIT;

Verify the result in three steps:

  1. Confirm that COMMIT completed without an error or a synchronous-replication cancellation warning.
  2. Confirm that response.ready, response.primary, and response.lease_ready are all true.
  3. Record header.cluster_id and header.member_id as decimal strings for the tenant configuration file.

If response.ready is false, inspect response.not_ready_reasons. If the Lease worker is still rebuilding, wait briefly and repeat the transaction. For other causes, see Troubleshooting.

Start the gateway

Create .cache/docs-dev/tenant.json from the tenant configuration example. Replace the placeholder "1" values for cluster_id and member_id with the decimal strings returned by diag.status, set database to pgetcd_demo and role to pgetcd_demo_gateway, and fill in your certificate paths.

Start pgetcd with PGETCD_DSN set to a verify-full TLS connection string:

export PGETCD_DSN='host=127.0.0.1 port=5432 dbname=pgetcd_demo user=pgetcd_demo_gateway sslmode=verify-full sslrootcert=/path/to/postgres-ca.crt'
.cache/docs-dev/pgetcd --tenant-config .cache/docs-dev/tenant.json

Append sslcert and sslkey to PGETCD_DSN if PostgreSQL requires SQL client certificates. Before opening its listeners, the gateway verifies the SQL ABI, persistent cluster and member identity, and Lease worker readiness.

In a second terminal, query the diagnostics readiness endpoint using the tenant client certificate:

curl --cacert /path/to/server-ca.crt \
  --cert /path/to/tenant-client.crt \
  --key /path/to/tenant-client.key \
  https://127.0.0.1:2381/readyz

A ready gateway returns {"health":true}. Continue with the etcdctl and Go clientv3 tutorials.

Note

This procedure was run end to end during the v0.1.0-rc1 regression (commit 7e43446) and again for v0.1.0-rc2 (commit 81691bc) on Linux amd64 with PostgreSQL 18.6, using certificate authentication and a synchronous standby.

2 - Tutorials

Use pgetcd from etcdctl and from a Go client.

These tutorials run against a development tenant and write keys under the /tutorial/ prefix. Reserve /tutorial/ for these exercises.

  1. Complete Quick start first if you do not have a running tenant, and keep the endpoint address and tenant client certificates ready.
  2. Follow Use etcdctl to read and write keys, watch prefix changes from a snapshot revision, and attach or revoke a Lease.
  3. Follow Use the Go client to execute a conditional Txn and watch a key from a known revision with clientv3.

For the full list of supported RPCs and limits, see Compatibility.

2.1 - Use etcdctl

Put, get, watch and lease keys with etcdctl over mutual TLS.

This exercise writes a key, watches changes from a snapshot revision, and deletes a key by revoking its Lease. It requires a running development tenant (Quick start), etcdctl 3.6.15 (or 3.7.2), and jq. Keep the /tutorial/ prefix free for this walkthrough.

Configure the client

Export the etcd v3 environment variables in each terminal, replacing the endpoint and certificate paths with those for your tenant:

export ETCDCTL_API=3
export ETCDCTL_ENDPOINTS=https://pgetcd.example.test:2379
export ETCDCTL_CACERT=/path/to/server-ca.crt
export ETCDCTL_CERT=/path/to/tenant-client.crt
export ETCDCTL_KEY=/path/to/tenant-client.key
export ETCDCTL_DIAL_TIMEOUT=5s
export ETCDCTL_COMMAND_TIMEOUT=10s

etcdctl version
etcdctl endpoint status --write-out=table

The endpoint hostname or IP must match the gateway server certificate (server.crt), and the client certificate (tenant-client.crt) must carry the tenant’s URI SAN (spiffe://pgetcd/tenant/demo). ETCDCTL_CACERT points to the CA that signed the gateway server certificate.

etcdctl endpoint status prints the tenant’s logical member ID, current revision, advertised version (3.6.0), and PostgreSQL relation size. etcdctl endpoint health reports healthy from v0.1.0-rc2; on v0.1.0-rc1 it fails because Maintenance.Alarm was unimplemented. If endpoint status fails, see Troubleshooting.

Read and write keys

Write and read back a key under /tutorial/:

etcdctl put /tutorial/hello world
etcdctl get /tutorial/hello
etcdctl get /tutorial/ --prefix --write-out=json

The first command prints OK. The second prints the key and world. The JSON output shows header.revision along with the key’s create_revision, mod_revision, and version (keys and values in JSON output are base64-encoded).

Write the same value a second time:

etcdctl put /tutorial/hello world
etcdctl get /tutorial/hello --write-out=json

Both version and mod_revision advance even when the value does not change. Do not hard-code revision numbers in scripts; concurrent writes or Lease expirations in the same tenant also advance the revision counter.

Read a snapshot, then watch

In the first terminal, read a prefix snapshot and start a Watch at header.revision + 1:

TUTORIAL_SNAPSHOT=$(etcdctl get /tutorial/ --prefix --write-out=json)
printf '%s\n' "$TUTORIAL_SNAPSHOT" | jq .
TUTORIAL_START=$(printf '%s\n' "$TUTORIAL_SNAPSHOT" | jq '.header.revision + 1')
etcdctl --command-timeout=0s watch /tutorial/ --prefix --prev-kv --rev="$TUTORIAL_START"

In a second terminal with the same ETCDCTL_* variables, update and delete the key:

etcdctl put /tutorial/hello updated
etcdctl del /tutorial/hello

The first terminal prints PUT and DELETE events with their previous key-value pairs (--prev-kv). Passing --rev="$TUTORIAL_START" ensures that any write committed between the get snapshot and the watch registration is still delivered, provided that revision has not been logically compacted.

Press Ctrl-C to stop the Watch. If the requested start revision has been compacted, take a fresh get snapshot and start a new Watch. For Watch stream and buffer limits, see Troubleshooting — Capacity.

Note

jq uses IEEE 754 double-precision numbers. For production applications where revisions can exceed $2^{53} - 1$, compute revision + 1 in a client that preserves 64-bit integers, such as the Go client example.

Attach and revoke a Lease

Grant a 30-second Lease:

etcdctl lease grant 30

Copy the hexadecimal Lease ID from the output and attach /tutorial/leased to it:

TUTORIAL_LEASE=0123456789abcdef
etcdctl put /tutorial/leased temporary --lease="$TUTORIAL_LEASE"
etcdctl lease timetolive "$TUTORIAL_LEASE" --keys
etcdctl lease revoke "$TUTORIAL_LEASE"
etcdctl get /tutorial/leased

Revoking the Lease atomically deletes /tutorial/leased in the same PostgreSQL transaction, so the final get returns no rows.

To keep a Lease alive continuously, grant a new Lease and run etcdctl --command-timeout=0s lease keep-alive <lease-id>. For Lease recovery behavior after a PostgreSQL restart, see Watch, Lease and history.

Clean up

Delete any remaining keys under /tutorial/:

etcdctl del /tutorial/ --prefix

Next, see Use the Go client for conditional transactions.

2.2 - Use the Go client

Connect clientv3 with tenant certificates and run transactions and watches.

This example uses the official go.etcd.io/etcd/client/v3 package (v3.7.2 in the pgetcd go.mod) to connect to a running development tenant over mutual TLS, execute a conditional Txn on /tutorial/go-client, and watch the next write starting from Header.Revision + 1.

Export the ETCDCTL_* environment variables from Use etcdctl before running the program.

Write the program

Create .cache/tutorial-client/main.go inside the pgetcd checkout (.cache/ is ignored by Git):

package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"errors"
	"fmt"
	"os"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
)

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func run() error {
	if len(os.Args) != 5 {
		return errors.New("usage: client <endpoint> <server-ca> <client-cert> <client-key>")
	}
	ca, err := os.ReadFile(os.Args[2])
	if err != nil {
		return err
	}
	roots := x509.NewCertPool()
	if !roots.AppendCertsFromPEM(ca) {
		return errors.New("invalid server CA")
	}
	cert, err := tls.LoadX509KeyPair(os.Args[3], os.Args[4])
	if err != nil {
		return err
	}
	client, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{os.Args[1]},
		DialTimeout: 5 * time.Second,
		TLS: &tls.Config{
			MinVersion:   tls.VersionTLS12,
			RootCAs:      roots,
			Certificates: []tls.Certificate{cert},
		},
	})
	if err != nil {
		return err
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()
	const key = "/tutorial/go-client"
	initial, err := client.Txn(ctx).
		If(clientv3.Compare(clientv3.Version(key), "=", 0)).
		Then(clientv3.OpPut(key, "hello")).
		Else(clientv3.OpGet(key)).
		Commit()
	if err != nil {
		return fmt.Errorf("initial transaction: %w", err)
	}
	fmt.Printf("created=%t revision=%d\n", initial.Succeeded, initial.Header.Revision)

	changes := client.Watch(ctx, key, clientv3.WithRev(initial.Header.Revision+1))
	written, err := client.Put(ctx, key, "updated")
	if err != nil {
		return fmt.Errorf("put: %w", err)
	}
	for response := range changes {
		if err := response.Err(); err != nil {
			return fmt.Errorf("watch: %w", err)
		}
		for _, event := range response.Events {
			if event.Kv.ModRevision == written.Header.Revision {
				fmt.Printf("%s %s=%s revision=%d\n",
					event.Type, event.Kv.Key, event.Kv.Value, event.Kv.ModRevision)
				return nil
			}
		}
	}
	if err := ctx.Err(); err != nil {
		return err
	}
	return errors.New("watch closed before the write was observed")
}

Run the program

From the pgetcd repository root, run:

go run ./.cache/tutorial-client \
  "$ETCDCTL_ENDPOINTS" "$ETCDCTL_CACERT" "$ETCDCTL_CERT" "$ETCDCTL_KEY"

Pass a single endpoint URL in ETCDCTL_ENDPOINTS. The first run prints created=true followed by the PUT event for updated. Subsequent runs print created=false because Version(key) is no longer 0.

Starting the Watch at initial.Header.Revision + 1 avoids a race between Watch registration and Put: even if Put commits before the Watch stream finishes registering, pg_etcd replays retained events from initial.Header.Revision + 1 onward.

All operations share a 15-second context timeout. If a write times out or returns an unknown outcome, do not blindly replay a non-idempotent write; inspect the committed state first.

Clean up and production notes

Delete the tutorial key when done:

etcdctl del /tutorial/go-client

When writing production clientv3 consumers:

  • Persist your consumer’s resume revision only after processing all events of a complete revision.
  • If a Watch response carries CompactRevision > 0 (ErrCompacted), take a fresh Get snapshot and open a new Watch from Header.Revision + 1.
  • If stream fragmentation is enabled, wait until More == false before treating a revision as complete.

For more details on Watch tailing and Lease lifecycles, see Watch, Lease and history.

3 - Compatibility

Supported RPCs, limits, differences from etcd and the evidence behind them.

This page documents the API scope, resource bounds, deliberate behavioral differences, and verification evidence for pgetcd v0.1.0-rc2 (local tag on commit 81691bc, verified on 2026-11-08) and the earlier 2026-10-08 frozen acceptance candidate (0.1.0-p1). v0.1.0-rc1 (commit 250df4c) is superseded; its results are kept where noted.

MVP scope

pgetcd provides a subset of the etcd v3 gRPC API backed by a single PostgreSQL 18 primary.

AreaSupported in v0.1.0-rc2
DeploymentOne PostgreSQL 18 primary; one gateway process per tenant; one database and one SQL role per tenant
KVRange, Put, DeleteRange, and Txn, including historical reads, comparisons, nested branches, and prev_kv
CompactionCompact, logical compaction only
LeasesLeaseGrant, LeaseRevoke, LeaseTimeToLive, LeaseLeases, and LeaseKeepAlive
WatchMultiple watches per stream, start revisions, filters, prev_kv, progress notification, fragmentation, and reconnect
Cluster and maintenanceMemberList and Status, reporting one logical tenant member; the Alarm list query, which returns an empty list
Client authenticationMutual TLS with client certificate URI SAN spiffe://pgetcd/tenant/<tenant>
PlatformsLinux amd64 and arm64; PostgreSQL 18.6

Target use cases for the MVP:

  • Applications using the official etcd Go clientv3 or etcdctl (configuration, service discovery, and Lease-backed coordination).
  • Kubernetes kube-apiserver storage for small clusters or development and test clusters.

Not supported in v0.1.0-rc2:

  • Unimplemented RPCs (return gRPC Unimplemented): RangeStream, physical Compact (physical=true), all Auth/User/Role RPCs, cluster membership changes (MemberAdd, MemberRemove, MemberUpdate, MemberPromote), Maintenance RPCs other than Status and the Alarm list query (alarm activation and deactivation, Defragment, Hash, HashKV, Snapshot, MoveLeader), and the Lock and Election services.
  • High-availability semantics: no automatic fencing or response-consistency guarantee across a PostgreSQL primary switchover. After a primary promotion, the operator updates PGETCD_DSN and restarts the gateway.
  • HTTP/JSON gateway: only gRPC is served.
  • Replica reads, more than 8 tenant databases per PostgreSQL instance, in-place schema upgrade migration, or performance SLAs.

Why Patroni is not supported

Patroni’s etcd3 client does not speak gRPC. It talks to the etcd HTTP/JSON gateway (/version, /v3/kv/range, /v3/kv/txn, /v3/lease/grant, /v3/watch). Because pgetcd v0.1.0 serves only gRPC, Patroni cannot use it as a DCS.

An HTTP/JSON gateway and Patroni validation are planned for MVP+1. Even then, a pgetcd instance used as a Patroni DCS must run on a separate PostgreSQL cluster; hosting a Patroni cluster’s DCS inside the same PostgreSQL cluster creates a circular dependency during failover.

RPC coverage

RPC groupImplemented behaviorOperational limit
Range, Put, DeleteRange, TxnBinary keys and values, historical reads, sorting and filtering, comparisons, nested branches, read-your-own-writes inside a Txn, prev_kv, and Lease attachmentBounded request and response sizes; one tenant per request
CompactLogical compaction, history anchor advancement, and boundary retentionphysical=true returns Unimplemented
LeaseGrant, LeaseKeepAlive, LeaseTimeToLive, LeaseLeases, LeaseRevokeLogged Lease table, background worker expiration, and atomic deletion of attached keys on revoke or expiryOne public Lease RPC per PostgreSQL transaction; cannot mix Lease and KV calls in one transaction
WatchMultiple watches per stream, create and cancel, filters, prev_kv, RequestProgress, fragments, and reconnectBounded per-tenant stream and buffer quotas; a create response alone does not advance progress
MemberList, StatusOne logical tenant member, certified cluster/member identity, current revision, and PostgreSQL relation sizeNo Raft peer topology
Alarm (from v0.1.0-rc2)The list query returns an empty list under a certified header; an unready tenant returns UnavailableAlarm activation and deactivation return Unimplemented

Since v0.1.0-rc2 (commit 81691bc), Maintenance.Alarm answers list queries, so etcdctl endpoint health reports healthy: the etcdctl 3.6.15 and 3.7.2 probes recorded 50 PASS / 0 FAIL on 2026-11-08. On v0.1.0-rc1 the same probes recorded 48 PASS / 2 FAIL, both endpoint health.

Version baseline and advertised compatibility

The root source tree for v0.1.0-rc2 (commit 81691bc; no dependency change since v0.1.0-rc1) and the 2026-10-08 frozen P0/P1/P2 acceptance candidate use the following component versions (from versions.lock.json and the build metadata):

Component or identifierv0.1.0-rc2 root build2026-10-08 frozen candidate
PostgreSQL18.6 (REL_18_6)18.6 (REL_18_6)
Go toolchain1.27.31.27.1
etcd API / clientv33.7.23.6.15, 3.7.2
Reference etcd servers3.6.15, 3.7.23.6.15, 3.7.2
Kubernetes reference trees1.36.4, 1.37.11.36.4, 1.37.1
gRPC / protobuf / pgx1.84.0 / 1.36.12 / 5.11.05.11.0 (pgx)
Gateway product version0.1.00.1.0-p1
Extension / SQL ABI / schema0.1.0 / 1 / 20.1.0 / 1 / 2
Advertised Status.Version3.6.03.6.0

Why Status advertises 3.6.0:

  • When RejectOldCluster is enabled, clientv3 v3.6.15 requires at least 3.5.0 and clientv3 v3.7.2 requires at least 3.6.0 (a 3.5.12 negative control is rejected by the 3.7 client).
  • Kubernetes 1.36.4 and 1.37.1 feature_support_checker parses Status.Version to enable RequestWatchProgress, rejecting versions below 3.4.31 and [3.5.0, 3.5.13).
  • Advertising 3.6.0 satisfies both checks and selects the same client code paths as 3.6.15 without claiming that every etcd 3.6 RPC is implemented.

Resource limits

ResourceBound
gRPC receive / send message size1,572,864 bytes (1.5 MiB) / 8 MiB
SQL JSONB request envelope2 MiB
KV / Txn response tree8 MiB conservative budget (p2-kv-response-v1)
Ordinary Lease response / legacy Tail2 MiB each
Complete _tail_v2 revision8 MiB; at most 4,096 events
Write key length1–2,048 bytes
Txn nesting depth / total comparisons and operationsDepth 8 / 128 across compare, success, and failure
Active Leases per tenant database1,024
Keys attached to a single LeaseAt most 4,096, bounded by the complete-revoke byte budget
Supervised tenant databases per PostgreSQL instanceAt most 8 (pg_etcd.databases)

Admission checks reserve serialized space for both the immediate revision and any future full-Lease revocation revision. As a result, pgetcd can reject large writes or Lease attachments with ResourceExhausted even when upstream etcd would accept them. See Configuration for gateway connection and Watch buffer settings.

Deliberate differences and contract observations

  • Primary-only serialized transactions: Every request runs on the PostgreSQL primary, including Range with serializable=true. Both reads and writes lock the single etcd.meta row (FOR UPDATE), write a logged publication barrier on read-only paths, and release the gRPC response only after a warning-free synchronous COMMIT.
  • Deterministic tie-breaking on non-key Range sorts: Upstream etcd 3.6.15 and 3.7.2 use a comparator that compares only the sort target (CREATE, MOD, VERSION, VALUE) via sort.Sort, leaving equal-target ordering unspecified. pgetcd always breaks ties by ascending key byte order (key ASC) across ASCEND, DESCEND, and NONE. Across 186 tie-sort test vectors against the reference servers, 59 match byte-for-byte and 127 differ only in tie-group permutation (76) or limit boundary selection within an equal-value group (51), with 0 semantic violations. When sort_order = NONE is combined with a non-key sort_target and a positive limit, pgetcd preserves upstream’s fetch-before-sort behavior (taking the limit + 1 key-ordered prefix before sorting by the target and truncating).
  • Revision and Compact edge cases (verified against etcd 3.6.15 and 3.7.2):
    • A fresh store starts at revision R = 1; Compact(-1) returns ErrCompacted, the first Compact(0) succeeds, and the first modifying write allocates R = 2.
    • After Compact(0), a top-level Range with revision <= 0 resolves to the current revision and succeeds, whereas a Range(-1) inside a Txn fails preflight validation with ErrCompacted.
    • Inside a Txn, a Range or no-op DeleteRange executed before a Put carries the pre-write revision R in its own child response header, while the Put and top-level Txn header carry R + 1. A no-op DeleteRange by itself allocates no revision. Nested Txn response headers report revision = 0.
  • Watch boundary and progress rules:
    • At the compacted revision boundary C, Watch still delivers DELETE events, with prev_kv omitted even when prev_kv=true was requested.
    • A watcher created with start_revision = 0 at revision R can legitimately receive a RequestProgress notification at R before its first event at R + 1, whereas an explicit future start_revision > R blocks stream-level (watch_id = -1) progress until caught up or canceled.
  • Leases:
    • Lease IDs and live remaining TTLs do not match another server’s clock. Requesting TTL = 1 yields a minimum granted TTL = 2.
    • Granting a duplicate Lease ID returns FailedPrecondition. Calling LeaseTimeToLive on an unknown or expired Lease succeeds with TTL = -1. Revoking an empty Lease (no attached keys) does not increment the KV revision.
    • After a PostgreSQL or worker restart, every active Lease is rebuilt with its full granted TTL, so restarts can delay expiry but never cause early expiry.
  • MemberList and Status:
    • MemberList reports a single logical member for the tenant. Status reports that member ID as leader with raftTerm = 0.
    • dbSize and dbSizeInUse report the bytes allocated by PostgreSQL relations in the etcd schema (including table and index bloat), not bbolt file sizes.

Kubernetes storage and conformance

Kubernetes compatibility has been tested at two levels on separate builds:

  1. Upstream k8s.io/apiserver storage probe on v0.1.0-rc1 (commit 7e43446, Linux amd64, 2026-11-08):
    • Kubernetes conformance is outside the MVP verification scope (MVP goal). The probe below was not repeated on v0.1.0-rc2.
    • Instead, v0.1.0-rc1 ran the upstream k8s.io/apiserver v0.36.4 and v0.37.1 etcd3 storage probes against a live gateway: 65 PASS / 0 FAIL on each version.
    • On Kubernetes 1.37.1, where EtcdRangeStream is enabled by default in Beta, the storage client attempts RangeStream, receives Unimplemented with zero chunks, calls MarkUnsupported in feature_support_checker, and falls back cleanly to unary Range.
  2. Full storage suites and selected conformance on the 2026-10-08 frozen candidate (0.1.0-p1, extension b0e08f12, gateway 935d9fd4):
    • Across all upstream packages under k8s.io/apiserver/pkg/storage/etcd3/... and k8s.io/apiserver/pkg/storage/cacher/... (including the 10,001-object TestConsistencyCheckerDigestMatches pagination and cache catch-up test under the 8 MiB p2-kv-response-v1 budget and pool_size = 32):
      • Kubernetes 1.36.4 (commit bb826b1d, 12 packages, 243 top-level tests, 1,227 test nodes): 1,219 PASS / 0 FAIL / 8 upstream skips.
      • Kubernetes 1.37.1 (commit f78e7223, 14 packages, 233 top-level tests, 1,209 test nodes): 1,196 PASS / 9 FAIL / 4 upstream skips. All 9 failed nodes are in tests that explicitly assert declared unsupported capabilities: 6 leaf assertions requiring native RangeStream (TestGetListStreamMultiChunk, TestWatchChanSync/RangeStream, TestWatchChanSyncStreamMatchesPaginated, TestWatchChanSyncStreamMetrics), 1 test calling WithCompactPhysical() (TestWatchChanSyncStreamCompactionError), and 2 parent test nodes propagating those child failures.
    • On the same 2026-10-08 frozen candidate, the selected Kubernetes conformance suites passed 446 cases on 1.36.4 and 462 cases on 1.37.1 with zero runtime skips. Those results belong to the 2026-10-08 frozen candidate and were not re-run on v0.1.0-rc1 or v0.1.0-rc2.

Acceptance evidence

SuiteBuild and platformResult
v0.1.0-rc2 official client probesCommit 81691bc, Linux amd64, 2026-11-08etcdctl 3.6.15 and 3.7.2: 50 PASS / 0 FAIL, including endpoint health
v0.1.0-rc2 concurrency testCommit 81691bc, Linux amd64, default pool_size = 32, 2026-11-0864 and 128 clients for a few minutes each: 0 refused requests, 0 readiness withdrawals; a long-lived Watch stayed connected but lagged under sustained writes
v0.1.0-rc1 P1 mixed model auditCommit 7e43446, Linux amd64, 2026-11-08100,000 mixed KV calls, 30,011 Lease calls, 20,006 controls across 2 mTLS gateways and 5,002 windows; 0 unknown outcomes; offline replay, SQL catalog audit, and 2-stream Watch audit passed
v0.1.0-rc1 official client probesCommit 7e43446, Linux amd64, 2026-11-08etcdctl 3.6.15 and 3.7.2: 48 PASS / 2 FAIL (both endpoint health); clientv3 3.6.15 and 3.7.2 Watch suites passed
Frozen P1 1M-call mixed model audit2026-10-08 frozen candidate (0.1.0-p1)1,000,000 mixed calls across 16 hot keys, 4 workers, 2 gateways, and rotating Watch streams on one primary; passed independent model and Watch audit

Status has the v0.1.0-rc2 results, performance numbers and known issues; Releases keeps the full v0.1.0-rc1 results.

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

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

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

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

5 - Reference

Gateway configuration and the SQL ABI of pg_etcd.

Reference documentation for configuring the pgetcd gateway and the pg_etcd PostgreSQL extension:

  • Configuration — Tenant JSON schema, mutual TLS rules, connection and Watch capacity parameters, PostgreSQL preload settings, and command-line flags.
  • SQL ABI — Controlled SQL entry points (_abi, _execute, _tail_v2, _publication_barrier), JSONB request and response envelopes, transaction discipline, and role grants.

5.1 - Configuration

Tenant configuration, listeners, pools and extension settings.

Start the tenant gateway with pgetcd --tenant-config FILE and PGETCD_DSN. The gateway reads the JSON file once at startup; restart the process to apply configuration changes.

Tenant JSON file

The example below configures one tenant. Replace the persistent cluster_id and member_id placeholders with the decimal values returned by diag.status during database setup, and set your certificate paths and listener addresses:

{
  "tenant": "demo",
  "listen": "127.0.0.1:2379",
  "diagnostics_listen": "127.0.0.1:2381",
  "database": "pgetcd_demo",
  "role": "pgetcd_demo_gateway",
  "cluster_id": "1",
  "member_id": "1",
  "member_name": "demo-1",
  "public_urls": ["https://127.0.0.1:2379"],
  "tls": {
    "certificate": "/etc/pgetcd/server.crt",
    "private_key": "/etc/pgetcd/server.key",
    "client_ca": "/etc/pgetcd/client-ca.crt",
    "client_uri": "spiffe://pgetcd/tenant/demo",
    "server_name": ""
  },
  "pool_size": 32,
  "max_streams": 32,
  "max_rpc_connections": 64,
  "watch_max_tenant_bytes": 134217728,
  "watch_progress_notify_interval": "10m"
}

The tenant file must be a single JSON object of at most 65,536 bytes. Unknown fields, duplicate keys, and trailing JSON values are rejected.

FieldRule
tenant1–63 characters; starts with a lowercase ASCII letter, followed by lowercase letters, digits, or -
listen, diagnostics_listenTwo distinct explicit IP:port addresses (port 1–65535); both are required with no built-in default
database, role, member_nameRequired non-empty strings
cluster_id, member_idCanonical decimal strings for non-zero uint64 values; checked against etcd.meta at startup
public_urls1–16 distinct https:// URLs; no credentials, query string, or fragment; path empty or /
tlsServer certificate, private key, client CA, exact tenant URI SAN, and optional SNI hostname

Each gateway process binds its listener to the single configured database and role. Request keys or gRPC metadata cannot select another database. Because cluster_id and member_id identify persistent database state, never generate new random IDs on gateway restart.

TLS and database connection

  • Client to gateway: The gateway requires TLS 1.2 or newer and a client certificate signed by tls.client_ca carrying the exact URI SAN spiffe://pgetcd/tenant/<tenant>. A valid certificate for a different tenant is rejected. Both the gRPC listener (listen) and the HTTP/1.1 diagnostics listener (diagnostics_listen) enforce the same client certificate check.
  • SNI and endpoint matching: For a DNS endpoint, set tls.server_name to that exact hostname and use it in every entry of public_urls; clients must send matching SNI. For an IP endpoint, leave tls.server_name empty and use IP URLs in public_urls.
  • Gateway to PostgreSQL (PGETCD_DSN): PGETCD_DSN must connect to the exact database and role named in the tenant JSON. Every host entry in PGETCD_DSN must verify the server certificate chain and hostname (for example sslmode=verify-full sslrootcert=/path/to/ca.crt). Add sslcert and sslkey when PostgreSQL requires client certificate authentication. Any plaintext or unverified TLS fallback in PGETCD_DSN causes startup to fail closed.

Capacity and timing

FieldDefault (when omitted or 0)Allowed range
pool_size321–256 PostgreSQL connections / publication slots
max_streams321–1,024 active Watch streams
max_rpc_connections641–4,096 TCP connections, enforced before the TLS handshake
watch_max_tenant_bytes134,217,728 (128 MiB)68,681,728–1,073,741,824 bytes (with default stream limits)
watch_progress_notify_interval"10m"Duration string of at least 1ms
  • Publication slots (pool_size): Each active request holds one slot until its synchronous COMMIT resolves. Since v0.1.0-rc2, a request that finds every slot busy waits up to 5 s for one and receives ResourceExhausted only if still waiting; the readiness check uses a separate reserved slot. Set pool_size for the expected concurrency per gateway. In v0.1.0-rc1 the readiness check shared these slots and requests were refused at once.
  • Watch byte budget (watch_max_tenant_bytes): The minimum budget reserves 32 MiB for reading _tail_v2 batches, 32 MiB for per-stream buffers, and 1.5 MiB for request envelopes. It bounds serialized event data, not total Go process RSS.
  • HTTP/2 keepalive: Fixed at a 5-second minimum ping interval with pings disallowed when no stream is open.

PostgreSQL extension settings

Load pg_etcd in postgresql.conf and list the tenant databases whose Lease background workers should be supervised:

shared_preload_libraries = 'pg_etcd'
pg_etcd.databases = 'pgetcd_demo'
synchronous_commit = on
GUC or settingRule
shared_preload_librariesMust include pg_etcd so the Lease worker launcher starts with the postmaster
pg_etcd.databasesComma-separated list of 1–8 distinct database names (each 1–63 bytes; quoted GUC syntax preserves case)
pg_etcd.databaseSingle-database alias; mutually exclusive with pg_etcd.databases
max_worker_processesMust leave enough background worker slots for the pg_etcd launcher plus 1 Lease worker per configured database
synchronous_commitMust be on (fsync = on, full_page_writes = on)

Changing shared_preload_libraries, pg_etcd.databases, or pg_etcd.database requires a PostgreSQL restart. Before running CREATE EXTENSION pg_etcd, create the pgetcd_owner NOLOGIN NOSUPERUSER role and grant the gateway login role only USAGE ON SCHEMA etcd and EXECUTE on the four public ABI functions (see SQL ABI).

Command-line flags

FlagPurpose
--tenant-config FILEProduction/MVP mode: start the mTLS tenant gateway from FILE (requires PGETCD_DSN)
--versionPrint the gateway version (0.1.0) and exit
--p0-fixtureInternal test mode: run the historical plaintext P0 loopback fixture (requires PGETCD_DSN)
--listen ADDRESSInternal test flag: set the --p0-fixture loopback address (default 127.0.0.1:12379; ignored in --tenant-config mode)
--qualification-config FILEInternal test mode: run development Owner/watchdog diagnostics

Exactly one of --tenant-config, --p0-fixture, or --qualification-config must be supplied when starting the server. Positional arguments are rejected.

5.2 - SQL ABI

The functions the gateway calls and the grants they need.

The SQL ABI is the contract between the Go pgetcd gateway and the C pg_etcd extension (pg_kvcore is an internal C module compiled into pg_etcd.so, not a separate extension). The gateway translates etcd v3 protobuf messages into JSONB calls over a pgx connection pool.

Extension boundary and role grants

SQL functionSignaturePurpose
etcd._abietcd._abi() RETURNS jsonbReport SQL ABI version, schema version, supported capabilities, and byte/cardinality bounds
etcd._executeetcd._execute(request jsonb) RETURNS jsonbExecute one logical KV, Lease, or diag.status operation
etcd._tail_v2etcd._tail_v2(after_revision bigint, max_envelope_bytes integer) RETURNS jsonbRead the next complete revision (> after_revision) and its manifest for Watch
etcd._publication_barrieretcd._publication_barrier() RETURNS voidWrite a logged publication barrier row when certifying startup or standalone probes

The extension also defines SQL convenience wrappers (etcd.get, etcd.put, etcd.delete_range, etcd.txn, etcd.compact) and retains legacy etcd._tail and experimental etcd._lease_probe for internal test suites. Do not grant those functions to the gateway login role.

Role separation is mandatory:

  • pgetcd_owner (NOLOGIN NOSUPERUSER) owns schema etcd, all 7 tables, and the SECURITY DEFINER entry-point functions.
  • Extension installation revokes all PUBLIC privileges on schema etcd and its objects.
  • The tenant gateway role (for example pgetcd_demo_gateway) receives only CONNECT on the database, USAGE ON SCHEMA etcd, and EXECUTE on the four functions in the table above. It has no direct table SELECT or DML privileges.
  • All public C entry points are VOLATILE PARALLEL UNSAFE SECURITY DEFINER with a fixed search_path = pg_catalog, etcd, pg_temp and execute parameterized SPI statements.

JSONB request and response envelopes

Every _execute call passes a single JSONB object of at most 2 MiB:

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

A state-dependent success response returns:

{
  "abi": "1",
  "status": "ok",
  "header": {
    "revision": "2",
    "cluster_id": "18446744073709551615",
    "member_id": "1",
    "raft_term": "0"
  },
  "response": {},
  "publication": "requires_commit",
  "certification": "performed"
}

Encoding rules:

  • All int64 and uint64 fields are canonical decimal strings (no leading zeroes, +, -0, exponents, or whitespace). cluster_id and member_id preserve the full 64-bit unsigned range.
  • Byte slices (key, range_end, value) use padded canonical RFC 4648 base64; the extension re-encodes decoded bytes to reject non-canonical padding bits.
  • Booleans use native JSON booleans; enums use upstream protobuf names ( Compare enums also accept int32 numbers for upstream compatibility). Unknown JSON fields fail explicitly.
  • State-dependent responses (both "status": "ok" and state errors such as compact_revision, future_revision, resource_exhausted, lease_not_found, lease_already_exists) carry "publication": "requires_commit" and "certification": "performed", alongside the observed header. Static validation errors (invalid_argument, unimplemented, lease_ttl_too_large) that do not inspect storage return "publication": "none".

Supported _execute methods

MethodRequest fieldsNotes
kv.rangekey, range_end, limit, revision, sort_order, sort_target, serializable, keys_only, count_only, min_mod_revision, max_mod_revision, min_create_revision, max_create_revision8 MiB response budget (p2-kv-response-v1)
kv.putkey, value, lease, prev_kv, ignore_value, ignore_leaseWrite keys capped at 2,048 decoded bytes
kv.delete_rangekey, range_end, prev_kvEmpty delete allocates no revision
kv.txncompare, success, failureMax depth 8; max 128 comparisons + operations across both branches
kv.compactrevision, physicalLogical compaction only; physical=true returns unimplemented
lease.grantID, TTLTTL < 2 normalized to 2; max 9,000,000,000 s; ID = 0 allocates a positive ID
lease.revokeIDAtomically deletes attached keys and emits DELETE events in one revision
lease.keep_aliveIDRenews committed sequence; missing lease returns TTL = 0
lease.time_to_liveID, keysMissing lease returns TTL = -1; keys=true capped by the 2 MiB Lease response budget
lease.leases{}Lists up to 1,024 active leases
diag.status{}Returns ready, primary, lease_ready, not_ready_reasons, restore_generation, storage_bytes, and persistent IDs

Transaction contract

Every gateway call runs inside one top-level READ COMMITTED transaction on the primary with synchronous_commit = on:

BEGIN ISOLATION LEVEL READ COMMITTED;
SET LOCAL synchronous_commit = on;
SELECT etcd._execute($1::jsonb);
COMMIT;
  • Metadata lock then fresh snapshot: The extension locks the single row in etcd.meta (FOR UPDATE), completes that SPI lock command, and registers a fresh snapshot after any lock wait.
  • Single-revision mutations: All Txn comparisons evaluate against the post-lock initial snapshot. Selected branch operations run sequentially so later operations in the same Txn observe earlier writes from the same Txn. All KV modifications in one _execute call share a single revision R + 1 with contiguous (R + 1, sub) event coordinates.
  • No-op and rollback preservation: Reads, empty DeleteRange, Compact, Lease-only operations (Grant, KeepAlive, TimeToLive, Leases, or revoking a Lease with zero attached keys), and rolled-back transactions do not increment the KV revision.
  • Strict transaction guards: The extension rejects READ UNCOMMITTED, REPEATABLE READ, SERIALIZABLE, standby/recovery sessions (pg_is_in_recovery()), subtransactions (SAVEPOINT), a second public ABI call in the same PostgreSQL transaction, and PREPARE TRANSACTION.

Certified publication

"certification": "performed" indicates that the extension wrote the required WAL records (either actual table mutations or an update to etcd.publication_barrier on read-only, no-op, _tail_v2, and state-error paths) after taking its snapshot. It does not mean that the transaction has committed.

The gateway buffers the entire response and releases it to the gRPC caller only after COMMIT returns normally with no PostgreSQL warning about canceled synchronous replication. If COMMIT fails, times out, is canceled, or loses its connection, the gateway discards the buffered response and never replays the request. See Transactions and publication.

Startup ABI checks

Before opening client listeners, the gateway calls SELECT etcd._abi() and diag.status to verify:

  • sql_abi = "1", schema_version = "2", and tail_abi = "2".
  • Resource profiles p1-revision-v1 (8 MiB / 4,096 events per complete revision) and p2-kv-response-v1 (max_kv_response_bytes = "8388608").
  • max_write_key_bytes = "2048", max_lease_response_bytes = "2097152", max_leases_per_database = "1024", and max_databases = "8".
  • Stored cluster_id, member_id, database_name, and lease_ready = true.

6 - Operations

Monitor, troubleshoot and build pgetcd.

Operational guides for running, diagnosing, and building pgetcd and pg_etcd:

  • Monitoring — Diagnostics HTTPS endpoints (/livez, /readyz, /health, /version, /metrics), Prometheus gauges, graceful shutdown, and single-primary switchover rules.
  • Troubleshooting — Startup, mTLS, readiness, capacity, and unknown-COMMIT recovery procedures, plus workarounds for v0.1.0-rc2 known issues.
  • Build from source — Repository layout, pinned toolchain and dependencies, build commands, and verification suites.

6.1 - Monitoring

Diagnostics endpoints, metrics and what to alert on.

This page covers health probes, Prometheus metrics, Watch client supervision, graceful shutdown, and primary switchover boundaries for the single-primary tenant gateway. When pgetcd backs Kubernetes, PostgreSQL and the gateway must be able to start without depending on that Kubernetes API server.

Diagnostics endpoints

The diagnostics listener (diagnostics_listen, port 2381 in examples) requires the same mutual TLS client certificate (spiffe://pgetcd/tenant/<tenant>) as the gRPC listener. All endpoints accept GET only and disable HTTP response caching.

EndpointResponse
/livezok (HTTP 200) if the gateway process is alive and serving
/readyz, /health{"health":true} (HTTP 200) when ready, or {"health":false} (HTTP 503) when not ready
/versionProduct version (0.1.0), advertised etcd version (3.6.0), SQL ABI (1), and resource profiles
/metricsPrometheus text exposition format with fixed metric names and no client-controlled labels

Query readiness with curl:

curl --cacert /path/to/server-ca.crt \
  --cert /path/to/tenant-client.crt \
  --key /path/to/tenant-client.key \
  https://127.0.0.1:2381/readyz

/livez checks only that the gateway HTTP handler responds. /readyz and /health also verify request admission, primary database connectivity, persistent identity, and Lease background worker readiness inside a fresh certified transaction that must complete its synchronous COMMIT within 1 second.

Warning

Since v0.1.0-rc2 (commit 81691bc), etcdctl endpoint health reports healthy, and the readiness check uses a reserved slot, so client load that fills pool_size does not withdraw readiness. The gateway logs tenant readiness withdrawn: <reason> and tenant readiness granted on each change; alert on the withdrawn line. In v0.1.0-rc1, endpoint health failed and the readiness check shared the client slots.

Prometheus metrics

All exported metrics on /metrics are gauges with no tenant keys, values, or credentials:

MetricMeaning
pgetcd_readyRuntime readiness flag (1 when ready, 0 when withdrawn)
pgetcd_publication_inflightActive requests currently holding a publication slot
pgetcd_publication_capacityConfigured publication slot capacity (pool_size)
pgetcd_pool_connections, pgetcd_pool_idle_connectionsTotal and idle connections in the PostgreSQL pool
pgetcd_watch_streamsCurrently admitted gRPC Watch streams
pgetcd_watch_senders, pgetcd_watch_receiversActive Watch sender and receiver goroutines
pgetcd_watch_tail_inflightIn-flight _tail_v2 polling transactions
pgetcd_watch_serialized_reserved_bytesReserved serialized Watch buffer bytes against watch_max_tenant_bytes

What to watch and alert on:

  • pgetcd_ready == 0: Alert immediately. Inspect diag.status in PostgreSQL (not_ready_reasons) or check whether pgetcd_publication_inflight reached pgetcd_publication_capacity.
  • pgetcd_publication_inflight approaching pgetcd_publication_capacity: Indicates slow SQL, lock contention on etcd.meta, or COMMIT waiting on synchronous standby replication. A slot remains occupied until its COMMIT finishes.
  • pgetcd_watch_serialized_reserved_bytes approaching watch_max_tenant_bytes: Indicates slow Watch consumers or high write volume; streams that exceed their buffer or tenant quota receive ResourceExhausted.

Watch client supervision

  • Watch consumers should persist a resume revision only after processing all events in a complete revision.
  • A Watch Create response confirms stream registration, not event progress.
  • If a Watch stream breaks with Unavailable, reconnect starting at last_processed_revision + 1.
  • If the requested revision has been logically compacted (CompactRevision > 0), read a fresh Range snapshot and open a new Watch at header.revision + 1 (see Use etcdctl).

Graceful shutdown

On SIGINT or SIGTERM, the gateway withdraws readiness, stops admitting new requests, closes Watch streams, and waits up to a shared 10-second deadline for in-flight publication transactions and gRPC transports to drain. When the 10-second deadline expires, it stops the gRPC and HTTP servers forcibly.

In-flight COMMIT calls hold their publication slots until they return. A completed gateway shutdown timeout does not prove that every PostgreSQL backend transaction rolled back; the gateway suppresses responses for any unresolved COMMIT and never replays it.

Primary switchover, backup, and restore

All KV rows, event history, revision manifests, history anchors, Leases, and publication barriers live in PostgreSQL tables under schema etcd.

  • Manual primary switchover: To preserve all acknowledged writes across a primary failure, PostgreSQL must run with synchronous_commit = on and a synchronous standby. After promoting the synchronous standby, point PGETCD_DSN at the new primary and restart pgetcd. In the v0.1.0-rc2 switchover smoke test (commit 81691bc, 2026-11-08), restarting the gateways after promotion took 1.03 s and kept all 52/52 acknowledged writes. This checks the procedure only; it does not provide fencing.
  • Database restore: Startup and periodic metadata checks verify database_name, database_oid, cluster_id, member_id, and restore_generation. Keep a restored database isolated until you verify these identities. Automated failover fencing and offline PITR protocol recovery (pgetcd-restore) are post-MVP roadmap items (see HA roadmap and Offline protocol recovery).

6.2 - Troubleshooting

Common failures, their symptoms and fixes, including known issues of the candidate.

When diagnosing an issue, record the gateway version (pgetcd --version), source commit, command flags, and exact error text with timestamps. Never include database passwords, private keys, or raw tenant payload values in bug reports.

Startup failures

SymptomCause and fix
select exactly one...Specify exactly one mode flag (--tenant-config, --p0-fixture, or --qualification-config) and remove positional arguments
PGETCD_DSN requiredExport PGETCD_DSN in the gateway process environment
invalid tenant configurationCheck JSON syntax, unknown or duplicate keys, field types, and the 65,536-byte file size limit
Listener rejectedUse explicit IP:port addresses and distinct non-zero ports for listen and diagnostics_listen
tenant storage configuration rejectedEnsure PGETCD_DSN connects to the same database and role as the tenant JSON and uses sslmode=verify-full on every host
Startup ABI, identity, or readiness check failedVerify CREATE EXTENSION pg_etcd, stored cluster_id / member_id, primary status, and pg_etcd.databases
Startup certification deadline reachedThe 10-second startup check timed out waiting for COMMIT; inspect PostgreSQL lock or synchronous-replication waits

Startup allows 10 seconds to certify the SQL ABI, persistent identity, and Lease readiness. It retries only when a transaction commits normally with ready = false (for example while the Lease worker finishes rebuilding). It never retries a SQL error or an unknown COMMIT.

TLS and authentication failures

Troubleshoot the two TLS hops separately:

  1. Client to gateway (listen and diagnostics_listen):
    • Confirm that the client certificate chains to tls.client_ca and carries the URI SAN spiffe://pgetcd/tenant/<tenant>.
    • If tls.server_name is set, confirm that the client dials that exact DNS name and sends matching SNI. If tls.server_name is empty, confirm that public_urls and the server certificate IP SAN match the IP address dialed by the client.
  2. Gateway to PostgreSQL (PGETCD_DSN):
    • Confirm sslmode=verify-full, sslrootcert, and hostname matching against the PostgreSQL server certificate.
    • Check every fallback host in PGETCD_DSN; any plaintext or unverified TLS option causes the gateway to reject the DSN.
    • Do not confuse the SQL client certificate (sslcert / sslkey for pg_hba.conf) with the etcd tenant client certificate.

Readiness failures

/livez can return 200 OK while /readyz returns 503 ({"health":false}) and gRPC requests return Unavailable: tenant is not ready.

Run diag.status as the PostgreSQL administrator to inspect the typed readiness fields:

BEGIN ISOLATION LEVEL READ COMMITTED;
SET LOCAL synchronous_commit = on;
SELECT etcd._execute(
  '{"abi":"1","method":"diag.status","request":{}}'::jsonb
);
COMMIT;

Check response.not_ready_reasons and the surrounding fields:

  • lease_rebuilding: The pg_etcd background worker is still reconstructing full Lease TTLs after startup. Wait for rebuild to finish and re-run the transaction.
  • worker_unavailable: Verify that shared_preload_libraries includes pg_etcd, the database name is listed in pg_etcd.databases (at most 8 databases), and max_worker_processes has enough free slots.
  • primary_required: The connected PostgreSQL instance is in recovery (pg_is_in_recovery() is true). Point PGETCD_DSN at the primary and restart the gateway.
  • identity_mismatch, schema_mismatch, or profile_mismatch: The stored cluster_id or member_id in etcd.meta, or the installed extension version, does not match the gateway configuration. After a restore or database swap, verify the intended database before editing tenant.json; changing IDs merely to bypass the check can corrupt client revision history.

Capacity and Watch errors

  • ResourceExhausted on KV or Lease calls: Compare the request against the resource limits (1.5 MiB gRPC receive, 2,048-byte write key, 8 MiB KV response tree, 4,096 events and 8 MiB per complete revision, 1,024 Leases per database, 4,096 keys per Lease). Remember that attaching a key to a Lease also checks whether revoking the entire Lease would exceed the 8 MiB / 4,096-event revision budget.
  • ResourceExhausted or Unavailable on Watch streams: A slow consumer can exhaust its per-stream queue or the tenant’s watch_max_tenant_bytes budget. Reconnect from last_processed_revision + 1, or take a new Range snapshot if history was compacted. Note that a watcher registered with a future start_revision blocks stream-level progress notifications on the same gRPC stream until that revision arrives or the watcher is canceled.

Unknown COMMIT outcomes

If the connection between the gateway and PostgreSQL drops, times out, or is canceled while COMMIT is in flight, the transaction may or may not have committed in PostgreSQL.

  • The gateway never publishes a buffered response without a confirmed synchronous COMMIT, and it never replays an unknown COMMIT automatically.
  • Before retrying a non-idempotent write, the client application must read current state (Range) or use a conditional Txn (Compare on version or mod_revision) to check whether the earlier write already took effect. Blindly retrying a write can apply the mutation twice and allocate a second revision.

Workarounds for v0.1.0-rc2 known issues

Symptom in v0.1.0-rc2Cause and workaround
Watch events arrive late during sustained heavy writesThe Watch reader reads one revision per _tail_v2 transaction and shares publication slots with client requests, so near the throughput limit (about 600 ops/s on the measured host) it falls behind. The stream stays connected and catches up when writes drop. Keep sustained write rates below that level if Watch latency matters.
Requests fail with ResourceExhausted: publication capacity exhaustedMore concurrent requests than pool_size reached one gateway and some waited longer than 5 s for a slot. Raise pool_size, add a gateway, or lower client concurrency; clients should back off and retry.
pg_etcd.so fails to load with GLIBC_2.38 not foundThe prebuilt extension tarballs were compiled on Debian 13 (glibc 2.38+). On EL8/EL9, Debian 12 or Ubuntu 22.04, build the extension from source (make -C extension).
Startup log prints "P1 incomplete"A stale string; verify the binary and ABI with /version and SELECT etcd._abi().

v0.1.0-rc2 fixed two rc1 issues: the gateway no longer withdraws readiness when client requests fill pool_size, and etcdctl endpoint health now reports healthy. If /readyz still returns 503, the gateway log line tenant readiness withdrawn: <reason> names the cause.

Build and test driver issues

  • On Linux, 16 P3 tests that require root privileges or cgroup mounts are gated behind the pgetcd_p3 build tag; standard go test ./... skips or isolates them.
  • Historical SQL and P2 Python test runners (tests/sql/run-p1-native.py and the P2 storage runner) hard-code the older P1 2 MiB output limit, macOS .dylib suffixes, or Homebrew paths; see Status — Known issues.

6.3 - Build from source

Toolchain, pinned versions and build commands.

This page describes the pgetcd repository layout, the current root-module dependencies, release build commands, and verification suites. The current tree is untagged; the v0.1.0-rc2 candidate remains documented in Releases. To start a local development tenant after building, see Quick start.

Repository layout

PathResponsibility
cmd/pgetcdGateway binary entry point (--tenant-config, --version, and internal test modes)
internal/gateway, internal/watchetcd v3 gRPC service handlers, Watch session multiplexing, and bounded event delivery
internal/pgstore, internal/pgprobeCertified SQL publication pool, transaction boundaries, and PostgreSQL state probes
internal/tenant, internal/tenantservice, internal/transportTenant JSON validation, readiness lifecycle, and mTLS listeners
extension/pg_etcd.c, extension/pg_kvcoreC/PGXS PostgreSQL extension, revision/Txn engine, _tail_v2, and Lease background workers
versions.lock.json, go.mod, go.sumPinned upstream reference versions and Go module checksums
tests/, scripts/SQL suites, official client probes, Watch race tests, and historical gate checkers

Toolchain and pinned versions

The current root tree after the 2026-11-11 dependency refresh requires the following versions:

ComponentPinned versionNotes
Go1.27.4Static gateway compilation (CGO_ENABLED=0)
PostgreSQL18.6 (REL_18_6)Server headers (postgresql-server-dev-18) and pg_config for PGXS
etcd Go API and clientv3v3.7.3Uses standard google.golang.org/protobuf bindings
gRPC / protobufv1.85.0 / v1.36.12Upstream generated protobuf bindings are consumed directly; protoc is not required for builds
pgxv5.12.0PostgreSQL wire driver and connection pool
Supporting modulesgrpc-gateway v2.33.0; x/net v0.62.0; x/sync v0.25.0; x/sys v0.50.0; x/text v0.44.0The complete selected module graph is recorded in go.mod and go.sum
Reference servers (test only)etcd v3.6.15, v3.7.2; Kubernetes v1.36.4, v1.37.1Locked in versions.lock.json for differential and storage probes

The reference-server modules under tests/ keep these versions because they are compatibility inputs. They are separate from the root gateway module.

Build commands

Gateway (pgetcd)

Build a development binary for the local host:

go build -o .cache/docs-dev/pgetcd ./cmd/pgetcd

Build a reproducible static Linux binary (used for the v0.1.0-rc1 and v0.1.0-rc2 archives on amd64 and arm64):

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o pgetcd ./cmd/pgetcd
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -ldflags "-s -w" -o pgetcd ./cmd/pgetcd

PostgreSQL extension (pg_etcd)

Compile and install the C/PGXS extension against your target PostgreSQL 18 installation:

make -C extension PG_CONFIG=/path/to/postgresql/bin/pg_config
make -C extension PG_CONFIG=/path/to/postgresql/bin/pg_config install

This installs lib/pg_etcd.so, share/extension/pg_etcd.control, and share/extension/pg_etcd--0.1.0.sql. To build inside a clean Debian 13 container (postgres:18.6), install build-essential and postgresql-server-dev-18 first and run make -C extension. Note that binaries compiled on Debian 13 require glibc 2.38 or newer; compile directly on the target distribution when targeting EL8/EL9, Debian 12, or Ubuntu 22.04.

Verification commands

On 2026-11-11, the current untagged tree passed go build ./cmd/..., go test ./..., and go vet ./... on macOS arm64 with Go 1.27.4. The pgx refresh also required the legacy batch-error adapter to implement pgx.BatchResults.Tx(). This local check does not replace the Linux release checklist for a future candidate.

CommandScope
go build ./cmd/...Compile gateway and helper commands; passed on the current macOS arm64 tree on 2026-11-11
go vet ./...Static analysis across all non-isolated packages; passed on the current macOS arm64 tree on 2026-11-11
go test ./...Unit and package tests; passed on the current macOS arm64 tree on 2026-11-11
make -C extension PG_CONFIG=...Compile pg_etcd.so with zero warnings
python3 tests/sql/run-p1-native.pySpin up an isolated temporary PostgreSQL cluster and run the SQL ABI test suites
python3 tests/sql/run-p1-multidb.pyVerify 8-database Lease worker supervision and tenant isolation on a temporary cluster
Note

The repository also contains make p0-gate, make p1-gate, and make p2-gate targets that audit archived evidence from the 2026-10-08 frozen candidate, as well as P3 native/cgroup tests isolated behind -tags pgetcd_p3. For v0.1.0-rcN, follow the lean release regression checklist described in Status.

7 - Status

Current candidate, its test results, known issues and what remains for the MVP.

pgetcd is in Release candidate status. On 2026-11-08 the project approved the MVP goal, which makes the release candidate v0.1.0-rcN the only current completion target and moves P3 high availability and the native runtime work out of the current scope.

Current candidate

Status
Release candidate
Local tag
v0.1.0-rc2 on commit 81691bc (branch main); the verification ran on this commit on 2026-11-08
Superseded
v0.1.0-rc1 on commit 250df4c
Publication state
Local tag and local tarballs only; the repository has no remote and nothing is published
Toolchain and base
Go 1.27.3 (CGO_ENABLED=0), etcd API/client 3.7.2, gRPC 1.84.0, pgx 5.11.0, PostgreSQL 18.6
SQL ABI and schema
Product version 0.1.0, extension 0.1.0, SQL ABI 1, schema 2, advertised etcd version 3.6.0

Fixed since rc1

  • Readiness under load (commits fad4d2f, db0577b): the once-per-second readiness check now uses a slot reserved for it. Client requests that find every publication slot busy wait up to 5 s instead of failing at once, so concurrency at or above pool_size no longer makes the gateway report tenant is not ready. The gateway logs each readiness change.
  • etcdctl endpoint health (commit 81691bc): the Maintenance.Alarm list query returns an empty list, so endpoint health reports healthy. Alarm activation and deactivation still return Unimplemented.

Verification results

The v0.1.0-rc2 verification ran on 2026-11-08 on a clean checkout of commit 81691bc, following the lean checklist of the MVP goal. The environment was a PostgreSQL 18.6 container on Linux amd64 (Ubuntu 26.04). The gateways used the default pool_size = 32.

CheckPlatformResultDetail
go build ./cmd/..., go vet ./..., go test ./...amd64Pass0 vet findings; 5,176 PASS / 0 FAIL / 49 SKIP (skips are integration tests that need dedicated fixtures)
Extension build and SQL suitesamd64Pass12 P1 SQL suites, the P2 KV output suite and 1,001 persistent Tail calls
Watch and gateway race integrationamd64Pass89 PASS; the wake and polling fallback cases pass
Official etcdctl 3.6.15 / 3.7.2 probesamd64Pass50 PASS / 0 FAIL, including endpoint health
Few-minute concurrency testamd64Pass, one known issue100,000 puts at 64 clients (171 s), 100,000 puts at 128 clients (168 s), 50,000 ranges at 128 clients (88 s): 0 refused requests and 0 readiness withdrawals; a long-lived Watch stayed connected, but its events lagged (known issue 1)
Primary switchover smokeamd64PassCrash-stop the primary, promote the synchronous standby, restart the gateways in 1.03 s; 52/52 acknowledged writes kept
Package install smokeamd64, arm64PassAll 4 tar.gz archives install on stock postgres:18.6 and pass CREATE EXTENSION, the readiness check and a read/write test
Kubernetes conformance—Outside the MVP verification scopeReference: on rc1 the k8s.io/apiserver 0.36.4 and 0.37.1 storage probes passed 65 tests per version

The P1 mixed model audit (100,000 calls) passed on rc1 and is no longer part of the checklist. Releases keeps the full rc1 results.

Important

The primary switchover smoke test checks only the manual operator procedure: promote the synchronous standby, point PGETCD_DSN at it and restart the gateway. pgetcd v0.1.0-rc2 does not provide automatic fencing or response consistency during a switchover.

Performance numbers

Measured once on v0.1.0-rc2 (commit 81691bc, Linux amd64, 2026-11-08) with two gateways (default pool_size = 32), one PostgreSQL 18.6 primary and one synchronous standby on the same host, using the benchmark tool from etcd v3.6.15. These are observations, not an SLA.

WorkloadThroughput (ops/s)p50 latencyp99 latencyRefused
Put 256 B, 1 client6281.6 ms2.7 ms0
Range (linearizable), 1 client7341.3 ms2.4 ms0
Put 256 B, 64 clients58572 ms538 ms0
Put 256 B, 128 clients595185 ms586 ms0
Range (linearizable), 128 clients569231 ms248 ms0

Known issues in v0.1.0-rc2

#IssueImpact and workaround
1Watch events lag under sustained heavy writesEach _tail_v2 call of the Watch reader reads one revision, in a transaction that takes the metadata lock and waits for synchronous COMMIT, and it shares slots with client requests. Near the throughput limit the reader falls behind; the connection stays up and catches up when writes drop. Measured on 81691bc: after 30,000 puts in 52 s at 128 clients, the Watch delivered the last event 24 s later. Idle Watches deliver at once.
2Throughput is about 600 ops/s, reads includedReads also take the etcd.meta lock, write a publication barrier and wait for synchronous COMMIT. Requests beyond the publication slots wait up to 5 s and receive ResourceExhausted only if still waiting.
3Extension packages require glibc 2.38+Prebuilt extension tarballs target Debian 13 / Ubuntu 24.04+ and PostgreSQL 18. Older distributions (EL8/EL9, Debian 12, Ubuntu 22.04) must build from source; there are no RPM or DEB packages yet.
4Kubernetes conformance is outside the MVP verification scopeThe upstream storage probe on rc1 passed 65 tests per version and serves as a reference only.
5Historical SQL/P2 test drivers need path patchestests/sql/run-p1-native.py still checks the old P1 2 MiB output limit and the macOS .dylib suffix, and the P2 driver hard-codes Homebrew paths.
6Stale startup bannerThe startup log line still prints "P1 incomplete".
7Narrow arm64 coverageOn rc2, linux/arm64 ran only the package build and install smoke. On rc1 it also ran the Go unit tests and the extension SQL suites.

Previous frozen candidate (2026-10-08)

Before the Go 1.27.3 root dependency refresh, the frozen candidate of 2026-10-08 (0.1.0-p1, Go 1.27.1, PostgreSQL 18.6) completed the initial P0 (17 items), P1 (22 groups) and P2 (20 groups) acceptance gates:

  • P1 mixed model audit: 1,000,000 mixed KV and Lease operations with an independent model and two-stream Watch audit on one primary.
  • P2 Kubernetes storage suites: 1,219 PASS / 0 FAIL / 8 SKIP on 1.36.4 and 1,196 PASS / 9 FAIL / 4 SKIP on 1.37.1 (all 9 failures in 1.37.1 were in declared unsupported RangeStream and physical Compact tests).
  • P2 selected Kubernetes conformance: 446 passed cases on 1.36.4 and 462 passed cases on 1.37.1, with 0 runtime skips.

Those results define the MVP API scope but do not certify the newer v0.1.0-rc2 binary.

After the MVP

The MVP goal defers these items:

  • HA support: its scope and verification will be defined when it is needed. The earlier design material stays in the HA roadmap and Recovery design.
  • MVP+1 HTTP/JSON gateway and Patroni: add the HTTP/JSON paths that Patroni’s etcd3 client uses, and validate Patroni with pgetcd hosted on a separate PostgreSQL cluster.
  • RangeStream and other unimplemented RPCs, a dedicated security review, and the shared Mimus runtime.
  • The frozen native research line is kept as material only; see The frozen native line.

8 - Releases

The release candidate and the acceptance checkpoints before it.

pgetcd has not made a public release. The records below bind every test result and artifact hash to the exact source candidate, platform, and date that produced it.

Release policy and identifiers

Each candidate record specifies its source commit, artifact SHA-256 digests, test platform, and verification scope. A result from an earlier checkpoint does not certify modified source bytes, and a local tag or tarball build does not constitute a public release.

IdentifierValue in v0.1.0-rc2Meaning
Gateway product version0.1.0Reported by pgetcd --version and diagnostics /version (earlier P1/P2 checkpoints used 0.1.0-p1)
Extension version0.1.0Installed by pg_etcd.control and pg_etcd--0.1.0.sql
SQL ABI / schema1 / 2Checked by the gateway via SELECT etcd._abi() before opening listeners
Advertised Status.Version3.6.0Used for clientv3 and Kubernetes feature detection; does not claim full etcd 3.6 RPC coverage

v0.1.0-rc2 (2026-11-08)

v0.1.0-rc2 is a local Git tag on commit 81691bc (branch main); the verification ran on that commit. It replaces v0.1.0-rc1. The repository has no remote; neither the tag nor the archives are published. An earlier local rc2 tag on feead4d, with only the first readiness fix, was never pushed and was replaced the same day.

Changes since rc1

  • Readiness under load (commits fad4d2f, db0577b): the readiness check uses a reserved slot that only the readiness monitor uses. Client requests that find every publication slot busy wait up to 5 s instead of failing at once; no SQL starts while they wait. The number of slots and connections is unchanged. The gateway logs each readiness change.
  • Maintenance.Alarm (commit 81691bc): the list query returns an empty list under a certified header, so etcdctl endpoint health reports healthy. Activation and deactivation return Unimplemented.

Artifacts

ArchiveSHA-256
pgetcd-0.1.0-linux-amd64.tar.gz5353e1dec969a24bf0e620ac5b38aa155c8b9bb69dd9ed1efcbd9b27d167a3c8
pgetcd-0.1.0-linux-arm64.tar.gzc8715c4e5f0f1474546e04ba6d2dc49112f1501b1934b11c3675b8c57e99cc84
pg_etcd-0.1.0-pg18-linux-amd64.tar.gz3b7686da13211898de044b04fd38e1a4ca96be443b8039116f559756b10d9b07
pg_etcd-0.1.0-pg18-linux-arm64.tar.gzcaae1311fd9e55b1356d003140b92b7a9d85001b249eb5cc68e2cb150c196a64

Contents, build commands and the glibc 2.38 requirement are the same as for rc1. The extension source has not changed since rc1.

Verification results

The lean checklist of the MVP goal ran on 2026-11-08 on a clean checkout of 81691bc (Linux amd64, PostgreSQL 18.6 container, default pool_size = 32): Go build, vet and 5,176 PASS / 0 FAIL / 49 SKIP tests; extension SQL suites; 89 PASS Watch and gateway race integration; etcdctl probes 50 PASS / 0 FAIL; a few-minute concurrency test at 64 and 128 clients with 0 refused requests and 0 readiness withdrawals; the primary switchover smoke; and the archive install smoke on amd64 and arm64. The P1 audit was not repeated and Kubernetes conformance is outside the MVP verification scope. Status has the table, the performance numbers and the known issues.

v0.1.0-rc1 (2026-11-08)

Note

Superseded by v0.1.0-rc2, which fixes known issues 1 and 2 below.

v0.1.0-rc1 is a local Git tag on commit 250df4c (mvp/v0.1 branch). The release regression ran on commit 7e43446; commit 250df4c changes only README.md. Neither the tag nor the binary archives have been pushed or published. The mvp/v0.1 branch has since been renamed main.

Artifacts and build

ArchiveSHA-256
pgetcd-0.1.0-linux-amd64.tar.gz463c488e80819e8602a2a33d787f06feea0418db4a734baa9c725e08ed73b6de
pgetcd-0.1.0-linux-arm64.tar.gz28ec5375b7e8b8e5062ef6e52384e32cb39bbd18ac30948c5d9aadf9bcd77048
pg_etcd-0.1.0-pg18-linux-amd64.tar.gz049a9c289c9d574c5385f3ea9efe98ea9c6cd7908f4df7c452f1a4fe1e4c6c9a
pg_etcd-0.1.0-pg18-linux-arm64.tar.gze407d16986ad2420ee4dde0d2a8040f6c48ee9896e5b8f2fed8597a1bfcd2dc5
  • Gateway archives contain a static bin/pgetcd binary built with Go 1.27.3:
    CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o pgetcd ./cmd/pgetcd
  • Extension archives contain lib/pg_etcd.so, pg_etcd.control, and pg_etcd--0.1.0.sql, built on the target architecture inside postgres:18.6 (Debian 13) with make -C extension. They require PostgreSQL 18 and glibc 2.38 or newer.
  • Every archive includes LICENSE, NOTICE, and installation notes. No RPM, DEB, or OCI container image is published yet.

Regression results

Executed on a clean checkout of commit 7e43446 on 2026-11-08 (Linux amd64: PostgreSQL 18.6 container on Ubuntu 26.04, 32 cores; Linux arm64: linux/arm64 container on Apple Silicon):

Checklist itemPlatformResultNotes
go build ./cmd/...amd64, arm64Pass
go vet ./...amd64, arm64Pass0 findings
go test ./...amd64, arm64Pass5,168 PASS / 0 FAIL / 49 SKIP (skips require external integration fixtures)
Extension build and SQL suitesamd64, arm64Pass0 warnings; 12 P1 SQL suites, P2 KV output suite, and 1,001 persistent Tail calls
Watch and gateway race integrationamd64Pass88 PASS, including wake and polling fallback cases
P1 mixed model audit (100,000 calls)amd64Pass2 mTLS gateways; 100,000 mixed KV calls, 30,011 Lease calls, 20,006 controls across 5,002 windows; 0 unknown outcomes; offline replay, SQL catalog check, and 2-stream Watch audit passed
Official etcd client probesamd6448 PASS / 2 FAILetcdctl 3.6.15 and 3.7.2: both failures are endpoint health; clientv3 3.6.15 and 3.7.2 Watch suites passed
Upstream k8s.io/apiserver storage probeamd64Pass0.36.4 and 0.37.1 etcd3 storage passed 65 tests each, including 1.37 RangeStream fallback
Primary switchover smokeamd64PassCrash-stop primary, promote synchronous standby, restart gateway in 1.03 s; 52/52 acknowledged writes preserved; identity unchanged
Archive install smokeamd64, arm64PassAll 4 archives installed in stock postgres:18.6, passed CREATE EXTENSION, readiness check, and read/write verification

During the regression run, 16 Linux P3 tests requiring root or cgroups were isolated behind the pgetcd_p3 build tag, and 3 Linux-only go vet warnings were fixed.

Performance baseline

Measured once on v0.1.0-rc1 (commit 7e43446, Linux amd64) using benchmark from etcd v3.6.15 against two gateways and one PostgreSQL 18.6 primary with a same-host synchronous standby (pool_size = 128 for 64-client runs):

TestThroughput (ops/s)p50p99
Put 256 B, 1 client5911.6 ms3.1 ms
Range (linearizable), 1 client4821.7 ms3.1 ms
Put 256 B, 64 clients53576 ms632 ms
Put 8 KiB, 64 clients47467 ms662 ms
Range (linearizable), 64 clients561115 ms125 ms
Txn (4 puts), 64 clients357174 ms491 ms
LeaseKeepAlive, 64 clients99264 ms71 ms

Known issues

v0.1.0-rc1 had 8 recorded known issues. The first two, readiness withdrawal when concurrent requests filled pool_size (default 32) and etcdctl endpoint health failing on the unimplemented Maintenance.Alarm, are fixed in rc2. The others, such as the glibc 2.38+ package requirement, carry over; Status lists the current rc2 issues.

Upgrade policy

v0.1.0-rc1 and v0.1.0-rc2 support only a fresh schema 2 installation; they share the schema, SQL ABI and extension, so moving from rc1 to rc2 replaces only the gateway binary. In-place upgrade migration from earlier development checkpoints is not supported.

Historical checkpoints

DateCandidate or checkpointSummary
2026-11-08v0.1.0-rc2 (commit 81691bc)Readiness under load fixed, Alarm list query added; lean verification under the MVP goal
2026-11-08v0.1.0-rc1 (commit 250df4c, regression 7e43446)First MVP release candidate under Design 0357; Linux amd64/arm64 tarballs and regression checklist completed
2026-11-11Unreleased root dependency refreshGo 1.27.4, etcd API/client v3.7.3, gRPC v1.85.0, pgx v5.12.0 and selected supporting modules; build, test and vet passed on macOS arm64; no tag or archives
2026-10-22root-go1273-20261022 dependency upgradeUpgraded root checkout to Go 1.27.3, etcd API/client 3.7.2 (standard google.golang.org/protobuf bindings replacing gogo), gRPC 1.84.0, protobuf 1.36.12, and grpc-gateway 2.32.0 while keeping pgx 5.11.0, SQL ABI 1, and advertised 3.6.0
2026-10-11 – 2026-11-04P3 native runtime and kernel checkpointsResearch series on custom PG wire/TLS, Go runtime accounting, and Linux kernel SLUB accounting; frozen on 2026-11-08 as post-MVP research (see Frozen native P3 line)
2026-10-08Frozen single-primary checkpoint (0.1.0-p1)Accepted P0 (17 feasibility items), P1 (22 groups, including the 1,000,000-call model/Watch audit), and P2 (20 groups, 8 MiB p2-kv-response-v1 budget, Kubernetes 1.36.4 and 1.37.1 storage suites, and 446 / 462 selected conformance cases)

9 - Design

The decisions that define pgetcd, condensed from its design records.

pgetcd’s companion repository accumulated 357 dated design and implementation records during development. This section condenses the architectural decisions that govern the current codebase and separates the active MVP scope from post-MVP roadmap and frozen research work.

Current goal and review

  • Status review, 2026-11-08 — Where the project stood before the MVP decision: code almost untracked, P3 drifted into kernel accounting, and why the work did not converge; with the outcome up to v0.1.0-rc2.
  • MVP goal (v0.1.0) — Approved on 2026-11-08: the v0.1.0-rcN release candidate is the only completion condition, with the single-primary scope, the lean release checklist and the rule that verification stays proportionate to an MVP. The current candidate is v0.1.0-rc2 (commit 81691bc).

Core architecture decisions

  • PostgreSQL as the authority — Why revisions, transactions, Leases, and event history live in logged PostgreSQL tables under a single meta-row lock rather than sequences or gateway caches (Design 0005).
  • Certified publication — Why read requests write a WAL barrier, why responses wait for synchronous COMMIT, and why unknown commits are never replayed (Design 0006).
  • Lease, Watch and history — Why Lease deadlines rebuild with a full TTL on restart, why NOTIFY is only a wake hint, and how anchor generations support atomic compaction (Design 0007).
  • Runtime boundary — Why pgetcd, pgsilo, and pgredis keep separate gateway processes and extensions until shared runtime integration is built (Design 0004).

Post-MVP roadmap and research

  • High availability roadmap — Target 3-node synchronous replication topology, primary fencing requirements, and single-container fault-injection findings (Design 0028, Design 0119).
  • Recovery design — Point-in-time recovery protocol rebasing (pgetcd-restore) and per-gateway publication revision journals (Design 0029, Design 0030).
  • The frozen native line — Summary of the 340+ records exploring custom wire stacks, Go runtime accounting, and the Linux shared-kernel accounting boundary (Design 0119, Design 0320, Design 0357).

9.1 - PostgreSQL as the authority

One Go gateway and one extension; a meta-row lock and a fresh snapshot per request; no sequences.
Note

Condensed from Design 0005 (accepted 2026-10-08, following architecture v1.0 dated 2026-10-05).

Decision

pgetcd splits the etcd v3 server into a stateless Go protocol gateway (pgetcd) and a single C/PGXS PostgreSQL extension (pg_etcd, with internal C helpers in pg_kvcore linked into the same shared library). PostgreSQL 18 is the implementation baseline.

All authoritative state—current revision R, compact revision C, history floor F, live KV rows, complete event history, revision manifests, Lease records, and cluster identity—lives in regular WAL-logged PostgreSQL tables inside the tenant database. Protocol reads and writes both route to the PostgreSQL primary.

Each logical etcd request executes inside one READ COMMITTED transaction:

  1. Lock the single row in etcd.meta (SELECT ... FOR UPDATE).
  2. Acquire a fresh PostgreSQL snapshot after the lock wait completes.
  3. Evaluate the request against that snapshot.
  4. Allocate at most one revision (R + 1) if the request performs one or more actual KV mutations; leave R unchanged on reads, no-op deletes, Lease-only operations, Compact, or rollbacks.

Why sequences and gateway caches are rejected

PostgreSQL SEQUENCE (nextval) advances outside transactional commit order: if two transactions call nextval concurrently or one rolls back, committed rows can appear out of revision order or contain uncompacted revision gaps, breaking etcd Watch cursors and Txn revision comparisons.

Similarly, caching the current revision or Lease expiration clock inside the Go gateway breaks as soon as two gateway processes share a tenant database or a gateway restarts. Keeping etcd.meta and etcd.leases in logged tables makes PostgreSQL the single source of truth across gateway restarts and multi-gateway deployments.

Keeping pg_kvcore as an internal static library inside pg_etcd avoids stabilizing a second public C/SQL ABI before another extension needs it.

Costs and trade-offs

Locking etcd.meta per request provides strict per-tenant serial ordering and a simple post-lock snapshot invariant, at the cost of serializing requests within a single tenant database.

Every mutation writes live KV state, complete new/previous event tuples, and a revision manifest row into WAL, requiring regular PostgreSQL VACUUM and sufficient background worker capacity. Multi-request batching and table partitioning require separate designs and are outside the MVP scope. See Transactions and revisions and Schema.

9.2 - Certified publication

Why reads write a barrier, why responses wait for synchronous commit, and why unknown commits are not replayed.
Note

Condensed from Design 0006 (accepted 2026-10-08).

Decision

Before sending any state-observing gRPC response to a client, pgetcd requires two steps:

  1. In-transaction certification: Capture a consistent post-lock snapshot inside pg_etcd. If the request does not already write WAL after that observation (for example, a read or a failed comparison), update the logged counter in etcd.publication_barrier.
  2. Synchronous commit before publication: Buffer the provisional response in the gateway’s Publisher component and execute a synchronous COMMIT (synchronous_commit = on). Release the buffered response to the gRPC stream only after COMMIT succeeds with zero PostgreSQL warnings.

This rule applies to Range, read-only or false-branch Txn replies, Watch creation (Created), Watch event batches, Watch progress notifications, MemberList, Status, and state-dependent errors (ErrCompacted, ErrFutureRev, ErrLeaseNotFound).

A single certified snapshot can serve multiple Watch streams during one tail cycle, but an earlier barrier never certifies a snapshot taken later.

Why read barriers are required

In PostgreSQL synchronous replication, a committing backend writes its WAL record and makes the transaction locally visible in shared memory before waiting for the synchronous standby to flush WAL. If an operator cancels that backend (pg_cancel_backend), terminates it, or restarts the primary before the standby acknowledges the LSN, another local backend running a plain SELECT can read locally visible rows that never reached the synchronous standby. If a failover then promotes the standby, any etcd response derived from that uncertified read would violate linearizability.

By writing a WAL-logged row to etcd.publication_barrier after taking the read snapshot and requiring that transaction’s own synchronous COMMIT to succeed without warnings, pgetcd guarantees that the standby has flushed both the barrier’s LSN and every earlier LSN visible in the read snapshot.

Plain SELECT queries, empty transactions, pg_current_wal_lsn() reads, UNLOGGED table writes, or barriers written before the snapshot do not establish this WAL ordering. The trade-off is that every read and state-dependent error pays a small WAL write and synchronous commit round-trip.

Unknown commit outcomes

The Publisher retains its database connection and inflight admission slot until COMMIT returns a known result. If COMMIT fails, returns a PostgreSQL warning (such as a canceled synchronous-replication wait), or loses its connection before the result is known, the buffered gRPC response is discarded and an error is returned to the client.

The gateway never automatically replays a transaction whose COMMIT outcome is unknown, because the transaction may have committed on the server just before the connection dropped. Retrying clients must resolve ambiguity using Txn predicates or application idempotency keys. See Transactions and revisions.

9.3 - Lease, Watch and history

Full-TTL rebuild after restart, NOTIFY as a hint, and anchor generations for compaction.
Note

Condensed from Design 0007 (accepted 2026-10-08).

Lease durability and full-TTL rebuild

pgetcd stores durable Lease facts—Lease ID, a 128-bit grant generation (grant_hi, grant_lo), granted TTL (granted_ttl_sec), renewal sequence (renew_seq), and attached-key byte ledgers—in etcd.leases. Monotonic expiration deadlines live in shared memory managed by a supervised PostgreSQL background worker (pg_etcd preload).

Before deciding whether a Lease has expired, the extension acquires locks in strict etcd.meta-then-etcd.leases order and refreshes shared-memory state from any newer committed renew_seq. It never holds a shared-memory lock while waiting for a PostgreSQL row lock.

When PostgreSQL or the Lease background worker restarts, tenant readiness (/readyz) closes while a new worker generation reconstructs runtime deadlines from etcd.leases. Every surviving Lease receives a full granted_ttl_sec starting from the reconstruction timestamp before readiness reopens. This conservative choice prevents premature Lease revocation and accidental key deletion across restarts, at the cost of delaying expiry by up to one full TTL per restart.

Watch event boundaries and wake hints

etcd.events stores both the complete new tuple and the complete previous tuple (prev_*) for every PUT and DELETE, paired with a per-revision summary in etcd.revision_manifest. The gateway’s Watch service reads events through etcd._tail_v2, verifies the manifest’s event count and byte budgets, certifies the scanned watermark, and advances watcher cursors only across complete revisions.

PostgreSQL LISTEN / NOTIFY messages are treated strictly as wake hints. A missed notification never loses events or stalls a stream permanently, because periodic polling (watch.poll_interval_ms) reads the durable event table directly. Stream-wide progress (watch_id = -1) is emitted only when every watcher on the stream is caught up; a Created response confirms registration only, not historical catch-up.

History anchors and atomic compaction

Rather than mutating historical events in place, Compact(rev) builds a complete baseline snapshot of all live keys at revision rev inside etcd.history_anchor under a new generation number. Within the same transaction, it updates etcd.meta to switch anchor_generation and set F = C = rev, then deletes older anchor generations and events strictly below F.

Events at the boundary revision F itself—including DELETE tombstones—remain in etcd.events. Keeping boundary tombstones ensures that historical Range reconstruction at F properly masks deleted keys and that Watch streams starting at F still observe the deletion event. See Watch, Lease and history.

9.4 - Runtime boundary

Why etcd, S3 and Redis keep separate gateways instead of one shared runtime.
Note

Condensed from Design 0004 (accepted 2026-10-08).

Decision

Within Mimus, pgetcd implements the etcd v3 gRPC gateway and pg_etcd C extension, alongside pgsilo / pgs3 for S3 object storage and pgredis for Redis. Although an earlier parent plan (“WOK”) considered combining the Go gateways for etcd, S3, and Redis into a single multi-protocol Go daemon, Design 0004 keeps the current pgetcd binary, module name, pg_etcd extension, and internal pg_kvcore boundary separate until shared runtime integration is explicitly designed and verified.

Why gateways stay separate

Each protocol gateway has distinct network framing, concurrency patterns, and PostgreSQL failure semantics:

  • etcd (pgetcd) requires HTTP/2 gRPC with tenant mTLS, per-request etcd.meta serialization, read certification barriers, synchronous COMMIT before response publication, and a preloaded C background worker for Lease expiration.
  • S3 (pgsilo) streams large binary object payloads over HTTP/1.1 with SigV4 authentication and chunked transfer encoding.
  • Redis (pgredis) serves RESP2/RESP3 commands over persistent TCP connections with pub/sub and blocking list semantics.

Merging these listeners into one process without unified admission control would allow a memory spike or slow stream in one protocol to starve Lease keepalives or Watch delivery in pgetcd.

Requirements for future integration

Before any shared gateway runtime or cross-protocol extension layer is adopted, it must define and test:

  • Process lifecycle, configuration reload, and per-protocol memory/connection admission limits.
  • Tenant isolation and credential mapping across protocols.
  • Explicit rules for whether protocols share a database, schema, or transaction boundary.

In the current architecture, each protocol installs its own schema and keeps its acceptance and release regression evidence independent. Passing an etcd regression suite does not certify another protocol or cross-protocol table access. See Architecture and Status.

9.5 - High availability roadmap

The post-MVP design for production HA, and the fault tests that informed it.
Important

Production high availability is a post-MVP roadmap design (Planned). The current MVP release candidate (v0.1.0-rc2) runs against a single PostgreSQL 18 primary and does not automate primary failover or fencing; after a primary switchover, operators must restart the pgetcd gateway.

Target topology

The post-MVP production HA design calls for three PostgreSQL 18 data nodes, an independent Distributed Consensus Store (DCS), and at least two stateless pgetcd gateways per tenant. The PostgreSQL cluster and its DCS must bootstrap independently—never host a Patroni cluster’s own DCS inside the pgetcd service backed by that same PostgreSQL cluster.

The target Patroni synchronous replication settings are:

synchronous_mode: on
synchronous_mode_strict: true
synchronous_node_count: 1
check_timeline: true

To prevent split-brain writes or stale reads during a network partition, an isolated or stalled old primary must be fenced via hardware/kernel watchdog.mode: required or validated STONITH before a standby promotes. A VIP, load balancer health check, or SQL pg_is_in_recovery() query is not a substitute for primary fencing.

Admission and route retirement

In the target HA lifecycle, each gateway incarnation starts with client admission closed. Opening admission requires verifying:

  1. Valid primary authority and an eligible synchronous standby.
  2. Matching database identity, extension version (0.1.0), schema version (2), and SQL ABI (1).
  3. A successful logged publication barrier commit.
  4. Completed Lease background worker reconstruction for the current worker generation.

When primary authority or worker readiness is lost, the gateway must immediately close new request admission, terminate active Watch delivery, and wait for in-flight SQL connections and sender goroutines to drain before retiring the route.

Component fault-injection findings (Design 0028)

On 2026-10-14, research candidate 1205/v6 ran component-level synchronous replication and physical promotion fault tests on Linux amd64 with PostgreSQL 18.6 (three PostgreSQL instances per test container):

Fault testResultObserved behavior
Abnormal SyncRep writer102 / 102 PASS (34 cancel, 34 terminate, 34 disconnect)Local state left visible by a canceled SyncRep wait is withheld by the read barrier; canceling the barrier returns zero bytes; restoring the synchronous standby allows a normal COMMIT to publish
Protocol observation gatingPASSRange, read-only Txn, and state-dependent Compact errors wait for synchronous barrier certification before leaving the gateway
Fresh Lease promotion50 / 50 PASSAfter synchronous flush/replay and standby promotion, the new Lease worker reconstructs durable Leases with a new owner generation and a full TTL; synchronous standby covers the new watermark
Old-primary crash and restart1 / 1 PASSCrashed primary recovers local state but withholds uncertified reads until synchronous replication and qualified promotion complete

These runs validated the C extension and Publisher COMMIT invariants across physical replication promotions inside a single container. They do not establish multi-host network partition tolerance, independent DCS/watchdog fencing, or automatic gateway endpoint switching.

Post-MVP acceptance gates

Before claiming production HA support in a future release, the roadmap (Design 0119 / ha-recovery) requires:

AreaTarget gate
Failover promotionsAt least 50 planned and fault-driven promotions in a 3-node PostgreSQL + independent DCS + 2-gateway topology, with target RTO <= 30 s when an eligible synchronous candidate exists
Synchronous replication faultsAt least 100 seeded abnormal SyncRep fault scenarios with zero exposed uncertified state
Endurance72-hour mixed-fault run with zero linearizability violations, premature Lease expirations, or silent Watch stalls
Multi-tenant capacityMeasured steady-state runs across 1, 3, and 20 tenants (requiring an extension of the current 8-database Lease worker allowlist)

Upgrade boundaries

Rolling gateway upgrades require a compatible SQL ABI (etcd._abi()). An incompatible pg_etcd extension upgrade requires a maintenance window: draining gateways, taking a verified backup, running the SQL migration, restarting PostgreSQL sessions that loaded the old shared library, and verifying /readyz before reopening client traffic.

9.6 - Recovery design

Point-in-time recovery and revision journals. Designed, not in the release.
Important

The offline protocol recovery tool (pgetcd-restore) and per-gateway publication revision journals (PGETCD_REVISION_JOURNAL) were prototyped in P3 research candidates (1212/v5 and 1216/v4, 2026-10-14) and are not included in the MVP release tree (v0.1.0-rc1, v0.1.0-rc2). This page documents their design as part of the post-MVP roadmap.

Why physical PITR needs protocol rebasing

When PostgreSQL restores a physical base backup and replays archived WAL to a recovery target (Point-in-Time Recovery, or PITR), the restored database state can end at a revision R_restored that is lower than the highest revision R_exposed already returned to etcd clients before the outage.

If a gateway reopened traffic directly on R_restored:

  • Subsequent writes would reuse revisions R_restored + 1 .. R_exposed with different keys and values, violating etcd revision monotonicity.
  • Active Watch clients holding cursors at R_exposed would either stall waiting for future revisions or silently miss the state rollback.

Safe recovery therefore requires knowing a trustworthy upper bound on R_exposed, rebasing the database’s current and compact revisions strictly above max(R_exposed, R_restored), and rotating the logical cluster_id and member_id so clients detect a new cluster incarnation and relist.

Per-gateway revision journals (Design 0030)

If the original PostgreSQL primary is still accessible in maintenance mode after traffic drains, an operator can query its final etcd.meta.revision directly. If the primary disk is lost, however, the backup alone does not record how many later revisions gateways published before the crash.

Design 0030 (prototyped in candidate 1216/v4) addresses this by wrapping the gateway’s Publisher with an optional per-gateway revision journal (PGETCD_REVISION_JOURNAL):

  1. At startup, the gateway records the source database and cluster identity in its local journal file before opening client listeners.
  2. After each normal synchronous COMMIT, the wrapper writes any new high-water revision to the journal and calls fsync before returning the KV, Lease, Watch, or diagnostic result to the client.
  3. If writing or syncing the journal fails (for example, ENOSPC), the wrapper withholds the gRPC response and closes admission for subsequent SQL calls.

During recovery after source loss, the operator collects the journal files from all gateways that served the tenant and merges them with the verified physical backup_manifest (pgetcd-restore export-journals) to establish a conservative upper bound R_exposed without needing a connection to the lost primary.

Transactional protocol rebase (Design 0029)

Once PostgreSQL finishes physical PITR in maintenance mode (with shared_preload_libraries = '' so the Lease worker does not start prematurely), Design 0029 (prototyped in candidate 1212/v5) runs a single READ COMMITTED transaction (pgetcd-restore restore):

  1. Lock etcd.meta and take a fresh snapshot.
  2. Verify that the restored database’s system identifier and prior logical identity match the exported recovery manifest.
  3. Compute the new baseline revision R_new = max(R_exposed, R_restored) + 1, checking for 64-bit integer overflow.
  4. Copy all live rows from etcd.kv into a complete new baseline generation in etcd.history_anchor.
  5. Set current revision R = R_new, compact revision C = R_new, and history floor F = R_new.
  6. Delete all prior rows in etcd.events, etcd.revision_manifest, and older etcd.history_anchor generations.
  7. Generate fresh cluster_id and member_id values in etcd.meta, while preserving live etcd.kv rows and durable etcd.leases facts.
  8. Write a certification update to etcd.publication_barrier and complete a synchronous COMMIT.

When PostgreSQL restarts with pg_etcd preloaded, the Lease background worker reconstructs surviving Leases with a full TTL under a new owner generation. Clients reconnecting to the gateway observe the new cluster_id and compact_revision = R_new; old Watch cursors below R_new receive an immediate compaction cancellation (compact_revision = R_new), prompting clients (such as kube-apiserver) to relist at R_new and resume watching from R_new + 1.

Prototype verification and remaining work

In single-container Linux amd64 tests on PostgreSQL 18.6 (2026-10-14):

  • Design 0029 (1212/v5, 6/6 PASS): Restored a pg_verifybackup-verified backup to revision 7 after clients had observed revision 10; protocol rebase established baseline revision 11 with new cluster/member IDs, compacted old Watch cursors, reconstructed Leases with full TTL, and delivered the next Watch write at revision 12. Injecting a late constraint failure (SQLSTATE 23514) rolled back all seven tables cleanly.
  • Design 0030 (1216/v4, 8/8 PASS): Recovered after stopping the source PostgreSQL instance using two gateway journals (at bounds 10 and 11), rebasing physical PITR revision 7 to 12, and verified that a full journal tmpfs (ENOSPC) withholds the gRPC response after SQL commit.

Bringing pgetcd-restore and revision journals into a future post-MVP release requires packaging the CLI in the main release tree, automating gateway journal inventory across hosts, and integrating post-restore identity re-enrollment.

9.7 - The frozen native line

The native PostgreSQL wire and runtime accounting work, and why it was frozen.
Note

Condensed from Design 0119 (2026-10-16), Design 0320 (2026-10-26), and Design 0357 (2026-11-08). Over 340 records in the companion repository (0009–0356) belong to this experimental P3 “native” line, which was frozen on 2026-11-08 when the project adopted the MVP goal. The 2026-11-08 status review explains why.

Goal of the native line

After freezing the P0–P2 single-primary candidates on 2026-10-08, the experimental P3 line explored whether a gateway could precharge and bound every byte of memory and I/O before admitting a request—covering PostgreSQL wire frames, TLS handshakes, Go runtime cold start, garbage-collection workers, and Linux kernel task/socket allocations—under a fixed three-part ledger (32 MiB Raw, 15 MiB Work, 32 MiB Backing).

Under that strict rule, native connection admission (Native CLOSED) remained disabled as long as any cold-start, runtime, or kernel resource category had an unproved upper bound (Known0).

Four phases of research (records 0009–0356)

RecordsAreaWhat was built and tested
0009–0026Custom wire and TLS transportFixed-extent Linux TCP socket handling, PostgreSQL SSLRequest framing without plaintext fallback, DER certificate validation, and preallocated TLS record and PostgreSQL StartupMessage / SELECT packet banks
0031–0118Staged capture engineStaged SQL transaction engine (Before probe, Target primary check, application Execute/TailV2, sole COMMIT, and After diagnostic query), preallocated 1,024-slot I/O books, and Patroni readiness/pidfd shutdown polling
0119–0318Custom Go 1.27 runtime accountingCustom Go runtime overlays (ABI V1 through V47) tracking cold-start M0 bootstrap allocations, procresize P/M births, g0/gsignal stack spans, mheap page-table levels, and GC worker nodes
0319–0356Linux kernel resource accountingSource review and isolated guest instrumentation of Debian Linux 6.12.111-1 kernel allocation and retirement paths (alloc_pid, idr_preload, __radix_tree_preload, SLUB caches, and RCU teardown)

Runtime and shared-kernel accounting boundaries

Two findings showed why exact precharge accounting cannot be closed purely inside a gateway process on a standard runtime and OS kernel:

  1. Cold-launch GOMAXPROCS (P) history (Design 0119): The Go runtime does not destroy per-P GC worker goroutines when GOMAXPROCS decreases. In candidate 1464/v1, a process whose P history moved 7 -> 11 -> 5 -> 2 retained 11 worker nodes (5,632 attributed bytes), whereas point observations of the launch setting (7), first GOMAXPROCS return (5), and current P (2) only declared 7. Point observations at startup cannot certify an unobserved intermediate peak.
  2. Shared Linux kernel caches and RCU retirement (Design 0320): Reviewing Debian kernel 6.12.111-1 (1637/kernel-model-v1) showed that alloc_pid calls idr_preload per PID namespace level, and __radix_tree_preload drops its local lock around each allocation while refilling a per-CPU radix-node pool that concurrent nonblocking operations can consume. That preload path strips __GFP_ACCOUNT on a slab cache without SLAB_ACCOUNT, bypassing SLUB memcg charging. On teardown, PID release and task-stack reclamation wait for asynchronous RCU callbacks and per-CPU caches, so wait4() completion and cgroup counter drops do not prove physical page release. Closing that boundary would require a custom kernel ABI outside PostgreSQL and the Go gateway.

Why the native line was frozen (Design 0357)

Because requiring a custom Go runtime overlay and a custom Linux kernel accounting ABI prevented shipping a usable etcd-on-PostgreSQL gateway, Design 0357 froze the entire P3 native line on 2026-11-08:

  • All P3 candidate trees are preserved as research material and are disabled in the default gateway build.
  • The MVP candidates (v0.1.0-rc1, v0.1.0-rc2) build directly from the root Go 1.27.3 source tree and pg_etcd C extension, enforcing request, stream, and revision budgets at the protocol and SQL boundaries while relying on standard PostgreSQL 18 and OS resource management. See Status and Releases.

9.8 - Status review, 2026-11-08

Where pgetcd stood before the MVP decision, why the work did not converge, and what changed.
Note

Review conclusion dated 2026-11-08. It applies to the repository as it stood that morning (one commit, b4f5c72) and records the outcome up to v0.1.0-rc2 (commit 81691bc). The decisions it led to are in the MVP goal.

Question

pgetcd had been in development for about a month and kept testing without closing out. The review asked three things: what the code and tests had actually reached, why the work did not converge, and whether a basic version could be cut.

State at the review

  • The single-primary subset was already accepted. On 2026-10-08 a frozen candidate passed P0 (17 items), P1 (22 groups, including a 1,000,000-call model and Watch audit) and P2 (20 groups, including the selected Kubernetes 1.36.4 / 1.37.1 conformance sets with 446 / 462 cases). It covered KV, Txn, Watch, Lease, logical Compact, MemberList and Status on one PostgreSQL primary.
  • Almost no code was in Git. The repository had one commit (b4f5c72, 2026-10-22), a Go 1.27.3 dependency upgrade with 38 files. About 1,226 files, including the gateway command and the extension, were untracked. A clean checkout of HEAD could not build the gateway.
  • The root tree had drifted from the accepted candidate. It stopped changing in mid-October except for the dependency upgrade. Compared with the frozen P2 gateway sources, 14 of 57 files differed, and the root tree had not been re-verified.
  • P3 had moved away from etcd. P3 started as production HA. It then grew into an own PostgreSQL wire and TLS stack (records 0009–0118), a custom Go 1.27 runtime with byte-level memory accounting (0119–0318), and finally a patched Linux kernel with SLUB and memblock accounting (0319–0356, kernel ABI 148). The rule was that native admission stays closed until every cost category under fixed 32/15/32 MiB budgets is proven, so the target had no reachable end.
  • The root tree still worked. On the review host the gateway built, go test ./... reported 5,164 PASS / 6 FAIL / 39 SKIP (all failures in a P3 source-constraint test), and the Watch and gateway race integration passed 88 tests on a real PostgreSQL 18.6 with the official clientv3 3.6.15 and 3.7.2.
  • Nothing was running. The last test output was from 2026-11-04.

Why the work did not converge

  1. An unbounded completion target. The P3 objective required every runtime, allocator, kernel and physical cost to be proven before HA testing could even begin. Each lower layer exposed new unproven costs.
  2. Full revalidation for every change. Any source change required a new immutable evidence epoch, rebuilds, paired counterexamples, two-site archive readback and bilingual documentation. The project accumulated about 840 P3 evidence epochs, about 215 kernel builds and about 600 companion pages.
  3. Deterministic, self-imposed failures. Most failures were capacity shortfalls against the project’s own budgets, not flaky tests.
  4. Nothing was ever promoted. Candidates lived outside the root tree and the code was not committed, so at no point was there a releasable state.
  5. Environment churn. Cache cleanups removed inputs that the old offline gates needed, so the P2 gate could no longer be reproduced.

Decisions

The user decided on 2026-11-08:

  • Freeze the P3 native line. Stop the own wire and TLS stack, the runtime accounting and the kernel accounting. Keep the candidate trees as research material. See The frozen native line.
  • Make the MVP release candidate the only completion condition. The MVP goal replaces the 0119 completion objective and “P3 OPEN”.
  • Remove defensive testing. Verification must be proportionate to an MVP: no endurance runs, full instrumentation matrices, repeated benchmark rounds, conformance rebuilds or root-cause batches for rare intermittent failures.
  • Keep design records here. pgetcd design documents now live in this section.

Outcome

StepCommitsResult
Commit the codef01c777, 4241ec7, b3d0bd2The root tree is in Git; large test inputs and historical notes stay ignored
Clear the testsff6f7e1, 6486cd1, a7b4206, a8851dd, 7e43446P3-only tests isolated behind the pgetcd_p3 build tag, a watchdog test race fixed, go vet clean on macOS and Linux
v0.1.0-rc12b36cba, tag on 250df4cRegression on 7e43446: all items passed except etcdctl endpoint health; benchmarks exposed the gateway withdrawing readiness under load
v0.1.0-rc2fad4d2f, db0577b, 81691bcReadiness check on a reserved slot, client requests queue up to 5 s, readiness changes logged, Alarm list query added; lean verification passed with 50/50 etcdctl probes and 0 refused requests at 128 clients

Status lists the remaining known issues of v0.1.0-rc2, including Watch delay under sustained heavy writes.

9.9 - MVP goal (v0.1.0)

The approved MVP scope, the lean release checklist and the verification rule for pgetcd v0.1.0.
Note

Approved by the user on 2026-11-08. It replaces the 0119 completion objective and “P3 OPEN” as the current completion condition, and applies to the v0.1.0-rcN candidates; the current one is v0.1.0-rc2 (commit 81691bc). Distilled from companion record 0357, which is kept as history and no longer updated. The 2026-11-08 status review explains why the goal changed.

Completion condition

The only current completion condition is the MVP release candidate v0.1.0-rcN. When it is reached, stop and report to the user; do not start a later phase automatically. The 0119 objective and P3 remain as material for later decisions.

Shared principles

pgredis, pgetcd and pgsilo use the same principles.

  • Scope freeze. Do only the listed work items and fixes for problems that block the MVP. Do not add features, test tiers, evidence formats or infrastructure.
  • Records. At most one short work log per working day. Status pages state the current state and known issues, not a running diary.
  • Authorization. Push, remote creation, package or image publication and site deployment each need separate user authorization. Local branch commits are allowed.
  • Performance. Publish measured baseline numbers and the test environment. There is no SLA, and performance does not block the release.

Verification

Keep verification proportionate to an MVP: run only functional and smoke tests that finish within minutes, and finish the whole release checklist within one or two hours. Do not run the following, and do not list them as post-MVP gates: long stability or endurance runs, full instrumentation matrices, repeated benchmark rounds, conformance tests that need a large external environment rebuilt, and diagnostic batches that chase the root cause of rare intermittent problems. If one is needed later, the user asks for it separately.

  • Run the checklist once on the frozen candidate; during development run only the items a change affects. Record each item as pass, fail or not applicable, with the command and where the raw output is kept.
  • Fix each failure, or list it as a known issue and state whether it blocks the release; the user decides.
  • Dropped: dual independent review, full revalidation because “older results do not certify changed source bytes”, immutable evidence epochs, paired counterexamples, two-site archive readback and tests of the test infrastructure.
  • Kept: no hidden or silently waived failures, and the correctness invariants: publish a response only after synchronous COMMIT succeeds, never replay an unknown COMMIT, keep the permission boundaries. A result belongs only to the candidate that produced it.

Scope

Supported in v0.1.0:

  • One PostgreSQL 18 primary; one gateway process per tenant; clients connect with mTLS.
  • The API accepted in P2: Range, Put, DeleteRange, Txn, Compact (logical only), LeaseGrant, LeaseRevoke, LeaseTimeToLive, LeaseLeases, LeaseKeepAlive, Watch, MemberList and Status. From v0.1.0-rc2 the Alarm list query is also supported, so etcdctl endpoint health works.

The P2 results belong to the frozen candidate of 2026-10-08 and only define the API scope; each release candidate runs its own checklist.

Target use cases:

  • Applications that use the etcd Go clientv3 or etcdctl.
  • Kubernetes apiserver storage for small clusters or development and test clusters.

Not supported:

  • HA semantics. After a PostgreSQL primary switchover, the operator restarts the gateway. There is no fencing and no response-consistency promise during the switchover.
  • Other RPCs. RangeStream, physical Compact, Auth/RBAC, membership changes, other Maintenance RPCs (Snapshot, Defragment, Hash, alarm activation) and Lock/Election.
  • An HTTP/JSON gateway, and therefore Patroni. Patroni’s etcd3 client uses the HTTP/JSON gateway. This moves to MVP+1. When pgetcd later serves as a Patroni DCS, a different PostgreSQL cluster must host it: a Patroni cluster that hosts its own DCS creates a circular dependency during failover.
  • Replica reads, more than 8 tenant databases per PostgreSQL instance, in-place upgrade migration and performance SLAs.

Work items

ItemOutcome
Freeze the P3 native line; keep its candidate trees as research materialDone; see The frozen native line
Commit the root source; a clean checkout must build the gateway and extension and pass the unit testsDone (f01c777, 4241ec7, b3d0bd2)
Clear go test and go vet; isolate P3-only tests; confirm the default gateway path does not enable P3 componentsDone (ff6f7e1 through 7e43446)
Use the root Go 1.27.3 source as the release baseline and run the checklist on LinuxDone for v0.1.0-rc1 and v0.1.0-rc2
Version 0.1.0, Linux amd64/arm64 gateway and PostgreSQL 18 extension archives, scope page, local tagDone; v0.1.0-rc2 on 81691bc

Release checklist

ItemContent
Go build and checksgo build ./cmd/..., go test ./..., go vet ./...
ExtensionExtension build and SQL test suites
Watch and gatewayWatch/gateway race integration tests on a real PostgreSQL server
Official clientsetcd 3.6 and 3.7 official client probes
Primary switchover smokePromote a new primary manually, restart the gateway, then confirm that clients reconnect and committed data is intact; this checks the operating requirement only
PerformanceOne set of basic numbers, run once and recorded only

The P1 mixed model audit (100,000 calls) passed on v0.1.0-rc1 and is no longer required. Kubernetes conformance is outside the MVP verification scope; the upstream k8s.io/apiserver storage probe passed 65 tests each for 1.36 and 1.37 on v0.1.0-rc1 and serves as a reference.

Deferred

  • HA support: define its scope and verification when it is needed.
  • HTTP/JSON gateway and Patroni validation (MVP+1).
  • RangeStream and other unimplemented RPCs.
  • A dedicated security review.
  • The shared Mimus runtime.