Contents
SQL, GUC & Operations Reference
This document covers the complete pgbreaker v0.1.0 SQL API, GUC configuration, privilege model, deterministic rule matching, rejection error format, and operational runbooks for PostgreSQL 14–18.
Configuration (4 GUCs)
| GUC | Default | Range / Type | Context | Description |
|---|---|---|---|---|
pgbreaker.enabled |
on |
bool |
PGC_SIGHUP |
Master hot bypass switch. When off, executor enforcement is bypassed immediately after a single check. |
pgbreaker.shadow |
off |
bool |
PGC_SIGHUP |
Global shadow mode. Counts would-be rejections in shadows_total and tracks live active_count for concurrency rules without rejecting queries. |
pgbreaker.max_rules |
1024 |
16..16384 |
PGC_POSTMASTER |
Preallocated shared-memory rule slot capacity (< 256 KB at default 1024 with 64-byte cachelines). |
pgbreaker.log_rejects |
off |
bool |
PGC_SIGHUP |
Emit server LOG lines on rejection, atomically rate-limited to 10 lines/second instance-wide. When off, emit_log_hook suppresses raw 53P01 error server logs (0 extension server lines). |
Query ID note:
_PG_initcallsEnableQueryId(), so PostgreSQL’s defaultcompute_query_id = 'auto'enablesquery_idgeneration automatically. Settingcompute_query_id = 'on'explicitly is also supported. Across PostgreSQL 14–18, parameterized queries ($1Paramnodes viaPREPAREor Extended Query Protocol) can produce a differentquery_idthan queries with literal constants (Constnodes such asWHERE id = 1); always obtain the exactquery_idfrompg_stat_activity,pg_stat_statements, orEXPLAIN (VERBOSE) EXECUTE ....
SQL Functions (5 Control Functions)
All objects live in the non-relocatable pgbreaker schema.
Non-transactional semantics: All 5 control functions mutate instance-wide shared memory immediately (
trip,set_rule,remove_rule, andclear_rulespersist to disk immediately;reset_statsis memory-only). Mutations do not roll back onROLLBACKorROLLBACK TO SAVEPOINT.
pgbreaker.trip
pgbreaker.trip(query_id bigint) RETURNS integer
Installs a persistent circuit breaker rule for subsequent ExecutorStart calls: upserts (query_id, 0, 0) with max_concurrency = 0, max_qps = -1, burst = 0, shadow = false, persists atomically, and returns rule_id. Does not cancel an already-running query (use pg_cancel_backend(pid)) and does not auto-expire (disarm with pgbreaker.remove_rule(rule_id)). Rejects NULL and 0 with 22023 to prevent accidental instance-wide blackouts (use pgbreaker.set_rule(query_id => 0, max_concurrency => 0) if you intentionally want an instance-wide wildcard trip).
pgbreaker.set_rule
pgbreaker.set_rule(
query_id bigint DEFAULT 0,
db_name text DEFAULT NULL,
role_name text DEFAULT NULL,
max_concurrency integer DEFAULT -1,
max_qps integer DEFAULT -1,
burst integer DEFAULT 0,
shadow boolean DEFAULT false
) RETURNS integer
Idempotent upsert keyed on (query_id, db_oid, role_oid) (db_name and role_name are lookup inputs resolved to OIDs):
- Wildcard & NULL handling:
NULLis valid only fordb_nameandrole_name(mapping to wildcard OID0; non-null names resolve viaget_database_oid/get_role_oid). Passing explicit SQLNULLforquery_id,max_concurrency,max_qps,burst, orshadowraises22023(invalid_parameter_value).query_id = 0matches any query ID. max_concurrency:-1= unlimited,0= instant trip (reject all non-exempt executions),> 0= maximum concurrent executions.max_qps:-1= unlimited, or1..1000000000(1B QPS cap) enforced via smooth GCRA with conservative ceiling emission intervalceil(1e9 / max_qps)ns.burst: token burst tolerance formax_qps > 0.0(default) usesmax(1, max_qps / 10); negative values raise22023.shadow: whentrue, would-be rejections incrementshadows_totalwithout rejecting the query.- Allow-override / hit-counting rules: leaving both
max_concurrency = -1andmax_qps = -1is valid and creates a hit-counting or allow-override rule (useful with matching precedence to exempt a specific(db, role)from a broadertrip()or wildcard cap). - Live upsert preservation: calling
set_rule()with identical(max_concurrency, max_qps, effective burst, shadow)on an existing key is a true no-op (retrying disk persistence only ifpersisted = false). Changing limits orshadowon an existing key updates the rule in place without bumpingrule_genor resetting liveactive_countor GCRA debt. Returnsrule_id.
pgbreaker.remove_rule
pgbreaker.remove_rule(rule_id integer) RETURNS boolean
Retires the slot matching rule_id, bumps rule_gen and rule_epoch, persists atomically, and returns true if removed (false if not found; still retries dirty disk persistence if persisted = false). Rejects explicit NULL with 22023 (or 55000 when unpreloaded).
pgbreaker.clear_rules
pgbreaker.clear_rules() RETURNS integer
Retires all active rules, clears any max_rules-truncation persistence pause, bumps rule_epoch, persists a clean empty file atomically, and returns the number of rules cleared.
pgbreaker.reset_stats
pgbreaker.reset_stats() RETURNS void
Resets cumulative counters (hits_total, rejects_total, shadows_total) to zero across all active rules in shared memory (memory-only; does not write to disk). Never modifies live active_count.
Observability Views (2 Views)
pgbreaker.rules
Returns one row per active rule (backed by pgbreaker.rules_view()):
| Column | Type | Description |
|---|---|---|
rule_id |
integer |
Unique rule identifier. |
query_id |
bigint |
Target query_id (0 = wildcard). |
db_oid |
oid |
Target database OID (0 = wildcard). |
db_name |
text |
Resolved database name (NULL if wildcard or dropped database). |
role_oid |
oid |
Target role OID (0 = wildcard). |
role_name |
text |
Resolved role name (NULL if wildcard or dropped role). |
max_concurrency |
integer |
-1 unlimited, 0 trip, > 0 concurrency cap. |
max_qps |
integer |
-1 unlimited, 1..1000000000 QPS cap. |
burst |
integer |
Effective GCRA burst tolerance. |
shadow |
boolean |
Per-rule shadow flag. |
active_count |
integer |
Live concurrency leases currently held (ExecutorStart acquire through ExecutorEnd / abort release). Includes open cursors (WITH HOLD cursors release their lease at COMMIT when their executor ends) and shadow concurrency rules. Editing an active rule’s max_concurrency to -1 stops new acquisitions while live holders drain naturally to 0; pure QPS-only rules never acquire a lease. |
hits_total |
bigint |
Cumulative decisions (allows + rejects + shadows). |
rejects_total |
bigint |
Cumulative enforced rejections. |
shadows_total |
bigint |
Cumulative shadow-mode would-be rejections. |
pgbreaker.status
Returns a single consistent snapshot row (backed by pgbreaker.status_view()):
| Column | Type | Description |
|---|---|---|
enabled |
boolean |
Current pgbreaker.enabled value. |
shadow |
boolean |
Current pgbreaker.shadow value. |
log_rejects |
boolean |
Current pgbreaker.log_rejects value. |
rule_epoch |
bigint |
Monotonic in-memory mutation counter for the current shared-memory lifecycle (resets on PostgreSQL restart). |
rule_count |
integer |
Number of active rules in shared memory. |
max_rules |
integer |
Configured pgbreaker.max_rules capacity. |
persist_path |
text |
Among callers authorized to read pgbreaker.status (superusers and pg_read_all_stats members), pg_read_all_settings controls path redaction: superusers and roles holding pg_read_all_settings (such as pg_monitor) receive the full $PGDATA/pg_stat/pgbreaker.rules path; pg_read_all_stats-only callers receive the relative path pg_stat/pgbreaker.rules. |
persisted |
boolean |
true when the latest rule_epoch was saved successfully under PostgreSQL’s configured durability policy (honoring fsync) and persistence is not paused due to lowered max_rules. |
Privilege Model & Preload Requirement
- Preload requirement: all 5 functions and both views (
pgbreaker.rules,pgbreaker.status) requireshared_preload_libraries = 'pgbreaker'and raiseERROR 55000: pgbreaker must be loaded via shared_preload_librariesif invoked without preloading (including whenNULLis passed totrip()orremove_rule()). - Schema install safety:
CREATE EXTENSION pgbreakerverifies that schemapgbreakeris owned by a superuser, has no non-superuserCREATEprivileges (direct or inherited), and contains no pre-existing relations, functions, or types. - Zero
PUBLICprivileges: schemapgbreaker, all 5 mutating functions, both backing SRFs (rules_view(),status_view()), and both views (rules,status) have all privileges revoked fromPUBLIC. - Mutating control functions: enforce
if (!superuser())in C in addition to SQLREVOKE ALL FROM PUBLIC. Even ifGRANT EXECUTEis issued manually, non-superusers cannot mutate rules. - Monitoring access:
USAGEon schemapgbreaker,EXECUTEonrules_view()/status_view(), andSELECTonrules/statusare explicitly granted topg_read_all_stats(whichpg_monitorinherits). This works even whenALTER DEFAULT PRIVILEGES REVOKE EXECUTE ON FUNCTIONS FROM PUBLICis configured.
Statement Scope & Exemptions
- Executor-only scope (
ProcessUtilityexclusion):pgbreakerattaches to PostgreSQL executor hooks (ExecutorStart/ExecutorRun/ExecutorFinish/ExecutorEnd). Utility work that does not start an executor (such asVACUUM,ANALYZE,CREATE INDEX, standard DDL, and plainCOPY tablewithout RLS) is excluded so maintenance and recovery are not blocked. Any statement—including utility commands that invoke the executor such asCOPY (SELECT ...),COPY table TOunder Row-Level Security,CREATE TABLE AS,REFRESH MATERIALIZED VIEW, and SQL executed inside DDL event triggers—passes throughExecutorStartat nesting level0. - Nesting semantics (
DO/CALLvs nested functions):pgb_nesting_levelis balanced unconditionally across all four executor hooks regardless of whetherpgbreaker.enabledorrule_countchanged mid-execution. Statements nested inside an active top-level executor query (SQL/PLpgSQL functions invoked bySELECT, triggers) seenesting_level > 0and are exempt. Direct SQL statements issued inside top-levelDOblocks orCALLprocedures run insideProcessUtility(executor nesting0) and are evaluated as top-level statements. - Effective role exemptions: exemptions check the current effective role (
GetUserId()): superusers and roles that inheritpg_use_reserved_connections(PG 16+, respectingWITH INHERIT FALSEandSET ROLE) are exempt. A superuser who executesSET ROLE app_useris governed byapp_user’s rules. - Other unconditional exemptions:
IsParallelWorker(),EXEC_FLAG_EXPLAIN_ONLY(EXPLAINwithoutANALYZE), and bootstrap processing mode.
Deterministic Matching Precedence
Rules are matched in strict specificity order over (query_id, db_oid, role_oid). A present_mask bitmask skips any pattern not currently populated:
(query_id, db_oid, role_oid)(query_id, db_oid, 0)(query_id, 0, role_oid)(query_id, 0, 0)(0, db_oid, role_oid)(0, db_oid, 0)(0, 0, role_oid)(0, 0, 0)
The first matching rule wins. Queries with query_id = 0 still match wildcard patterns (5–8).
Rejection Error & Server Log Behavior
When a query is rejected, pgbreaker fails fast in ExecutorStart with custom Class 53 (Insufficient Resources) 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
SQLSTATE:53P01(Class 53 indicates insufficient resources; whether and how to back off or retry is application policy—note that persistenttrip()rules will immediately reject retries until removed or bypassed).reason:concurrency_limit(including when the 32-entry per-backend concurrency ledger is full under enforcement) orqps_limit.- Bounded extension server logs (
emit_log_hook):pgbreakerchainsemit_log_hookto suppress PostgreSQL’s server-side logging of raw53P01ERRORrecords (clients always receive the fullERRORandDETAIL). Note that PostgreSQL facilities logging prior toExecutorStart(such aslog_statement = 'all') still log incoming statements normally. Forpgbreaker’s own rejection output:- When
pgbreaker.log_rejects = off,0server log lines are emitted for53P01rejections regardless oflog_min_messagesorlog_min_error_statement. - When
pgbreaker.log_rejects = on, at most10serverLOGlines/second are emitted instance-wide:text LOG: pgbreaker: rejected query (rule_id=1 reason=concurrency_limit query_id=-4829103847129384 db_oid=16384 role_oid=16385)
- When
Operational Playbooks
1. Safe Shadow-First Rollout
Validate impact before blocking live traffic by creating a rule with shadow => true (or enabling pgbreaker.shadow = on globally via SIGHUP). Note that both the per-rule shadow flag (false) and the global pgbreaker.shadow GUC (off) must be disabled for rejections to be enforced:
SELECT pgbreaker.set_rule(
query_id => 771829301293847,
max_concurrency => 20,
shadow => true
);
-- Watch live active_count and shadows_total under real traffic
SELECT rule_id, active_count, hits_total, shadows_total
FROM pgbreaker.rules;
-- Verify global pgbreaker.shadow is off, then upsert the same key with shadow => false
-- to enforce in place (preserves live active_count)
SHOW pgbreaker.shadow;
SELECT pgbreaker.set_rule(
query_id => 771829301293847,
max_concurrency => 20,
shadow => false
);
2. Emergency Hot Bypass (SIGHUP)
Bypass all pgbreaker enforcement without restarting PostgreSQL or losing persisted rules. pg_reload_conf() signals reload asynchronously; bypass takes effect per backend upon processing SIGHUP:
ALTER SYSTEM SET pgbreaker.enabled = off;
SELECT pg_reload_conf();
Re-enable once the incident is resolved:
ALTER SYSTEM SET pgbreaker.enabled = on;
SELECT pg_reload_conf();
3. Read-Only Hot Standby Local Trip & pg_basebackup Seeding
- Because
pgbreakerstores state in node-local shared memory and$PGDATA/pg_stat/pgbreaker.rules(with zero catalog writes and zero SPI), you can trip a runaway reporting query directly on a read-only hot standby without touching the primary:sql -- Run directly on the standby as superuser SELECT pgbreaker.trip(query_id => -4829103847129384); - Initial seeding via
pg_basebackup: because the persisted rules file lives on disk in$PGDATA/pg_stat/, a newly takenpg_basebackupcopies the persisted file present on the primary at backup time (not unpersisted in-memory shared memory; inspectpgbreaker.ruleson the standby after startup). Afterward, primary and standby rules evolve independently and never replicate via WAL.
4. Persistence, Fail-Open Recovery & Lowered max_rules
- Immediate publish + decoupled durability: the 4 rule mutators (
trip,set_rule,remove_rule,clear_rules) publish changes into shared memory immediately so emergency trips take effect even if disk I/O is slow or failing (reset_stats()is memory-only). Disk saves write a unique temp file ($PGDATA/pg_stat/pgbreaker.rules.tmp.<pid>.<seq>), callpg_fsync, swap atomically viarename, and fsync the parent directory under PostgreSQL’s configured durability policy (fsync). If disk persistence fails,pgbreakeremits aWARNING, setspgbreaker.status.persisted = false, and automatically retries flushing on the next call to any of the 4 rule mutators (trip,set_rule,remove_rule, orclear_rules—including an idempotent no-opset_rule()or non-matchingremove_rule()). - Startup loading: on a fresh cluster where
$PGDATA/pg_stat/pgbreaker.rulesdoes not exist (ENOENT), startup succeeds silently with0rules. If the file is non-regular (e.g., FIFO or symlink), unreadable, truncated, CRC32C-corrupted, or version-incompatible,pgbreakerlogs aWARNINGand boots with0rules (Fail-Open). - Lowering
pgbreaker.max_rules: if the on-disk file contains more rules than the configuredpgbreaker.max_rules,pgbreakerloads the firstmax_rulesentries Fail-Open, emits aWARNING, setspersisted = false, and pauses persistence (preserving the oversized on-disk file) until you either raisepgbreaker.max_rulesand restart or runSELECT pgbreaker.clear_rules()to reset persistence cleanly.
5. Cleaning Up Orphaned Rules After DROP DATABASE / DROP ROLE
Rules are keyed by numeric db_oid and role_oid. If a referenced database or role is dropped, the rule remains in shared memory with db_name = NULL or role_name = NULL. Remove orphaned rules directly from the filtered result set:
-- Inspect and remove rules referencing dropped databases or roles
SELECT r.rule_id, r.query_id, r.db_oid, r.role_oid,
pgbreaker.remove_rule(r.rule_id) AS removed
FROM pgbreaker.rules AS r
WHERE (r.db_oid <> 0 AND r.db_name IS NULL)
OR (r.role_oid <> 0 AND r.role_name IS NULL);
6. DROP EXTENSION pgbreaker Semantics
DROP EXTENSION pgbreaker drops only the SQL functions and views in the current database. Active rules in shared memory and $PGDATA/pg_stat/pgbreaker.rules remain enforced until you run SELECT pgbreaker.clear_rules() before dropping, bypass with pgbreaker.enabled = off, or remove pgbreaker from shared_preload_libraries and restart PostgreSQL.