pgbreaker
A minimal, lock-free circuit breaker and SQL concurrency/QPS limiter for PostgreSQL 14–18, written in Pure C99 + PGXS.
- Instant circuit breaking & rate limiting: cap concurrency (
0for immediate fast-fail) or smooth QPS (GCRA) by integer(query_id, db, role)across Simple, Extended, andPREPARE/EXECUTEqueries. - Lock-free steady-state hot path: zero
LWLocks, zeropalloc, and zero string ops once warmed, with zero clock reads for concurrency-only rules (excluding logged rejections whenpgbreaker.log_rejects = on). - Built-in lockout safety: effective superusers, roles inheriting
pg_use_reserved_connections(PG 16+), parallel workers,EXPLAIN-only runs, nested executor queries, and utility/maintenance commands that do not invoke the executor (VACUUM,ANALYZE, DDL) are exempt, withSIGHUPbypass (pgbreaker.enabled = off). - Restart & hot-standby ready: rules persist atomically to
$PGDATA/pg_stat/pgbreaker.ruleswith zero Background Worker, zero SPI, and zero catalog writes—enabling localtrip()directly on read-only standbys.
Installation
Requires PostgreSQL 14–18 server development headers (postgresql-server-devel or postgresql-server-dev-*) and GCC or Clang.
git clone https://github.com/cwj2001/pgbreaker.git
cd pgbreaker
make && sudo make install
# With a custom pg_config path:
# make PG_CONFIG=/usr/pgsql-16/bin/pg_config && sudo make PG_CONFIG=/usr/pgsql-16/bin/pg_config install
Enable in postgresql.conf and restart PostgreSQL (pgbreaker calls EnableQueryId(), works with PostgreSQL’s default compute_query_id = 'auto', and co-loads cleanly with pg_stat_statements in either load order):
shared_preload_libraries = 'pgbreaker'
Create the extension in any database (rules live in shared memory and apply instance-wide across all databases):
CREATE EXTENSION pgbreaker;
Quickstart
-- 1. Locate a runaway query_id from pg_stat_activity (or pg_stat_statements)
SELECT pid, query_id, left(query, 80)
FROM pg_stat_activity
WHERE state = 'active' AND query_id IS NOT NULL;
-- 2. Trip a persistent circuit breaker for subsequent executions (non-zero query_id).
-- Note: trip() enforces at ExecutorStart and does not cancel an already-running
-- query or auto-expire; use pg_cancel_backend(pid) for in-flight queries and
-- remove_rule(rule_id) when ready to re-enable.
SELECT pgbreaker.trip(query_id => -4829103847129384) AS rule_id;
-- Later, disarm the rule:
SELECT pgbreaker.remove_rule(rule_id => 1);
-- 3. Shadow-first rollout: observe would-be rejections before enforcing caps
SELECT pgbreaker.set_rule(
query_id => 771829301293847,
db_name => 'appdb', -- NULL = all databases
role_name => 'app_ro', -- NULL = all roles
max_concurrency => 20, -- -1 unlimited, 0 trip, >0 max concurrent
max_qps => 500, -- -1 unlimited, 1..1000000000 QPS limit
burst => 50,
shadow => true -- flip to false when ready to enforce
);
-- Inspect active rules and live status (superuser or pg_read_all_stats)
SELECT * FROM pgbreaker.rules;
SELECT * FROM pgbreaker.status;
-- 4. Emergency hot bypass without restart (SIGHUP)
ALTER SYSTEM SET pgbreaker.enabled = off;
SELECT pg_reload_conf();
Rejected queries fail fast with Class 53 SQLSTATE 53P01:
ERROR: 53P01: pgbreaker: query rejected by circuit breaker
DETAIL: pgbreaker rule_id=1 reason=concurrency_limit query_id=-4829103847129384 db_oid=16384 role_oid=16385
SQL & GUC Summary
- Control functions (superuser-only, non-transactional):
pgbreaker.trip(query_id),pgbreaker.set_rule(...),pgbreaker.remove_rule(rule_id),pgbreaker.clear_rules(),pgbreaker.reset_stats(). - Observability views (granted to
pg_read_all_stats, notPUBLIC):pgbreaker.rules(definitions + liveactive_count,hits_total,rejects_total,shadows_total) andpgbreaker.status(runtime flags,rule_epoch,rule_count,persist_path,persisted). - GUCs:
pgbreaker.enabled(on, SIGHUP),pgbreaker.shadow(off, SIGHUP),pgbreaker.max_rules(1024, POSTMASTER),pgbreaker.log_rejects(off, SIGHUP).
See docs/reference.md for complete signatures, privilege rules, matching precedence, SQLSTATE 53P01 details, and operational playbooks.
Performance
Measured on PostgreSQL 16.16 (Rocky Linux 9.8 x86_64) via pgbench -S -M prepared -c 8 -j 4 -T 10 (non-superuser, 2 s warmup + 10 s timed):
| Scenario | Throughput (TPS) | Avg Latency | Observed Delta |
|---|---|---|---|
Vanilla PostgreSQL (compute_query_id = on) |
134,252 | 0.060 ms | baseline |
pgbreaker loaded, 0 rules (fast-path) |
138,677 | 0.058 ms | +3.3% |
pgbreaker loaded, 100 rules + concurrency match |
143,982 | 0.056 ms | +7.2% |
pgbreaker loaded, 100 rules + GCRA QPS match |
136,597 | 0.059 ms | +1.7% |
On this single-host 10-second run (~134k–144k TPS), observed throughput across loaded scenarios ranged from +1.7% to +7.2% relative to vanilla PostgreSQL, with 0 leaked slots across 1.72M cumulative matched executions (warmup + timed). See docs/architecture.md for internals and full test/benchmark details.
Documentation
- SQL, GUC & Operations Reference — full API signatures, matching precedence, error codes, and operational playbooks.
- Architecture, Safety & Verification — lock-free engine design, safety invariants, non-goals, and test suites.
- 30-Second Chaos Demo — reproducible Docker Compose demo showing live
pgbreaker.trip()recovery under connection starvation.
License
Released under the PostgreSQL License.