PgBouncer architecture, pgbouncer.ini reference & pooling hub.
PgBouncer
libevent Pooler Stack (:6432)
Transaction Pooling
recommendedAssigns a PostgreSQL backend only for the duration of a single transaction (`BEGIN ... COMMIT`), returning it immediately afterward.
Prepared Statements (1.21+)
recommendedTracks and rewrites protocol-level `Parse`/`Bind` statements across shared backends in transaction mode without `prepared statement already exists` errors.
Multi-Core SO_REUSEPORT
supportedRun N worker processes per vCPU sharing port 6432 via kernel socket sharding for 100,000+ QPS workloads.
Admin Console :6432
supportedVirtual `pgbouncer` database for live connection queue metrics, online config reloads, and zero-drop failover pausing.
We deploy PgBouncer on Linux VMs, Kubernetes sidecars, and in front of AWS RDS, Aurora, and Cloud SQL.
- P1: 15 min · P2: 30 min
- SLA response times, 24/7 (P3: 60 min). Response means an on-call engineer is working the incident.
- Pool Sizing Formula
- default_pool_size = ((vCPU * 2) + effective_spindle_count) divided across active user/database pairs.
- Consulting & Support
- Use this page for pgbouncer.ini and SHOW POOLS reference patterns, or visit our dedicated PgBouncer Consulting spoke for custom engagements.
Selected clients
Production Failure Modes
Six PgBouncer bottlenecks we resolve in production.
Putting PgBouncer in front of PostgreSQL is only step one. Misconfigured pool sizes per user/DB pair, missing prepared-statement settings, or zombie transactions can still bring traffic to a halt.
Prisma, Go pgx, or JDBC throws prepared statement errors
ERROR: prepared statement "s1" already exists (42P05)
PgBouncer is running `pool_mode = transaction` on an older release (<1.21) or with `max_prepared_statements = 0`, while the ORM uses protocol-level prepared statements across shared backend sessions.
Upgrade to PgBouncer 1.21+ and set `max_prepared_statements = 200` in `pgbouncer.ini` so PgBouncer multiplexes and renames server-side prepared statements transparently.
Application requests stall in queue during traffic spikes
cl_waiting > 0 and maxwait climbing in SHOW POOLS
All `default_pool_size` + `reserve_pool_size` backend connections are pinned by slow queries or `idle in transaction` sessions, starving incoming client transactions.
Inspect `SHOW POOLS` and `pg_stat_activity`, set `idle_transaction_timeout = 30` and `query_wait_timeout = 60`, and right-size `default_pool_size`.
PostgreSQL still hits `FATAL: sorry, too many clients already`
sum(default_pool_size) > PostgreSQL max_connections
`default_pool_size` in PgBouncer applies per `(database, user)` pair, not globally! With 6 microservices (6 DB users) and `default_pool_size = 50`, a single PgBouncer can open 300 backend connections.
Bound total backend connections using `max_db_connections` and `max_user_connections` in `[databases]`/`[users]` so the sumacross all PgBouncer instances stays below `max_connections - superuser_reserved_connections`.
Single PgBouncer process hits 99% CPU on 1 core at 45,000 QPS
pgbouncer PID pinned at 99%+ CPU in top/htop
PgBouncer uses a single-threaded `libevent` event loop per process; TLS handshakes (`client_tls_sslmode`) and high packet rates saturate a single CPU core.
Enable `so_reuseport = 1` in `pgbouncer.ini` and run multiple systemd template units (`pgbouncer@1.service` ... `pgbouncer@4.service`) sharing port 6432 across cores.
SCRAM-SHA-256 authentication fails when adding new PostgreSQL users
FATAL: password authentication failed / auth_query mismatch
Static `/etc/pgbouncer/userlist.txt` hashes are out of sync with `pg_authid`, or `auth_user` lacks `SECURITY DEFINER` helper access to fetch SCRAM verifiers dynamically.
Replace static userlists with `auth_type = scram-sha-256`, `auth_user = pgbouncer_auth`, and a restricted `SECURITY DEFINER` `auth_query` function.
Session-level features (`SET LOCAL`, `LISTEN/NOTIFY`, advisory locks) break
Notifications missed or session GUC leaked across tenants
Workloads using `LISTEN/NOTIFY`, session-level `pg_advisory_lock()`, or un-scoped `SET search_path` are routed through a `pool_mode = transaction` pool.
Create a dedicated `[databases]` alias in `pgbouncer.ini` (for example, `app_session = host=... pool_mode=session default_pool_size=15`) specifically for long-lived worker listeners.
Response SLA & Incident Triage
SLA response times and the first hour of a P1.
When `cl_waiting` spikes into the hundreds or `max_connections` is breached during a launch, you reach a senior PostgreSQL DBRE directly.
15 mins
Response SLA
P1 response SLA: 15 mins, 24/7.
30 mins
Response SLA
P2 response SLA: 30 mins, 24/7.
60 mins
Response SLA
P3 response SLA: 60 mins, 24/7.
SLA response times by severity (24/7)
Production database down, primary unreachable, data corruption risk, or active failover event.
Severe latency spike, replication lag climbing rapidly, connection exhaustion, or degraded HA node.
Non-critical slow query regression, staging issue, backup warning, configuration question, or planned operational request.
Our engineering team is in India (IST, UTC+5:30) and provides 24/7 support. Response means an on-call engineer is working the incident, not an automated reply.
01 · Page
0 to 15 minutes (P1 response SLA)
Your alert reaches a senior PostgreSQL/PgBouncer DBRE directly, with no Tier-1 ticket triage queue.
02 · Triage
15 to 30 minutes
We connect to the PgBouncer Admin console (`psql -p 6432 pgbouncer`) and inspect `SHOW POOLS`, `SHOW CLIENTS`, `SHOW SERVERS`, and `SHOW STATS` alongside `pg_stat_activity`.
03 · Mitigate
30 to 60 minutes
We clear `cl_waiting` queues by terminating blocking `idle in transaction` backends, adjusting `default_pool_size` / `max_db_connections`, and issuing a live `RELOAD;` without dropping clients.
04 · Review
Within 24 hours
We deliver a written finding with permanent `pgbouncer.ini` changes, prepared-statement cache sizing, and Prometheus `pgbouncer_exporter` alert rules.
Architecture & Operational Scope
Six PgBouncer capabilities we architect and operate.
We configure PgBouncer so your application developers get both high connection concurrency and full protocol-level prepared statement performance.
Pool Mode Architecture (Transaction vs Session)
Design dual-pool `[databases]` topologies that run 95% of OLTP traffic through `pool_mode = transaction` while isolating `LISTEN/NOTIFY` and migrations on a `session` alias.
- Elimination of session-state leaks via `server_reset_query` and `DISCARD ALL` tuning.
- Safe transaction-scoped GUC usage (`SET LOCAL`) for multi-tenant RLS schemas.
Protocol Prepared Statement Multiplexing
Unlock full prepared-statement performance in transaction pooling mode using PgBouncer 1.21+ `max_prepared_statements`.
- Zero code changes required for Prisma, Hibernate/PgJDBC, Go pgx, and SQLAlchemy.
- Memory footprint calibration per backend connection for prepared plan caches.
Dynamic SCRAM-SHA-256 & TLS Termination
Harden authentication and encryption with dynamic `auth_query` lookups and TLS 1.3 frontend termination.
- Zero manual `userlist.txt` edits when rotating database role passwords.
- Offload expensive TLS handshakes from PostgreSQL backends to PgBouncer workers.
Multi-Core `so_reuseport` & Kubernetes Sidecars
Scale PgBouncer horizontally across CPU cores on Linux VMs or as a container sidecar inside Kubernetes deployments.
- Kernel `SO_REUSEPORT` socket sharding across N systemd processes per host.
- Graceful `SHUTDOWN WAIT_FOR_CLIENTS` lifecycle hooks for zero-drop K8s pod rollouts.
Patroni & RDS/Aurora Failover Integration
Combine PgBouncer `PAUSE` / `RESUME` / `RECONNECT` primitives with Patroni and HAProxy for sub-second connection cutovers.
- Hold client transactions queued in memory during primary switchovers.
- Aggressive `server_lifetime`, `server_idle_timeout`, and `dns_max_ttl` tuning for RDS/Aurora.
Queue Telemetry & Prometheus Alerting
Instrument every pool with `pgbouncer_exporter` and Percona PMM so connection saturation is caught before `query_wait_timeout` fires.
- Real-time tracking of `cl_waiting`, `maxwait_us`, `sv_active`, and `avg_xact_time`.
- Automated capacity forecasts tying application pod scaling to backend pool ceilings.
Interactive Pool States & Reference pgbouncer.ini
How PgBouncer behaves across transaction pooling, queue saturation, and PAUSE/RESUME.
Simulate steady-state 100:1 transaction multiplexing, a `cl_waiting` pool starvation incident, and a zero-drop `PAUSE`/`RESUME` primary switchover, then inspect our reference `pgbouncer.ini`.
PgBouncer Pool & Queue State Simulator (SHOW POOLS)
Application and routing
8,500 Kubernetes app connections share 80 PostgreSQL backends via `pool_mode = transaction` and `max_prepared_statements = 200`; `cl_waiting` is 0.
App Fleet (Prisma / pgx / JDBC)
8,500 persistent client sockets
TLS 1.3 terminated at PgBouncer :6432
PgBouncer 1.22 (so_reuseport x4)
pool_mode = transaction · max_prepared = 200
cl_waiting = 0 · sv_idle = 12
PostgreSQL 17 Primary (16 vCPU)
80 warm backend processes
Low context switching · 99.4% cache hit
8,500 Kubernetes app connections share 80 PostgreSQL backends via `pool_mode = transaction` and `max_prepared_statements = 200`; `cl_waiting` is 0.
Application and routing
An unindexed slow query or external HTTP call inside a `BEGIN ... COMMIT` block pins all 80 `sv_active` servers, causing `cl_waiting` to surge to 640.
App Fleet
640 requests stalled waiting for server
Approaching query_wait_timeout = 30s
PgBouncer Pool Queue
sv_idle = 0 · reserve_pool exhausted
ALERT: pgbouncer_pools_client_waiting > 50
PostgreSQL Primary
45 backends stuck `idle in transaction`
Holding row locks and pool slots
An unindexed slow query or external HTTP call inside a `BEGIN ... COMMIT` block pins all 80 `sv_active` servers, causing `cl_waiting` to surge to 640.
Application and routing
During a planned PostgreSQL primary switchover, PgBouncer executes `PAUSE;`, buffers incoming transactions for 1.8 seconds, reconnects to the new primary, and runs `RESUME;`.
App Fleet
Sockets remain open on :6432
Transactions experience brief 1.8s pause
PgBouncer Admin Automation
PAUSE -> update host -> RESUME
Triggered by Patroni on_role_change hook
Promoted PostgreSQL Primary
Accepts fresh warm pool connections
Old primary drained cleanly
During a planned PostgreSQL primary switchover, PgBouncer executes `PAUSE;`, buffers incoming transactions for 1.8 seconds, reconnects to the new primary, and runs `RESUME;`.
Production Configuration Specimen · PgBouncer 1.22+
Hardened pgbouncer.ini with Prepared Statements & SCRAM-SHA-256 auth_query
1. Reference /etc/pgbouncer/pgbouncer.ini
/etc/pgbouncer/pgbouncer.ini
[databases] ; Primary transactional pool (95% of application traffic) prod_oltp = host=10.0.3.10 port=5432 dbname=appdb pool_mode=transaction max_db_connections=120 ; Dedicated session pool for LISTEN/NOTIFY workers & schema migrations prod_session = host=10.0.3.10 port=5432 dbname=appdb pool_mode=session default_pool_size=10 [pgbouncer] listen_addr = 0.0.0.0 listen_port = 6432 so_reuseport = 1 auth_type = scram-sha-256 auth_user = pgbouncer_auth auth_query = SELECT usename, passwd FROM pgbouncer.get_auth($1) pool_mode = transaction max_client_conn = 10000 default_pool_size = 40 min_pool_size = 10 reserve_pool_size = 10 reserve_pool_timeout = 3 max_db_connections = 140 ; Protocol-level prepared statement multiplexing (PgBouncer 1.21+) max_prepared_statements = 200 ; Timeouts & Zombie Transaction Protection server_idle_timeout = 300 server_lifetime = 3600 query_wait_timeout = 30 idle_transaction_timeout = 30 tcp_keepalive = 1 tcp_keepidle = 30 tcp_keepintvl = 10
2. Admin console triage & switchover commands (:6432/pgbouncer)
psql -p 6432 -U pgbouncer_admin pgbouncer
-- Connect to the virtual PgBouncer Admin console -- psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -- 1. Check for queued clients (cl_waiting) and maximum wait time (maxwait) SHOW POOLS; -- 2. Inspect transaction throughput, average query latency, and wait time SHOW STATS; -- 3. Reload pgbouncer.ini changes (pool sizes, timeouts, auth) online without dropping clients RELOAD; -- 4. Gracefully pause traffic during a primary switchover, reconnect backends, and resume PAUSE prod_oltp; RECONNECT prod_oltp; RESUME prod_oltp;
Shared Responsibility & Platforms
What your team owns and what JusDB owns.
Managed cloud databases automate much of the infrastructure layer, but your team still owns query performance, capacity, cost, and incident decisions. We deploy and operate PgBouncer across bare-metal Linux, Kubernetes sidecars/Deployments, AWS EC2/RDS/Aurora, GCP Cloud SQL, and Azure.
| Operational Layer | Customer Team | JusDB DBRE Team |
|---|---|---|
| Application ORM & Connection Strings | Point application services at PgBouncer port 6432 (`prod_oltp` / `prod_session`) | Audit ORM prepared-statement settings, client pool limits, and transaction boundaries |
| `pgbouncer.ini` & Pool Sizing | Approve infrastructure PRs or Helm chart values | Calculate `default_pool_size`, `max_db_connections`, and `max_prepared_statements` per workload |
| SCRAM-SHA-256 Auth & TLS Certificates | Provide TLS certificates from Vault/ACM/cert-manager | Deploy `SECURITY DEFINER` `auth_query` functions and configure TLS 1.3 frontend termination |
| Multi-Core Scaling & Failover Hooks | Provide VM/Kubernetes compute resources | Configure `so_reuseport = 1` systemd units and wire Patroni/HAProxy `PAUSE`/`RESUME` hooks |
| 24/7 Queue Monitoring & Incident Response | Receive Slack/PagerDuty escalations on SLA events | Monitor `cl_waiting` / `maxwait` via Prometheus and triage within the response SLA |
Customer Boundary
What stays in your control
- Set business priorities, application requirements, and release plans
- Approve production changes, except routine actions you have pre-approved
- Own your cloud accounts, access policies, and vendor relationships
- Decide when maintenance can happen and how quickly service must recover
- Move the work in-house or to another provider after your agreement's notice period, with your data returned or deleted and the transition help your agreement sets out (Terms, section 8)
JusDB Execution Scope
What our DBREs execute for you
- Monitor database health, investigate alerts, and involve the right people
- Review query performance, replication, capacity, and backup health
- Carry out approved changes and update the operating instructions they affect
- Report completed work, open risks, and recommended next steps
Pooler Comparison & Commercial Engagement Paths
PgBouncer vs alternatives and how to engage JusDB.
Compare PgBouncer against Pgpool-II, Odyssey, and AWS RDS Proxy, then choose between our dedicated PgBouncer Consulting spoke, an ongoing PostgreSQL Support retainer, or a free connection pool audit.
| Evaluation Vector | JusDB PgBouncer DBRE | RDS Proxy / PgPool-II | Direct Connection Default |
|---|---|---|---|
| Pool Architecture & Multiplexing Modes | Expert transaction-mode tuning, reserve pool burst configuration, client-to-server multiplexing ratios such as 50:1, and a large drop in Postgres backend memory | Standard session pooling defaults with low client concurrency thresholds and high connection latency overhead | Direct client connections resulting in thousands of postgres backend processes competing for shared memory and CPU context switches |
| Latency Overhead & Memory Footprint | Sub-millisecond connection checkout latency, lightweight single-binary C footprint consuming single-digit megabytes under massive load | Heavier Java- or Python-based proxies or RDS Proxy with network hop overhead and added monthly vCPU infrastructure charges | Application-side connection pools in containerized microservices creating hundreds of idle connections per pod across K8s clusters |
| Prepared Statements & Transaction State | Protocol-level named prepared statement workarounds, DEALLOCATE cleanup hooks, and transaction-safe ORM configuration (Django, Rails, Prisma) | Silent prepared statement errors (e.g. prepared statement already exists) or forcing fallback to high-overhead session pooling | Developers disabled prepared statements globally or encountering unexplained connection state leaks across multi-tenant clients |
| Failover Resilience & HA Topologies | Redundant active-passive PgBouncer pairs fronted by HAProxy or Keepalived VIP, synchronized with Patroni REST API /master health endpoints | Single PgBouncer instance representing a single point of failure without automated backend failover tracking | Stale PgBouncer connection pools holding dead TCP sockets to demoted primary nodes following an unexpected database failover |
| Serverless & Microservice Burst Protection | Instant connection acceptance for thousands of ephemeral AWS Lambda / Cloud Run invocations without backend process fork storms | Strict connection rate limits causing HTTP 500 errors and lambda timeouts during sudden traffic surges | Lambda bursts overwhelming PostgreSQL max_connections within seconds, cascading into total application outage |
| Monitoring & Incident Response | Continuous SHOW POOLS and SHOW CLIENTS metrics export to Prometheus, pool starvation alerting, and senior DBREs on your incident bridge. SLA response times: P1 – 15 mins | P2 – 30 mins | P3 – 60 mins. | Standard cloud support tickets with delayed response times and lack of deep PgBouncer configuration diagnosis | Platform teams guessing at max_client_conn and default_pool_size values after production connection pool exhaustion alerts |
PgBouncer Architecture & Implementation Consulting
Fixed-scope engagement to design, deploy, or tune PgBouncer 1.22+ across Linux VMs, Kubernetes sidecars, or AWS/GCP/Azure.
- Pool sizing math aligned with your vCPU count, IOPS, and PostgreSQL `max_connections`.
- Migration to `pool_mode = transaction` with `max_prepared_statements = 200`.
- Dynamic SCRAM-SHA-256 `auth_query` setup and `so_reuseport` multi-core scaling.
Ongoing PostgreSQL & PgBouncer Support
Named senior PostgreSQL DBREs managing your PgBouncer fleet and PostgreSQL primaries/replicas under one unified SLA.
- 24/7 support. SLA response times: P1 – 15 mins | P2 – 30 mins | P3 – 60 mins.
- Proactive `SHOW POOLS` queue tuning, certificate rotation, and PgBouncer minor upgrades.
- Coordinated `PAUSE`/`RESUME` execution during schema migrations and failovers.
Free PgBouncer & Connection Pool Audit
Seeing `cl_waiting` spikes or `prepared statement already exists` errors? Get a senior PostgreSQL DBRE to inspect your config.
- Review of your `pgbouncer.ini`, `SHOW POOLS`, `SHOW STATS`, and `postgresql.conf`.
- Exact recommendations for `default_pool_size`, `max_db_connections`, and timeouts.
- 30-minute walkthrough with actionable configuration diffs.
Procurement and security
Ready for legal and security review.
- Mutual NDA before any access
- Named individual accounts only
- Read-only access by default
- ISO 27001 & SOC 2 Type II: aligned, certification in progress
Mutual NDA before any access
We sign a mutual NDA before viewing schemas, logs, slow-query captures, or cloud topology.
Least-privilege, named credentials
Engineers connect through your bastion, VPN, or SSM using named accounts with read-only permissions by default.
Change control & approval gates
Production DDL, parameter changes, and failovers follow your change-management workflow with rollback steps prepared first.
Named leadership & direct escalation
Engagements are led by named senior database reliability engineers in India with direct Slack, Teams, and PagerDuty channels.
PgBouncer Technical & Operational FAQ
Frequently asked PgBouncer questions.
Synced 1-to-1 with our structured FAQPage schema. Have a question about `max_prepared_statements` or `SHOW POOLS` queue spikes? Speak with our PostgreSQL DBRE team.
Still have a question?
Ask it on a scoping call. No production access needed.
Book a 30-min scoping call (opens Google Calendar in a new tab)How is this PgBouncer Reference Hub different from JusDB's PgBouncer Consulting page?
Does PgBouncer support prepared statements in transaction pooling mode?
How should `default_pool_size` and `max_db_connections` be calculated?
What do `cl_waiting` and `maxwait` mean in `SHOW POOLS`?
How do we scale PgBouncer past a single CPU core?
How does PgBouncer compare to AWS RDS Proxy, Pgpool-II, and Supavisor?
What are JusDB's SLA response times for PgBouncer and PostgreSQL support?
Related Spokes, Tools & Reference Hubs
Continue exploring PostgreSQL pooling & HA.
Pair PgBouncer transaction pooling with Patroni consensus failover, HAProxy health checks, and right-sized postgresql.conf memory buffers.
PgBouncer Consulting Services
Fixed-scope architecture design, pool sizing, and transaction-mode migration engagements.
PostgreSQL Config Optimizer
Generate tuned postgresql.conf memory, WAL, and max_connections settings alongside PgBouncer.
Patroni Architecture Reference Hub
Combine PgBouncer PAUSE/RESUME callbacks with Patroni + etcd v3 automatic failover.
Pgpool-II Reference Hub
Compare lightweight PgBouncer pooling against Pgpool-II query-level read/write load balancing.
HAProxy Database Routing Hub
Place HAProxy between PgBouncer and Patroni `:8008` health endpoints for seamless primary routing.
PostgreSQL vs Supabase (Supavisor vs PgBouncer)
See how dedicated PgBouncer compares to Supabase's multi-tenant Supavisor pooler at scale.
PostgreSQL Database Services Hub
PostgreSQL performance tuning, HA, upgrades, and support for the databases behind your PgBouncer pools.
Ready to Right-Size Your PgBouncer Pools?
Get a senior PostgreSQL DBRE to review your pgbouncer.ini and SHOW POOLS metrics.
Or request a free audit of one database instance, subject to availability: mutual NDA before read-only access, a prioritized report within one week after access is ready, and no obligation. Or jump straight to our commercial PgBouncer Consulting spoke at /tools/pgbouncer/consulting.







