Contents
Architecture, Safety & Verification
Design Philosophy
pgbreaker puts only the minimal fast-fail primitives inside PostgreSQL that cannot be replicated cleanly outside the kernel: integer-key concurrency control/tripping and lock-free GCRA QPS limiting for PostgreSQL 14–18. Policy orchestration, SQL auditing, queueing, and cluster-wide rule distribution stay external.
Two-Layer Module Seam
+-----------------------------------------------------------------------+
| PostgreSQL Backend Warm Hot Path (zero LWLock, zero palloc, no strings)|
| src/pg/pgb_hooks.c --> PgbLocalSnapshot (epoch-synced) |
| | | |
| v v |
| src/core/ (ZERO postgres.h dependency) |
| - pgb_matcher.c : present_mask + expected O(1) hash lookup |
| - pgb_limiter.c : eval_state pin + packed CAS & 64-bit GCRA CAS |
| - pgb_ledger.c : fixed 32-level per-backend slot stack |
+-----------------------------------------------------------------------+
| ^
single-word atomic CAS epoch refresh / startup
v |
+-----------------------------------------------------------------------+
| Fixed Preallocated Shared Memory (< 256 KB @ max_rules = 1024, 64B CL)|
| src/pg/pgb_shmem.c : PgbShmemHeader + PgbRuleSlot[max_rules] |
| src/pg/pgb_api.c : 5 SQL functions + 2 SRFs (decoupled I/O locks) |
| Disk persistence : $PGDATA/pg_stat/pgbreaker.rules (v1, CRC32C) |
+-----------------------------------------------------------------------+
| Layer | Files | Responsibilities |
|---|---|---|
Core engine (src/core/) |
pgb_atomic.h, pgb_core.h, pgb_matcher.c, pgb_limiter.c, pgb_ledger.c |
Pure C99/C11 with zero postgres.h dependency. Compiles standalone under ASan, UBSan, and TSan (-DPGB_USE_PG_ATOMICS switches atomics to PG port/atomics.h with pg_memory_barrier() acquire/release semantics for weakly-ordered CPUs such as ARM64). Enforces GCC/Clang alignment (PGB_ALIGNAS) and native 64-bit atomics at compile time (PGB_CACHELINE_SIZE defaults to 64 B, overrideable for 128 B architectures). |
PG adapter (src/pg/) |
pgb_pg.h, pgb_shmem.c, pgb_hooks.c, pgb_api.c |
PG 14–18 compatibility macros, fixed shared memory, backend-local snapshot refresh, executor/xact/subxact/log/exit hooks, atomic file persistence, and SQL API. |
Lock-Free Hot Path Internals
- Empty / Disabled Fast-Path:
ExecutorStartmaintains balancedpgb_nesting_levelunconditionally across all four executor hooks (ExecutorStart/ExecutorRun/ExecutorFinish/ExecutorEnd), then checkspgb_enabledand performs a single relaxed atomic load ofrule_count. When disabled or zero rules are configured, enforcement is skipped immediately. - Epoch-Driven Local Snapshot: each backend keeps a read-only
PgbLocalSnapshotallocated once inTopMemoryContext. In steady state (cached_epoch == rule_epoch), zeroLWLocks are acquired and lookups take expected O(1) time in the local open-addressing hash table filtered bypresent_mask. A snapshot rebuild acquirespgb_shmem->lock(LW_SHARED) briefly once after a control-plane mutation bumpsrule_epoch, skips any retired slot (!in_useorPGB_EVAL_RETIRED_BIT), and returnsfalse(clearingcached_epoch) rather than marking a truncated snapshot current; diskfsyncruns under a separatepersist_lockso I/O never blocks hot-path refreshes or emergency trips. - Cacheline Isolation, Quiescent Slot Pinning & ABA-Free Concurrency CAS: each
PgbRuleSlotis compile-time verified at2 * PGB_CACHELINE_SIZE(128 bytes on 64B cachelines), separating read-mostly metadata on cacheline 0 from hot atomics on cacheline 1:eval_statepacks(gen_tag << 32) | retired_bit | eval_pinsinto one 64-bit atomic word. Bothpgb_try_acquire()andpgb_release()pineval_stateacross 64-bitrule_genvalidation,active_stateCAS, GCRA, and telemetry updates, and unpin before returning. Retired slots (pgb_slot_retireclearsin_use = falseand setsretired_bit) are only reactivated once quiescent (retired && eval_pins == 0), preventing stale evaluators or delayed releases from touching a replacement rule’s counters,active_state, or GCRA state (unconditionally ABA-free).active_statepacks((uint32_t)rule_gen << 32) | active_countinto one 64-bit atomic word for single-word atomic CAS validation and saturating decrement.- Single-RMW decision telemetry: each decision increments exactly one mutually exclusive counter (
allows_total,rejects_total, orshadows_total), avoiding double atomic writes on reject/shadow paths;pgb_slot_read_stats()computeshits_total = allows + rejects + shadowsfrom one load per counter sorules_viewalways reportshits_total >= rejects_total + shadows_totaleven acrossreset_stats().
- Single-Word CAS GCRA QPS Limiter:
CLOCK_MONOTONICis read only when the matched rule setsmax_qps > 0(or on rejection whenpgbreaker.log_rejects = on). Pure concurrency/trip rules issue zero clock syscalls on normal execution. GCRA uses conservative ceiling intervals (ceil(1e9 / max_qps)ns), never rewindsgcra_tat_nson stale/delayed samples, fails closed if timestamp arithmetic would overflowUINT64_MAX, fails open ifclock_gettimeitself fails, and immediately rolls back any acquired concurrency slot (via internalpgb_release_pinned) on GCRA reject. - Fixed 32-Level Slot Ledger: every acquired concurrency lease is recorded in the backend’s
PgbSlotLedgerwith(slot_idx, rule_gen, subxid, cookie)wherecookie = (uintptr_t)queryDesc. If the 32-entry ledger is full, enforced concurrency rules fail closed with53P01(reason=concurrency_limit) while shadow mode skips slot acquisition cleanly. Leases unwind deterministically across:- Normal completion:
ExecutorEnd_hook(cookie-matched pop, cursor-safe). - Startup / execution / finish error:
PG_CATCHinExecutorStart_hook,ExecutorRun_hook, andExecutorFinish_hook(releases failed parent cursors inside child savepoints immediately). - Query error /
statement_timeout/pg_cancel_backend:RegisterXactCallback(XACT_EVENT_ABORT,COMMIT,PREPARE). SAVEPOINTrollback / commit:RegisterSubXactCallback(SUBXACT_EVENT_ABORT_SUBdrains aborted subxact entries;SUBXACT_EVENT_COMMIT_SUBreparents entries to parent subxid).pg_terminate_backend/ backend exit: lazily registeredbefore_shmem_exitdrains all remaining slots.
- Normal completion:
Node-Local Atomic Persistence
pgbreaker requires no Background Worker, no SPI, and no catalog tables:
- Control-plane rule mutators (
trip,set_rule,remove_rule,clear_rules) publish changes into shared memory immediately underlock(LW_EXCLUSIVE), then flush underpersist_lockvia interruptibleLWLockConditionalAcquirepolling so slow disk I/O never stalls emergency rule publication. - Persistence writes a host-endian v1 file: a 20-byte
PgbPersistHeader(magic0x50474252, format version1,rule_count,next_rule_id,pg_crc32c) plus 40-bytePgbPersistRulerecords to a unique temp file ($PGDATA/pg_stat/pgbreaker.rules.tmp.<pid>.<seq>, openedO_CREAT | O_EXCL | O_NOFOLLOW), flushed withpg_fsync, swapped via direct atomicrename()+ parent directoryfsync(honoring PostgreSQL’sfsyncGUC). shmem_startup_hookcleans up stalepgbreaker.rules.tmp.*temp files, opens the state file withO_RDONLY | O_NONBLOCK | O_NOFOLLOWand checksS_ISREGbefore reading, validating CRC32C and checking duplicaterule_id/key entries in $O(N \log N)$ time.- Missing files (
ENOENT) boot silently with0rules; non-regular, unreadable, truncated, corrupt, or incompatible files emit aWARNINGand boot with0rules (Fail-Open). Loweredmax_rulesloads the firstmax_rulesentries, setsstatus.persisted = false, and preserves the oversized file on disk untilclear_rules().
Safety Invariants
- No self-lock: exempts effective
superuser(), roles inheritingpg_use_reserved_connections(PG 16+, cached withAUTHOID/AUTHMEMMEMROLE/AUTHMEMROLEMEMsyscache invalidation),IsParallelWorker(),EXEC_FLAG_EXPLAIN_ONLY, bootstrap mode, nested executor statements (nesting_level > 0), andProcessUtilitywork that does not invoke the executor (VACUUM,ANALYZE, DDL).pgbreaker.enabled = off(SIGHUP) provides hot bypass. - Zero slot leaks: multi-exit unwinding (
ExecutorStart/Run/FinishPG_CATCH,ExecutorEnd, xact/subxact callbacks,before_shmem_exit) witheval_statepinning,rule_genvalidation, and saturating decrement. - Fail-Open startup & bounded server logs: corrupt/missing state files never block PostgreSQL startup;
emit_log_hooksuppresses raw53P01server error spam (0extension lines whenlog_rejects = off, atomically capped at10LOGlines/sec via single 64-bit monotonic CAS whenon). - Standby-safe control plane: node-local shmem + file persistence lets read-only standbys run
trip()/set_rule()locally without touching the primary (pg_basebackupcopies the persisted file in$PGDATA/pg_stat/as the standby’s initial seed, after which nodes diverge independently). - Control-plane discipline: schema-hijack install guard, least-privilege SQL grants (
REVOKE ALL FROM PUBLIC,pg_read_all_statsfor views), C-levelsuperuser()enforcement on all mutators, andreset_stats()preservingactive_count.
Explicit Non-Goals
| Out of Scope | Recommended Layer / Alternative |
|---|---|
| SQL auditing, injection firewall, DDL guards | pg-safeupdate, pg_savior, SQL gateway |
Regex, SQL text, table-name, or application_name matching |
ProxySQL, PgDog, application middleware |
| In-backend wait queues | PgBouncer, Odyssey (queuing in PG holds max_connections & xmin) |
| Cross-node rule replication | Patroni, Ansible, external control plane |
| Adaptive heuristics, business priority scoring & TTL scheduling | External orchestrator / pg_cron |
| Connection storm protection | PgBouncer, Odyssey |
Static planner cost filtering (max_cost) |
pg_plan_filter |
Testing & Verification
Running the Suites
# Standalone core suite (no PostgreSQL required):
# C99 & C11 Clang ASan+UBSan, C99 & C11 Clang TSan (64-thread stress), and GCC -O2 Release
make test-core
# End-to-end PostgreSQL integration, chaos, hot standby & pgbench suite
make && sudo make install
make test-pg # full suite including pgbench (12 suites)
SKIP_BENCH=1 make test-pg # fast CI mode (11 suites, ~16s)
Override compilers or pg_config as needed:
make SAN_CC=clang CORE_CC=gcc test-core
make PG_CONFIG=/usr/pgsql-16/bin/pg_config && sudo make PG_CONFIG=/usr/pgsql-16/bin/pg_config install
Verified Test Matrix (v0.1.0)
- Core engine (
tests/core/test_pgb_core.c): 17/17 suites across 5 standalone builds (C99 & C11 Clang ASan+UBSan, C99 & C11 Clang TSan with 64-worker + control-plane churner stress, livepgb_try_acquire+ deterministiceval_statepin rendezvous, per-windowpgb_log_rate_alloworacle, GCRA stale-timestamp /!clock_okpreservation / overflow checks, subxact & full drains, duplicate-release probes, and GCC-O2Release) —0warnings,0leaks,0data races. - PostgreSQL 14–18 CI & Integration Suite (
tests/pg/run_pg_tests.sh): Unix-socket-only isolated primary + hot-standby clusters running with defaultcompute_query_id = 'auto'(verifyingEnableQueryId()):- Control API (
CREATE EXTENSION pgbreakerunder restrictive default privileges, schema-hijack rejection includingCREATE DOMAIN,trip,trip(0)22023,set_rulelive upsert & explicit-NULL22023, non-transactionalROLLBACK,remove_rule,clear_rules,reset_statspreserving liveactive_count,rules&statusviews includingpersisted, dropped-roleNULL, and un-preloaded55000errors) - Enforcement (
SQLSTATE 53P01+DETAIL) vs per-rule &SIGHUPglobalshadow, andemit_log_hookserver-log suppression (0lines whenoff,<= 10LOGlines/window whenon, without suppressing unrelated user53P01errors) SIGHUPemergency bypass (pgbreaker.enabled = off / on)- Effective-role enforcement (
SET ROLE, PG 16+pg_use_reserved_connectionsincludingWITH INHERIT FALSEand liveGRANT/REVOKE),EXPLAIN-only, real parallel workers (Workers Launched >= 1, leaderhits_total = 1), direct ACL &pg_read_all_statsvspg_monitorpersist_pathisolation, C-levelsuperuser()auth, and(q,d,r) > (q,0,0)precedence - Concurrency enforcement (
max_concurrency = 2with deterministic advisory-lock barriers and boundedlock_timeoutprobes,active_count = 0) - Zero-leak chaos: pooled-connection checks after
ERROR/statement_timeout/pg_cancel_backend,pg_terminate_backend(57P01),SAVEPOINT/ROLLBACK TO SAVEPOINT/RELEASE SAVEPOINT,WITH HOLDcursors,NO SCROLLbackward-fetch portal cleanup, returnedrefcursordeferred admission,SCROLL+MOVE ABSOLUTE 0rewind safety, out-of-order multi-cursor close, failing parent cursor inside child savepoint with sibling cursor live, 32-cursor ledger-full53P01rejection, mid-flight rule added during running PL/pgSQL function, depth-6 recursion +EXCEPTION, mid-flightrule_genbump with active replacement holder (allactive_count == 0) - Wire Extended Query Protocol (
PQexecParams) &PREPARE/EXECUTEcached generic plan interception across PG 14–18 - GCRA QPS rate limiting (burst, cap, elapsed-time admission bounds, phase-2 delta, combined concurrency rollback
active_count == 0) - Restart & immediate-crash persistence,
status.persistedfailure/retry + crash verification, atomic FIFO replacement, startup orphan.tmp.*cleanup, loweredmax_rulespreservation untilclear_rules(), concurrent mutator convergence, and CRC32C-corrupt/truncated fail-open recovery (preserving corrupt disk files across no-op calls) - Read-only hot standby (
pg_basebackupseed identity + live WAL streaming over Unix sockets + local standbytrip()isolated from primary + standby restart persistence) pg_stat_statementsbidirectional co-loading ('pg_stat_statements,pgbreaker'and'pgbreaker,pg_stat_statements'): bit-for-bitqueryidparity, concurrency &trip()enforcement, accuratepg_stat_statements.callsaccounting, and0slot leaks
- Control API (
Micro-Benchmark (pgbench)
Measured on PostgreSQL 16.16 (Rocky Linux 9.8 x86_64) via pgbench -S -M prepared -c 8 -j 4 -T 10 as a non-superuser (2 s warmup + 10 s timed):
| Scenario | Throughput (TPS) | Avg Latency | Observed Delta |
|---|---|---|---|
Vanilla PostgreSQL (compute_query_id = on) |
134,252.0 | 0.060 ms | baseline |
pgbreaker loaded, 0 rules (fast-path) |
138,676.8 | 0.058 ms | +3.30% |
pgbreaker loaded, 100 non-matching rules |
139,701.6 | 0.057 ms | +4.06% |
pgbreaker loaded, 100 rules + 1 matching concurrency rule (1,718,920 warmup+timed hits, 0 leaks) |
143,981.5 | 0.056 ms | +7.25% |
pgbreaker loaded, 100 rules + 1 matching GCRA QPS rule (1,640,730 warmup+timed hits) |
136,597.0 | 0.059 ms | +1.75% |
On this single-host 10-second run (~134k–144k TPS), observed throughput across loaded scenarios ranged from +1.75% to +7.25% relative to vanilla PostgreSQL, with 0 leaked slots across all matched executions.