Learn Labs
Replication & Scaling

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.

[databases]appdb = host=haproxy port=5000 dbname=appdbthe primary, through HAProxyappdb_ro = host=haproxy port=5001 dbname=appdbthe replicas[pgbouncer]pool_mode = transactiona server connection per transaction, not per clientmax_client_conn = 2000default_pool_size = 20server connections per (database, user)server_login_retry = 1default 15: see the failover drillmax_prepared_statements = 200protocol-level prepared statements (1.21+)auth_type = scram-sha-256auth_query = SELECT usename, passwd FROM pgbouncer.get_auth($1)

Two choices in this config are worth explaining:

  • auth_query instead of a password file. PgBouncer looks up each user's SCRAM hash in Postgres through a SECURITY DEFINER function 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 returns postgres.
  • 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
the client doesworks?30 clientssafe for others?no leaks or straysSET work_mem (session)!!SET LOCAL in a transaction✓✓pg_advisory_lock / unlock✗!SQL PREPARE / EXECUTE✗✓protocol prepared statements✓✓
  • A session SET leaks to strangers. The SET stayed on the server connection it ran on, and 33 queries from other clients that later borrowed that connection ran with work_mem = 77MB. Imagine that with SET search_path or SET 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 LOCAL is 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 at COMMIT.
  • SQL PREPARE fails at random. 100 of 600 EXECUTEs landed on a connection without the statement, and 24 PREPAREs 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.

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"

On this page