Subscribe

Connection pooling for Postgres with PgBouncer

Running PgBouncer 1.26 in front of Postgres 18 in Docker: why raising max_connections isn't the fix, transaction vs session pooling, the session state that leaks between clients, prepared statements with pgx, and RDS Proxy as the managed option.

Connection pooling for Postgres with PgBouncer

Every Postgres connection is a separate server process with its own memory. That's fine for ten connections. It is not fine when you scale an app to twenty containers, each with a pool of twenty, and a cron job and a migration run on top. Sooner or later a new connection gets refused, and the first instinct is to raise max_connections.

In this blog we will put PgBouncer in front of Postgres, see why raising max_connections isn't the real fix, compare session and transaction pooling, look at what breaks in transaction mode, and get prepared statements from Go working through it. It is an intermediate post in my Postgres in production series, after zero-downtime schema changes. Versions I used: Postgres 18.7 (postgres:18-alpine), PgBouncer 1.26.1 (the edoburu/pgbouncer:v1.26.1-p0 image, as I couldn't find an image from the PgBouncer project itself), Go 1.27.3 and pgx v5.13.0.

Running out of connections

A Docker network so PgBouncer can reach Postgres by name, then Postgres and a role for the app:

docker network create pgnet
docker run -d --name pg18 --network pgnet --network-alias pg \
  -e POSTGRES_PASSWORD=secret postgres:18-alpine
docker exec pg18 psql -U postgres \
  -c "CREATE ROLE app LOGIN PASSWORD 'app-secret'" \
  -c "CREATE DATABASE shorty5 OWNER app"
docker exec pg18 pgbench -i -s 10 -q -h localhost -U app shorty5

The default max_connections is 100. pgbench ships inside the postgres image, so I asked it for 150 clients straight at Postgres:

docker exec -e PGPASSWORD=app-secret pg18 \
  pgbench -h pg -U app -c 150 -j 1 -T 5 -S shorty5
pgbench: error: connection to server at "pg" (192.168.117.2), port 5432 failed: FATAL:  remaining connection slots are reserved for roles with the SUPERUSER attribute
pgbench: error: could not create connection for client 97

Client 97 is the first one refused. 100 slots minus 3 kept for superusers (superuser_reserved_connections) is 97. My first try used -j 4 and the output also had a pile of "could not calculate client proof: OpenSSL failure" lines mixed in, which sent me looking at SCRAM for a while. With one thread only the real error was left. I'm not sure what pgbench was doing there, so just take the FATAL line as the one that matters.

You could set max_connections = 500. It works, until it doesn't. Each backend has its own memory for sorts and caches, and hundreds of mostly idle processes still cost something on every snapshot. Postgres does its best work with roughly as many active connections as it has CPU cores to run them. Most app connections sits idle between queries anyway. What you want is many client connections sharing a few real ones.

PgBouncer in transaction mode

The whole config is one ini file and a user list:

[databases]
shorty5 = host=pg port=5432 dbname=shorty5

[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
admin_users = app

pool_mode = transaction
default_pool_size = 20
max_client_conn = 1000
max_prepared_statements = 200

server_idle_timeout = 600
ignore_startup_parameters = extra_float_digits

For userlist.txt I copied the SCRAM verifier out of Postgres instead of writing a plain password into a file. PgBouncer can use it both to check the client and to log in to Postgres:

mkdir -p conf
docker exec pg18 psql -U postgres -Atc \
  "SELECT '\"' || rolname || '\" \"' || rolpassword || '\"' FROM pg_authid WHERE rolname = 'app'" \
  > conf/userlist.txt
chmod 600 conf/userlist.txt
"app" "SCRAM-SHA-256$4096:/3ef...

Then start it, mounting whole conf folder:

docker run -d --name pgbouncer --network pgnet --network-alias bouncer \
  -p 6432:6432 -v "$PWD/conf:/etc/pgbouncer:ro" edoburu/pgbouncer:v1.26.1-p0

Actually, I mounted the folder because of a small mistake. First I mounted the two files one by one and edited pgbouncer.ini with sed -i between tests. The second time I did that, RELOAD said "RELOAD failed" and inside the container the file was gone. sed -i writes a new file and renames it over the old one, and a single file bind mount keeps pointing at the old, deleted one. Folder mounts don't have that problem.

The same 150 clients, now through PgBouncer:

docker exec -e PGPASSWORD=app-secret pg18 \
  pgbench -h bouncer -p 6432 -U app -c 150 -j 4 -T 10 -S shorty5
number of clients: 150
number of transactions actually processed: 552292
number of failed transactions: 0 (0.000%)
latency average = 2.616 ms
tps = 57333.297623 (without initial connection time)

No refused clients, and Postgres only ever saw 20 connections from app. That tps number is my laptop with the whole data set in memory, don't read anything into it. The admin console shows what happens under load. I ran it in the middle of a 150 client read-write run:

docker exec -e PGPASSWORD=app-secret pg18 \
  psql -h bouncer -p 6432 -U app pgbouncer -x -c "SHOW POOLS"
database              | shorty5
user                  | app
cl_active             | 20
cl_waiting            | 130
sv_active             | 20
sv_idle               | 0
maxwait_us            | 330106
pool_mode             | transaction

20 clients have a server connection, 130 wait in line, the longest for 0.33 seconds. Waiting in PgBouncer is cheap and it's visible. cl_waiting staying above zero all day means the pool is too small or the queries are too slow, and that is the number I'd alert on.

Session vs transaction pooling

In session mode a client keeps its server connection until it disconnects. Everything works like a direct connection, but you only save the connect cost. Ten app containers with long-lived pools still hold the same number of server connections.

In transaction mode a client gets a server connection only for one transaction, then gives it back. That's where the big savings are, and also the catch. Anything that lives in the session rather than the transaction can end up on someone else's connection. I made a second entry with a pool of one so it's easy to see:

shorty5_tiny = host=pg port=5432 dbname=shorty5 pool_size=1

Client A sets a timeout and disconnects:

SET statement_timeout = '50ms';
SELECT pg_backend_pid();
 pg_backend_pid
----------------
            734

Then a completely separate client B connects:

SELECT pg_backend_pid();
 pg_backend_pid
----------------
            734
SHOW statement_timeout;
 statement_timeout
-------------------
 50ms
SELECT pg_sleep(0.2);
ERROR:  canceling statement due to statement timeout

Client B never set a timeout itself and still got killed by A's. In transaction mode PgBouncer doesn't run DISCARD ALL between clients by default. The same goes for session advisory locks, LISTEN, temp tables that outlive a transaction, and cursors WITH HOLD.

The fix is to keep settings inside the transaction with SET LOCAL:

BEGIN;
SET LOCAL statement_timeout = '50ms';
SELECT pg_sleep(0.2);
ERROR:  canceling statement due to statement timeout
ROLLBACK;
SHOW statement_timeout;
 statement_timeout
-------------------
 0

Or set it per role on the server, ALTER ROLE app SET statement_timeout = '5s', so every connection starts with it. Newer PgBouncer versions do track some parameters for you (1.26 added search_path to the tracked list by default) but I wouldn't depend on that for anything else.

Prepared statements and pgx

pgx by default prepares each query once per connection and caches it. In transaction mode the next transaction may run on another server connection where that statement doesn't exist. PgBouncer 1.21 added tracking for protocol level prepared statements and since 1.24 it's on by default with max_prepared_statements = 200. To see what it saves you, I set it to 0 and ran a small Go program: 50 goroutines, 200 lookups each, through PgBouncer.

cfg, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil {
    log.Fatal(err)
}
cfg.MaxConns = 50
if os.Getenv("SIMPLE") == "1" {
    // for PgBouncer older than 1.21, or max_prepared_statements = 0
    cfg.ConnConfig.DefaultQueryExecMode = pgx.QueryExecModeSimpleProtocol
}
pool, err := pgxpool.NewWithConfig(ctx, cfg)
max_prepared_statements = 0
mode=cache statement ok=2931 failed=7069
first error: ERROR: prepared statement "stmtcache_1231e781d3e65bf00b1d4b7680a39eacb8f7243fbdb51bad" does not exist (SQLSTATE 26000)
mode=simple protocol ok=10000 failed=0

max_prepared_statements = 200
mode=cache statement ok=10000 failed=0
mode=simple protocol ok=10000 failed=0

70% failed with support off. pgbench in -M prepared mode failed the same way, with "prepared statement "P_0" does not exist" and "already exists" errors. With the default setting everything worked. SHOW STATS after the Go run had total_client_parse_count 50 and total_server_parse_count 20: fifty client connections prepared the query, PgBouncer prepared it once on each of its twenty server connections.

So basically, on a current PgBouncer, keep pgx's default mode. On an old one, use QueryExecModeSimpleProtocol or QueryExecModeExec. The pool settings themselves are in talking to Postgres from Go with pgx and sqlc, shorty uses DB_MAX_CONNS=10 per instance.

Sizing it

I start with default_pool_size near the number of CPU cores on the database, times two or so, and leave headroom under max_connections for migrations, psql and monitoring. Then max_client_conn can be as large as you like. App pools can stay at their normal size, and the app should still have a query timeout so a slow query gives up instead of holding a server slot. Designing for failure goes into those timeouts.

RDS Proxy as the managed option

On RDS you can use RDS Proxy instead of running PgBouncer yourself. It also multiplexes per transaction, plus it handles failover and can use IAM auth and Secrets Manager. But it is quite a bit stricter. For Postgres it "pins" a client to one server connection for the rest of the session on any SET, on PREPARE/EXECUTE, temp tables, LISTEN, session advisory locks and even nextval. A pinned client gets no pooling benefit. The DatabaseConnectionsCurrentlySessionPinned metric in CloudWatch tells you how often it happens. If most of your sessions pin, PgBouncer on a small instance may serve you better.

To clean up: docker rm -f pgbouncer pg18 and docker network rm pgnet.