Skip to content

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

Return to the regular view of this page

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.

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.

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.