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_init calls EnableQueryId(), so PostgreSQL’s default compute_query_id = 'auto' enables query_id generation automatically. Setting compute_query_id = 'on' explicitly is also supported. Across PostgreSQL 14–18, parameterized queries ($1 Param nodes via PREPARE or Extended Query Protocol) can produce a different query_id than queries with literal constants (Const nodes such as WHERE id = 1); always obtain the exact query_id from pg_stat_activity, pg_stat_statements, or EXPLAIN (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, and clear_rules persist to disk immediately; reset_stats is memory-only). Mutations do not roll back on ROLLBACK or ROLLBACK 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: NULL is valid only for db_name and role_name (mapping to wildcard OID 0; non-null names resolve via get_database_oid / get_role_oid). Passing explicit SQL NULL for query_id, max_concurrency, max_qps, burst, or shadow raises 22023 (invalid_parameter_value). query_id = 0 matches any query ID.
  • max_concurrency: -1 = unlimited, 0 = instant trip (reject all non-exempt executions), > 0 = maximum concurrent executions.
  • max_qps: -1 = unlimited, or 1..1000000000 (1B QPS cap) enforced via smooth GCRA with conservative ceiling emission interval ceil(1e9 / max_qps) ns.
  • burst: token burst tolerance for max_qps > 0. 0 (default) uses max(1, max_qps / 10); negative values raise 22023.
  • shadow: when true, would-be rejections increment shadows_total without rejecting the query.
  • Allow-override / hit-counting rules: leaving both max_concurrency = -1 and max_qps = -1 is valid and creates a hit-counting or allow-override rule (useful with matching precedence to exempt a specific (db, role) from a broader trip() 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 if persisted = false). Changing limits or shadow on an existing key updates the rule in place without bumping rule_gen or resetting live active_count or GCRA debt. Returns rule_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) require shared_preload_libraries = 'pgbreaker' and raise ERROR 55000: pgbreaker must be loaded via shared_preload_libraries if invoked without preloading (including when NULL is passed to trip() or remove_rule()).
  • Schema install safety: CREATE EXTENSION pgbreaker verifies that schema pgbreaker is owned by a superuser, has no non-superuser CREATE privileges (direct or inherited), and contains no pre-existing relations, functions, or types.
  • Zero PUBLIC privileges: schema pgbreaker, all 5 mutating functions, both backing SRFs (rules_view(), status_view()), and both views (rules, status) have all privileges revoked from PUBLIC.
  • Mutating control functions: enforce if (!superuser()) in C in addition to SQL REVOKE ALL FROM PUBLIC. Even if GRANT EXECUTE is issued manually, non-superusers cannot mutate rules.
  • Monitoring access: USAGE on schema pgbreaker, EXECUTE on rules_view()/status_view(), and SELECT on rules/status are explicitly granted to pg_read_all_stats (which pg_monitor inherits). This works even when ALTER DEFAULT PRIVILEGES REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC is configured.

Statement Scope & Exemptions

  • Executor-only scope (ProcessUtility exclusion): pgbreaker attaches to PostgreSQL executor hooks (ExecutorStart / ExecutorRun / ExecutorFinish / ExecutorEnd). Utility work that does not start an executor (such as VACUUM, ANALYZE, CREATE INDEX, standard DDL, and plain COPY table without RLS) is excluded so maintenance and recovery are not blocked. Any statement—including utility commands that invoke the executor such as COPY (SELECT ...), COPY table TO under Row-Level Security, CREATE TABLE AS, REFRESH MATERIALIZED VIEW, and SQL executed inside DDL event triggers—passes through ExecutorStart at nesting level 0.
  • Nesting semantics (DO / CALL vs nested functions): pgb_nesting_level is balanced unconditionally across all four executor hooks regardless of whether pgbreaker.enabled or rule_count changed mid-execution. Statements nested inside an active top-level executor query (SQL/PLpgSQL functions invoked by SELECT, triggers) see nesting_level > 0 and are exempt. Direct SQL statements issued inside top-level DO blocks or CALL procedures run inside ProcessUtility (executor nesting 0) and are evaluated as top-level statements.
  • Effective role exemptions: exemptions check the current effective role (GetUserId()): superusers and roles that inherit pg_use_reserved_connections (PG 16+, respecting WITH INHERIT FALSE and SET ROLE) are exempt. A superuser who executes SET ROLE app_user is governed by app_user’s rules.
  • Other unconditional exemptions: IsParallelWorker(), EXEC_FLAG_EXPLAIN_ONLY (EXPLAIN without ANALYZE), 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:

  1. (query_id, db_oid, role_oid)
  2. (query_id, db_oid, 0)
  3. (query_id, 0, role_oid)
  4. (query_id, 0, 0)
  5. (0, db_oid, role_oid)
  6. (0, db_oid, 0)
  7. (0, 0, role_oid)
  8. (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 persistent trip() 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) or qps_limit.
  • Bounded extension server logs (emit_log_hook): pgbreaker chains emit_log_hook to suppress PostgreSQL’s server-side logging of raw 53P01 ERROR records (clients always receive the full ERROR and DETAIL). Note that PostgreSQL facilities logging prior to ExecutorStart (such as log_statement = 'all') still log incoming statements normally. For pgbreaker’s own rejection output:
    • When pgbreaker.log_rejects = off, 0 server log lines are emitted for 53P01 rejections regardless of log_min_messages or log_min_error_statement.
    • When pgbreaker.log_rejects = on, at most 10 server LOG lines/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)

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 pgbreaker stores 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 taken pg_basebackup copies the persisted file present on the primary at backup time (not unpersisted in-memory shared memory; inspect pgbreaker.rules on 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>), call pg_fsync, swap atomically via rename, and fsync the parent directory under PostgreSQL’s configured durability policy (fsync). If disk persistence fails, pgbreaker emits a WARNING, sets pgbreaker.status.persisted = false, and automatically retries flushing on the next call to any of the 4 rule mutators (trip, set_rule, remove_rule, or clear_rules—including an idempotent no-op set_rule() or non-matching remove_rule()).
  • Startup loading: on a fresh cluster where $PGDATA/pg_stat/pgbreaker.rules does not exist (ENOENT), startup succeeds silently with 0 rules. If the file is non-regular (e.g., FIFO or symlink), unreadable, truncated, CRC32C-corrupted, or version-incompatible, pgbreaker logs a WARNING and boots with 0 rules (Fail-Open).
  • Lowering pgbreaker.max_rules: if the on-disk file contains more rules than the configured pgbreaker.max_rules, pgbreaker loads the first max_rules entries Fail-Open, emits a WARNING, sets persisted = false, and pauses persistence (preserving the oversized on-disk file) until you either raise pgbreaker.max_rules and restart or run SELECT 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.