Free audit

View Audit Scope
JusDBPgBouncer 1.21 - 1.23+ · Lightweight PostgreSQL Connection Pooler

PgBouncer architecture, pgbouncer.ini reference & pooling hub.

PostgreSQL forks a dedicated OS process (~10 MB RAM plus catalog caches) for every backend connection, causing context-switching and lock contention above a few hundred active sessions. PgBouncer is a lightweight libevent connection pooler (~2 KB per client socket) that multiplexes thousands of application connections onto a tight pool of PostgreSQL backends. This hub documents pgbouncer.ini sizing, prepared-statement multiplexing, and SHOW POOLS triage, backed by a 15-minute P1 response SLA.

PgBouncer

libevent Pooler Stack (:6432)

Transaction Pooling

recommended

Assigns a PostgreSQL backend only for the duration of a single transaction (`BEGIN ... COMMIT`), returning it immediately afterward.

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

  • Innoviti
  • Blitz
  • Freecharge
  • Nango
  • Recochain
  • Screen Facts
  • Nexora
  • WeCredit

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.

P1 incidents, 24/7

15 mins

Response SLA

P1 response SLA: 15 mins, 24/7.

P2 incidents, 24/7

30 mins

Response SLA

P2 response SLA: 30 mins, 24/7.

P3 incidents, 24/7

60 mins

Response SLA

P3 response SLA: 60 mins, 24/7.

SLA response times by severity (24/7)

P1 · Critical15 mins

Production database down, primary unreachable, data corruption risk, or active failover event.

P2 · High30 mins

Severe latency spike, replication lag climbing rapidly, connection exhaustion, or degraded HA node.

P3 · Medium60 mins

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 · [databases] · server_reset_query

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.
max_prepared_statements = 200 · PgBouncer 1.21+

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.
scram-sha-256 · auth_query · client_tls_sslmode

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.
so_reuseport = 1 · Kubernetes Sidecar · systemd

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.
PAUSE / RESUME · Patroni · dns_max_ttl

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.
SHOW POOLS · SHOW STATS · pgbouncer_exporter

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.

Active
  • 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.

Production Configuration Specimen · PgBouncer 1.22+

Hardened pgbouncer.ini with Prepared Statements & SCRAM-SHA-256 auth_query

Before: 850 PG backends · 42P05 errorsAfter: 80 PG backends · 0 cl_waiting

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 LayerCustomer TeamJusDB DBRE Team
Application ORM & Connection StringsPoint application services at PgBouncer port 6432 (`prod_oltp` / `prod_session`)Audit ORM prepared-statement settings, client pool limits, and transaction boundaries
`pgbouncer.ini` & Pool SizingApprove infrastructure PRs or Helm chart valuesCalculate `default_pool_size`, `max_db_connections`, and `max_prepared_statements` per workload
SCRAM-SHA-256 Auth & TLS CertificatesProvide TLS certificates from Vault/ACM/cert-managerDeploy `SECURITY DEFINER` `auth_query` functions and configure TLS 1.3 frontend termination
Multi-Core Scaling & Failover HooksProvide VM/Kubernetes compute resourcesConfigure `so_reuseport = 1` systemd units and wire Patroni/HAProxy `PAUSE`/`RESUME` hooks
24/7 Queue Monitoring & Incident ResponseReceive Slack/PagerDuty escalations on SLA eventsMonitor `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 VectorJusDB PgBouncer DBRERDS Proxy / PgPool-IIDirect Connection Default
Pool Architecture & Multiplexing ModesExpert transaction-mode tuning, reserve pool burst configuration, client-to-server multiplexing ratios such as 50:1, and a large drop in Postgres backend memoryStandard session pooling defaults with low client concurrency thresholds and high connection latency overheadDirect client connections resulting in thousands of postgres backend processes competing for shared memory and CPU context switches
Latency Overhead & Memory FootprintSub-millisecond connection checkout latency, lightweight single-binary C footprint consuming single-digit megabytes under massive loadHeavier Java- or Python-based proxies or RDS Proxy with network hop overhead and added monthly vCPU infrastructure chargesApplication-side connection pools in containerized microservices creating hundreds of idle connections per pod across K8s clusters
Prepared Statements & Transaction StateProtocol-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 poolingDevelopers disabled prepared statements globally or encountering unexplained connection state leaks across multi-tenant clients
Failover Resilience & HA TopologiesRedundant active-passive PgBouncer pairs fronted by HAProxy or Keepalived VIP, synchronized with Patroni REST API /master health endpointsSingle PgBouncer instance representing a single point of failure without automated backend failover trackingStale PgBouncer connection pools holding dead TCP sockets to demoted primary nodes following an unexpected database failover
Serverless & Microservice Burst ProtectionInstant connection acceptance for thousands of ephemeral AWS Lambda / Cloud Run invocations without backend process fork stormsStrict connection rate limits causing HTTP 500 errors and lambda timeouts during sudden traffic surgesLambda bursts overwhelming PostgreSQL max_connections within seconds, cascading into total application outage
Monitoring & Incident ResponseContinuous 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 diagnosisPlatform teams guessing at max_client_conn and default_pool_size values after production connection pool exhaustion alerts
Dedicated Consulting Spoke

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.
Managed DBRE Retainer

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 Engineering Entry Point

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, least-privilege credentials in your vault, and security controls aligned with ISO 27001 and SOC 2 Type II. JusDB's security practices are aligned with ISO 27001 and SOC 2 Type II, and JusDB is pursuing both certifications (see Terms, section 12).
  • 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?

This page (/databases/tools/pgbouncer) is our technical architecture and `pgbouncer.ini` configuration reference hub covering pooling modes, prepared-statement multiplexing, `SHOW POOLS` metrics, and multi-core `so_reuseport` scaling. If you want to scope a commercial consulting project, architecture audit, or implementation engagement, visit our dedicated consulting spoke at /tools/pgbouncer/consulting.

Does PgBouncer support prepared statements in transaction pooling mode?

Yes, starting in PgBouncer 1.21.0! By setting `max_prepared_statements = 200` (or another positive integer) in `pgbouncer.ini`, PgBouncer intercepts client protocol-level `Parse`, `Bind`, and `Close` messages, rewrites statement names per backend (`PGBOUNCER_1`, `PGBOUNCER_2`, etc.), and re-prepares statements automatically if a transaction lands on a backend that has not cached that statement yet. You no longer need to disable prepared statements in Prisma (`?pgbouncer=true`), PgJDBC, or Go `pgx`.

How should `default_pool_size` and `max_db_connections` be calculated?

A common mistake is setting `default_pool_size = 200`, which actually allows 200 backend connections *per `(database, user)` pair* and can easily exceed PostgreSQL's `max_connections`. Instead, compute your total optimal active query concurrency on PostgreSQL (typically `(vCPU * 2)` to `(vCPU * 4)` on NVMe storage), set `max_db_connections` on each database to stay comfortably below `max_connections`, and divide that budget across your PgBouncer instances and active application roles using `default_pool_size` (typically 20 to 50).

What do `cl_waiting` and `maxwait` mean in `SHOW POOLS`?

In PgBouncer's `SHOW POOLS` output, `cl_waiting` is the number of client connections currently queued waiting for a free PostgreSQL server connection (`sv_idle`), and `maxwait` (plus `maxwait_us`) is the age in seconds of the longest-waiting client in that queue. In a healthy cluster, `cl_waiting` should be 0 except for brief sub-second bursts. Sustained `cl_waiting > 0` indicates either slow queries/locks on PostgreSQL or `idle in transaction` sessions pinning all `sv_active` slots.

How do we scale PgBouncer past a single CPU core?

Because PgBouncer's event loop is single-threaded per OS process, a single instance can saturate one vCPU core at roughly 35,000 to 50,000 QPS (or lower when terminating TLS). Setting `so_reuseport = 1` in `pgbouncer.ini` allows multiple PgBouncer processes on the same host to bind to port `6432` simultaneously, with the Linux kernel distributing incoming TCP connections evenly across worker processes.

How does PgBouncer compare to AWS RDS Proxy, Pgpool-II, and Supavisor?

PgBouncer has a tiny memory footprint (~2 KB per connection), adds sub-millisecond latency, supports protocol-level prepared statements in transaction mode (1.21+), and runs identically on-prem, on EC2/Kubernetes, or in front of RDS/Cloud SQL without per-vCPU cloud proxy surcharges. AWS RDS Proxy integrates with IAM and Aurora failover metadata but incurs per-vCPU licensing charges and pins connections when session state changes. Pgpool-II adds SQL query parsing, read/write load balancing, and HA watchdog orchestration at the cost of higher memory and CPU overhead.

What are JusDB's SLA response times for PgBouncer and PostgreSQL support?

24/7 support. SLA response times: P1 – 15 mins | P2 – 30 mins | P3 – 60 mins. P1 covers a critical production outage, connection pool starvation, or failover hang. Response means an on-call engineer is working the incident, not an automated reply.

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.

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.