Connection Pooling with PgBouncer
Why a pooler, how transaction pooling works, and the five things it breaks, measured with 30 concurrent clients
Every Postgres connection is a process with its own memory, and
max_connections is a hard wall (200 here). Applications want far more
connections than that: every web worker, every serverless function, every
pod keeps a few open, mostly idle. PgBouncer accepts thousands of
client connections and lends a small pool of real server connections to
whichever client is running a transaction.
Two choices in this config are worth explaining:
auth_queryinstead of a password file. PgBouncer looks up each user's SCRAM hash in Postgres through aSECURITY DEFINERfunction that only returns non-superusers. There's no second copy of every password to keep in sync; the security lab checks that the function can't be called by the application and never returnspostgres.- TLS on both sides. Clients must use TLS to PgBouncer
(
client_tls_sslmode = require), and PgBouncer verifies the server certificate when it connects onward (server_tls_sslmode = verify-full).
What pooling buys you under load is measured in the load-testing lesson (p99 latency at 128 clients: 275 ms direct, 58 ms through PgBouncer; 300 clients fail direct and work through PgBouncer). This page is about the cost.
What transaction pooling breaks
In transaction mode a client has a server connection only between BEGIN
and COMMIT (or for one statement in autocommit). Anything that lives in
the session stays behind on that server connection, and the next
transaction may get a different one. labs/pooling.py measures each case
with 30 concurrent clients:
docker compose -f compose_prod.yaml run --rm labs python pooling.py
1. SET work_mem = '77MB' on one client, then 30 clients check
the client that ran SET saw 77MB in 20 of 20 queries
other clients saw 77MB in 33 of 300 queries (leaked)
2. SET LOCAL inside a transaction
inside the transaction: 77MB; afterwards 77MB seen by 0 of 50 clients
3. Session advisory locks: lock in one transaction, unlock in the next
30 clients x 20 lock/unlock pairs: 460 unlocks failed ("you don't own a lock");
460 advisory locks still held afterwards by pooled connections
4. Prepared statements, 30 concurrent clients x 20 executions
SQL PREPARE/EXECUTE: 500 executed, 100 'does not exist', 24 PREPAREs 'already exists'
protocol-level prepared statements (psycopg prepare_threshold=0): 0 errors in 600 executions- A session
SETleaks to strangers. TheSETstayed on the server connection it ran on, and 33 queries from other clients that later borrowed that connection ran withwork_mem = 77MB. Imagine that withSET search_pathorSET ROLE. The client that ran it happened to see its setting 20 times out of 20 only because, alone and idle, it kept getting the same connection; under load it wouldn't. SET LOCALis safe. It lasts until the end of the transaction, and the transaction is exactly the unit PgBouncer lends. 0 of 50 clients saw it afterwards.- Session advisory locks break both ways. 460 of 600 unlocks ran on a
different server connection than their lock, failed, and left 460
locks held by connections now serving other clients, which would block
anyone wanting those keys. Use transaction-level locks
(
pg_advisory_xact_lock), which release atCOMMIT. - SQL
PREPAREfails at random. 100 of 600EXECUTEs landed on a connection without the statement, and 24PREPAREs collided with another client's statement of the same name already on the connection. - Protocol-level prepared statements work. Drivers that prepare
through the extended protocol (psycopg's
prepare_threshold, JDBC, most ORMs) had 0 errors in 600 executions: since 1.21 PgBouncer tracks them and re-prepares on whichever connection a client gets.
The first version of this lab ran the PREPARE test with a single
client, and all 20 EXECUTEs worked. Alone, the client kept getting the
same server connection. Pooling bugs only show under concurrency, which
is exactly why they reach production.
To clean up after a leak, the admin console can drop every server connection and start fresh:
psql "host=localhost port=6432 dbname=pgbouncer user=pgbouncer_admin sslmode=require" -c "RECONNECT appdb"One PgBouncer is a single point of failure, and here it also sits in
front of a single HAProxy. In production, run PgBouncer next to each
application (a sidecar or per host), or two or more behind a load
balancer. Size default_pool_size from the database's cores, not the
number of clients: the load test found the best throughput at 32 busy
connections on a 2-core primary.