PgBouncer cl_waiting Queue Saturation & Little’s Law Pool Sizing
Use Little’s Law to size PgBouncer default_pool_size, fix transaction-mode prepared statement errors, and eliminate connection queue storms.
API p99 latency spikes from 40ms to 8,000ms while PostgreSQL CPU sits at only 28%. SHOW POOLS in PgBouncer reports cl_waiting > 350 and maxwait > 5s.
pgbouncer_pools_client_waiting_connections > 25 AND pgbouncer_pools_client_maxwait_seconds > 0.5By Little’s Law (L = lambda * W), concurrency equals throughput times average query hold time. If a missing composite index slows a query from 4ms to 80ms (20x), the exact same 400 RPS workload suddenly demands 32 active Postgres server connections instead of 2.
When PgBouncer default_pool_size is set too low (or pool_mode=session holds connections across idle app think-time), excess requests pile up in cl_waiting until client timeouts trigger retry storms.
Conversely, setting default_pool_size above ~2x-4x vCPU cores causes OS context-switching thrash and LWLock contention inside PostgreSQL.
An 8-vCPU PostgreSQL primary sits behind PgBouncer (pool_mode=transaction, default_pool_size=24). Traffic is flat at 500 RPS, yet cl_waiting jumps to 400 and Postgres CPU is 95%. What is the fastest safe mitigation?
- Verify SHOW POOLS shows cl_waiting = 0 and maxwait < 0.05s at peak RPS.
- Fix the underlying slow query with CREATE INDEX CONCURRENTLY so query hold time W drops back below 10ms.
- Verify application drivers do not rely on session-scoped SET variables or advisory locks when running in pool_mode=transaction.
How do I calculate default_pool_size with Little’s Law?
Multiply peak queries per second (lambda) by p95 query duration in seconds (W), then cap the pool at roughly 2x to 4x PostgreSQL vCPU cores so CPU saturation does not trigger lock thrash.
Does PgBouncer transaction pooling support prepared statements?
Yes. PgBouncer 1.21+ natively supports protocol-level prepared statements in transaction mode when max_prepared_statements is set above 0.
Why should query_wait_timeout be low (e.g., 5s) instead of 120s?
Clients and load balancers time out after 5-15s anyway. Letting PgBouncer queue abandoned requests for 120s executes dead work after the caller gave up and fuels cascading retry storms.