Databases · Advanced · 24 min
Pool PostgreSQL connections with PgBouncer
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7 · PgBouncer 1.26.1 (PGDG apt)
You will put PgBouncer 1.26 in front of PostgreSQL 18 with SCRAM authentication through an auth_query, run 500 pgbench clients that PostgreSQL alone refuses, and know which features transaction pooling breaks and how to work around them.
On this page
Every PostgreSQL connection is a separate server process with its own memory. A hundred of them is normal; a thousand gets expensive, and past max_connections (100 by default) the server refuses new ones outright. Applications hit that limit sooner than people expect: each web worker keeps its own pool, autoscaling adds more workers, and short-lived scripts open a fresh connection for every request.
PgBouncer sits between the applications and PostgreSQL. Clients connect to PgBouncer, which can accept hundreds or thousands of them, and it hands each one a PostgreSQL connection only while that client needs one. In this tutorial you build a practice database, watch PostgreSQL refuse 500 clients, then put PgBouncer 1.26 in front of it. You set up SCRAM authentication that reads password secrets from PostgreSQL through an auth_query, so there is no file listing every user's password. You switch from session to transaction pooling, see what transaction pooling breaks, and finish by comparing pgbench numbers with and without the pooler.
You need PostgreSQL 18 from the PGDG repository, installed as in /tutorials/install-postgresql-18-on-ubuntu-26-04. PostgreSQL 19.0 was released on 19 November 2026; PgBouncer and the steps here should work the same with it, though they were checked on 18.
If you run on a small VPS to keep hosting costs down, pooling is often the cheapest upgrade you can make: a 1 or 2 GB server that would struggle with 300 PostgreSQL processes can serve 300 app connections through 20.
Step 1 · Create a practice database and an app role
Create a login role pooldemo_app and a database pooldemo it owns. The password is generated, sent to psql on standard input and saved straight into your ~/.pgpass, so it never appears in your shell history or in the process list. Every later psql and pgbench command reads it from there.
PGPW="$(openssl rand -hex 24)"
printf "CREATE ROLE pooldemo_app LOGIN PASSWORD '%s';\n" "$PGPW" | sudo -u postgres psql -X -v ON_ERROR_STOP=1
sudo -u postgres createdb -O pooldemo_app pooldemo
[ -e ~/.pgpass ] || install -m 600 /dev/null ~/.pgpass
printf '127.0.0.1:*:*:pooldemo_app:%s\n' "$PGPW" >> ~/.pgpass
unset PGPWThe .pgpass line matches any port and any database name for pooldemo_app on 127.0.0.1, which covers PostgreSQL on 5432 and PgBouncer on 6432. If you prefer to type a password, run sudo -u postgres psql -c '\password pooldemo_app' instead and add the line to ~/.pgpass by hand.
Now load the standard pgbench tables at scale 10, one million rows in pgbench_accounts:
pgbench -i -s 10 -h 127.0.0.1 -U pooldemo_app pooldemoIt takes a few seconds and ends with a line that starts done in.
Check it worked
psql -h 127.0.0.1 -U pooldemo_app -d pooldemo -Atc "SELECT count(*) FROM pgbench_accounts;"The answer is 1000000. You connected over TCP with a password and were not prompted, so the .pgpass entry works.
Step 2 · Hit the max_connections limit
Ask pgbench for 500 clients for 10 seconds of read-only (-S) traffic, straight at PostgreSQL:
pgbench -h 127.0.0.1 -U pooldemo_app -c 500 -j 4 -T 10 -S pooldemopgbench opens all its connections before it starts the clock, and it stops partway with something like this (the client number varies from run to run):
pgbench: error: connection to server at "127.0.0.1", port 5432 failed: FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute
pgbench: error: could not create connection for client 97Check the limit itself:
sudo -u postgres psql -Atc "SHOW max_connections;"It prints 100, and three of those are kept for superusers (superuser_reserved_connections), so an ordinary role gets 97, and the 98th connection is the one refused with the reserved-slots message. You could raise max_connections, but each extra connection is another process holding memory and taking part in locking and snapshot work, and it needs a restart. Pooling is the better fix.
Record two baselines that do fit. The first keeps 50 connections open for the whole run. The second adds -C, which opens a new connection for every transaction, the way a PHP request or a serverless function often does:
pgbench -h 127.0.0.1 -U pooldemo_app -c 50 -j 4 -T 10 -S pooldemo
pgbench -h 127.0.0.1 -U pooldemo_app -c 50 -j 4 -T 10 -S -C pooldemoWrite down the tps = ... line from each run, and the average connection time from the second. The -C figure is far lower than the first: most of each transaction's time goes on starting a server process and checking the password, not on the query.
Check it worked
The 500-client run stopped with remaining connection slots are reserved for roles with the SUPERUSER attribute, and you have two tps numbers on paper: persistent connections and a new connection per transaction.
Step 3 · Install PgBouncer and an auth lookup function
PgBouncer is in the PGDG repository you added when you installed PostgreSQL, and that build tracks upstream releases.
sudo apt-get update
sudo apt-get install -y pgbouncer
pgbouncer --versionThe first line reads PgBouncer 1.26.1 or a later 1.26 release. The package runs PgBouncer as the postgres system user, keeps its configuration in /etc/pgbouncer/ and installs a pgbouncer systemd service.
PgBouncer has to check each client's password before it lets the client in. The old way is a userlist.txt holding every user's password or hash, which you then keep in step with PostgreSQL by hand. The better way is auth_query: PgBouncer logs in as one small role and asks PostgreSQL for the user's SCRAM secret when the user connects.
Reading secrets needs access to pg_authid, which only superusers have. Do not give PgBouncer a superuser. Instead, create a function owned by postgres that runs with its owner's rights (SECURITY DEFINER), returns one user's secret, refuses superusers and expired passwords, and can be called only by a dedicated pgbouncer_auth role. auth_query runs in the database the client asked for, so the function goes into pooldemo; add it to each database you put behind PgBouncer.
sudo -u postgres psql -X -v ON_ERROR_STOP=1 -d pooldemo <<'SQL'
CREATE ROLE pgbouncer_auth LOGIN;
CREATE SCHEMA pgbouncer;
REVOKE ALL ON SCHEMA pgbouncer FROM PUBLIC;
GRANT USAGE ON SCHEMA pgbouncer TO pgbouncer_auth;
CREATE FUNCTION pgbouncer.get_auth(p_usename text)
RETURNS TABLE (usename name, passwd text)
LANGUAGE sql
SECURITY DEFINER
SET search_path = pg_catalog
AS $$
SELECT rolname,
CASE WHEN rolvaliduntil < now() THEN NULL ELSE rolpassword END
FROM pg_catalog.pg_authid
WHERE rolname = p_usename
AND rolcanlogin
AND NOT rolsuper;
$$;
REVOKE ALL ON FUNCTION pgbouncer.get_auth(text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION pgbouncer.get_auth(text) TO pgbouncer_auth;
SQLSET search_path = pg_catalog stops anyone from planting a look-alike table that the function would read instead, and the query PgBouncer runs will name the schema in full for the same reason. PgBouncer 1.25.1 fixed a vulnerability that depended on an auth_query without schema-qualified names.
pgbouncer_auth itself still needs a password, and it is the one password PgBouncer keeps in a file. It must be plain text: PgBouncer uses it to log in to PostgreSQL, and a SCRAM secret cannot be turned back into a login. The warning comes first: the next command replaces any existing /etc/pgbouncer/userlist.txt with an empty file. It creates the file private (mode 640, owner postgres) before anything is written to it.
sudo install -m 640 -o postgres -g postgres /dev/null /etc/pgbouncer/userlist.txt
AUTHPW="$(openssl rand -hex 24)"
printf "ALTER ROLE pgbouncer_auth PASSWORD '%s';\n" "$AUTHPW" | sudo -u postgres psql -X -v ON_ERROR_STOP=1
printf '"pgbouncer_auth" "%s"\n' "$AUTHPW" | sudo tee /etc/pgbouncer/userlist.txt > /dev/null
unset AUTHPWCheck it worked
Call the function as pgbouncer_auth for the app role and for postgres:
sudo -u postgres psql -X -d pooldemo -c "SET ROLE pgbouncer_auth; SELECT usename, left(passwd, 14) AS secret_starts FROM pgbouncer.get_auth('pooldemo_app');"
sudo -u postgres psql -X -d pooldemo -c "SET ROLE pgbouncer_auth; SELECT count(*) FROM pgbouncer.get_auth('postgres');"The first returns one row, pooldemo_app with a secret starting SCRAM-SHA-256$. The second returns 0: superusers cannot log in through PgBouncer. sudo ls -l /etc/pgbouncer/userlist.txt shows -rw-r----- 1 postgres postgres.
Step 4 · Configure PgBouncer in session mode
Keep a copy of the packaged configuration, then replace it. The tee command below overwrites /etc/pgbouncer/pgbouncer.ini completely.
sudo cp /etc/pgbouncer/pgbouncer.ini /etc/pgbouncer/pgbouncer.ini.orig
sudo tee /etc/pgbouncer/pgbouncer.ini > /dev/null <<'EOF'
[databases]
pooldemo = host=127.0.0.1 port=5432 dbname=pooldemo
[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
unix_socket_dir = /var/run/postgresql
logfile = /var/log/postgresql/pgbouncer.log
pidfile = /var/run/postgresql/pgbouncer.pid
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
auth_user = pgbouncer_auth
auth_query = SELECT usename, passwd FROM pgbouncer.get_auth($1)
pool_mode = session
max_client_conn = 600
default_pool_size = 20
max_prepared_statements = 200
EOFWhat the settings do:
[databases]maps the name clients ask for to a PostgreSQL server and database. The entry has nouser=, so PgBouncer logs in to PostgreSQL as whoever logged in to it. With SCRAM that works only because the client authenticated with SCRAM and PgBouncer holds the same secret PostgreSQL has, whichauth_queryguarantees.listen_addr = 127.0.0.1keeps PgBouncer local to this server. Open it to your app servers later with the same care as PostgreSQL itself.auth_type = scram-sha-256makes clients prove their password with SCRAM.auth_userandauth_querylook up anyone not listed inauth_file, which here is everyone exceptpgbouncer_auth.pool_mode = sessiongives a client one server connection from login until it disconnects. It is the safe default: everything behaves exactly as with a direct connection.default_pool_size = 20caps server connections per database and user pair.max_client_conn = 600caps client connections to PgBouncer as a whole. Each client uses a file descriptor, so if you raisemax_client_connpast about 1,000, raise the service's open-file limit too.
Restart PgBouncer to load the file, then check the service:
sudo systemctl restart pgbouncer
sudo systemctl status pgbouncer --no-pagerThe status shows active (running). If it does not, the last lines of /var/log/postgresql/pgbouncer.log name the setting it disliked.
Check it worked
Connect through port 6432 and ask the server who you are and which port it answered on:
psql -h 127.0.0.1 -p 6432 -U pooldemo_app -d pooldemo -c "SELECT current_user, inet_server_port();"You get pooldemo_app and 5432: you talked to PgBouncer, and PostgreSQL ran the query. Now open PgBouncer's admin console. The user pgbouncer can log in without a password over the Unix socket when the client runs as the same system user as PgBouncer, which is postgres:
sudo -u postgres psql -h /var/run/postgresql -p 6432 -U pgbouncer pgbouncer -c "SHOW POOLS;"There is a row for pooldemo with user pooldemo_app, one for the pgbouncer_auth lookups, and one for the console itself. sv_idle on the pooldemo_app row is 1: the server connection your query used is kept open for the next client, and pool_mode reads session.
Step 5 · Switch to transaction pooling and run 500 clients
In session mode, 20 server connections means at most 20 connected clients at a time, and the 21st waits until one disconnects. That suits apps that already keep a small pool of long-lived connections. It does nothing for 500 clients that each hold a connection open.
Transaction mode returns the server connection to the pool as soon as each transaction ends. Between transactions a client holds nothing, so 500 mostly idle clients can share 20 server connections. Rewrite the configuration with pool_mode = transaction, and add a second database name, pooldemo_session, that points at the same database but keeps session pooling for the clients that need it (you will use it in the next step). As before, this replaces the whole file.
sudo tee /etc/pgbouncer/pgbouncer.ini > /dev/null <<'EOF'
[databases]
pooldemo = host=127.0.0.1 port=5432 dbname=pooldemo
pooldemo_session = host=127.0.0.1 port=5432 dbname=pooldemo pool_mode=session
[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
unix_socket_dir = /var/run/postgresql
logfile = /var/log/postgresql/pgbouncer.log
pidfile = /var/run/postgresql/pgbouncer.pid
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
auth_user = pgbouncer_auth
auth_query = SELECT usename, passwd FROM pgbouncer.get_auth($1)
pool_mode = transaction
max_client_conn = 600
default_pool_size = 20
max_prepared_statements = 200
EOFsudo systemctl restart pgbouncerRun the same 500-client test that PostgreSQL refused, this time against port 6432, for 20 seconds:
pgbench -h 127.0.0.1 -p 6432 -U pooldemo_app -c 500 -j 4 -T 20 -S pooldemoWhile it runs, open a second terminal and look at the pools:
sudo -u postgres psql -h /var/run/postgresql -p 6432 -U pgbouncer pgbouncer -c "SHOW POOLS;"On the pooldemo_app row, cl_active plus cl_waiting is about 500 and sv_active plus sv_idle is at most 20. cl_waiting counts clients that sent a query and are queued for a free server connection, and maxwait says how long the oldest has waited, in seconds. A maxwait that keeps climbing on a real system means the pool is too small for the load, or a slow query is holding connections.
PostgreSQL agrees. In the second terminal, count the server processes for the app role:
sudo -u postgres psql -Atc "SELECT count(*) FROM pg_stat_activity WHERE usename = 'pooldemo_app';"The count is 20 or fewer.
Check it worked
Back in the first terminal, pgbench finishes with number of clients: 500, number of failed transactions: 0 (0.000%) and a tps figure. Note it next to your baselines.
Step 6 · Work around what transaction pooling breaks
In transaction mode, consecutive transactions from one client can run on different server connections, and one server connection serves many clients. Anything that lives in the session, rather than in one transaction, leaks between clients or gets lost. PgBouncer does not reject these statements; it passes them on, and the damage is quiet.
See it with a setting. One client sets a statement timeout outside a transaction and disconnects; a second client then checks the setting:
psql -h 127.0.0.1 -p 6432 -U pooldemo_app -d pooldemo -c "SET statement_timeout = '5s';"
psql -h 127.0.0.1 -p 6432 -U pooldemo_app -d pooldemo -c "SHOW statement_timeout;"The second client most likely sees 5s, a setting it never asked for, because PgBouncer reuses the most recently released server connection first. In session mode PgBouncer runs DISCARD ALL when a client leaves; in transaction mode it does not. Clear the leftover state by asking PgBouncer to replace its server connections for that database:
sudo -u postgres psql -h /var/run/postgresql -p 6432 -U pgbouncer pgbouncer -c "RECONNECT pooldemo;"The features to avoid through a transaction-mode pool, and what to use instead:
SETandRESET: useSET LOCALinside a transaction, which ends with the transaction, or give the role a default withALTER ROLE pooldemo_app SET statement_timeout = '5s', which every new server connection picks up.- Session advisory locks (
pg_advisory_lock): the lock stays on a server connection that the next client inherits. Usepg_advisory_xact_lock, which is released at commit or rollback. LISTEN: notifications go to whichever client holds that server connection next, or nobody. Run listeners through a session-mode entry or directly against PostgreSQL.NOTIFYis fine.- SQL-level
PREPARE,EXECUTEandDEALLOCATE,WITH HOLDcursors, temporary tables that outlive a transaction andLOAD: same problem, same answer.
The pooldemo_session entry is the escape hatch. Clients that connect to that name get session pooling against the same database, so a background worker that uses LISTEN keeps working while the web app uses transaction mode:
psql -h 127.0.0.1 -p 6432 -U pooldemo_app -d pooldemo_session -c "LISTEN order_events;"
sudo -u postgres psql -h /var/run/postgresql -p 6432 -U pgbouncer pgbouncer -c "SHOW DATABASES;"Check it worked
LISTEN replies LISTEN. In SHOW DATABASES, the pool_mode column is session for pooldemo_session and empty for pooldemo, which means it uses the global transaction setting.
Step 7 · Keep prepared statements working
Most drivers (psycopg 3, JDBC, Go's pgx, node-postgres with named queries) prepare statements at the protocol level: they send a parse message once and then execute it by name. Before PgBouncer 1.21 that broke in transaction mode, because the next execute could land on a server connection that had never seen the parse. With max_prepared_statements above zero, PgBouncer tracks each client's prepared statements and prepares them on whichever server connection the client gets. The default has been 200 since 1.24, and your configuration sets it explicitly so the intent is visible.
pgbench's -M prepared mode uses exactly this protocol. Run it through the transaction pool:
pgbench -h 127.0.0.1 -p 6432 -U pooldemo_app -c 100 -j 4 -T 10 -S -M prepared pooldemoIt reports number of failed transactions: 0 and usually a higher tps than the plain run, because the server parses and plans each query once per connection rather than for every call. With max_prepared_statements = 0 the same command should fail within seconds with an error such as prepared statement "P_0" does not exist (or already exists, because every pgbench client uses the same statement names).
This support covers protocol-level statements only. A SQL PREPARE typed by an application is still passed straight to whatever server connection is current, and is still on the list of things to avoid.
Check it worked
pgbench exits without errors, and the summary shows query mode: prepared and zero failed transactions.
Step 8 · Compare the numbers before and after
You already have the direct baselines. Run the matching tests through PgBouncer:
pgbench -h 127.0.0.1 -p 6432 -U pooldemo_app -c 50 -j 4 -T 10 -S pooldemo
pgbench -h 127.0.0.1 -p 6432 -U pooldemo_app -c 50 -j 4 -T 10 -S -C pooldemoPut the tps figures side by side:
Test Direct (5432) PgBouncer (6432)
50 clients, persistent connections your number your number
50 clients, new connection each time your number your number
500 clients, persistent connections refused your numberHow to read them:
- Persistent connections: about the same, or a little slower through PgBouncer, because every query takes an extra hop. A pooler does not make queries faster.
- New connection each time: PgBouncer is usually well ahead. A new client connection to PgBouncer costs a password check in an already-running process; a new connection to PostgreSQL also starts a server process.
- 500 clients: the direct run did not happen at all. Through PgBouncer it completed with 20 server connections. That is the result that matters.
Use the numbers to size the pool. A good starting default_pool_size is a small multiple of the server's CPU cores; adding server connections past the point where CPU or disk is busy only adds queueing inside PostgreSQL instead of inside PgBouncer.
Check it worked
Your table has five numbers and one "refused", and the 500-client PgBouncer run had zero failed transactions.
Step 9 · Remove the practice setup
When you are done, remove what this tutorial created. The commands below stop PgBouncer, delete the pooldemo database (including the auth function inside it) and both roles, remove the pooldemo_app line from ~/.pgpass and leave any other lines in place, and purge the PgBouncer package with its whole /etc/pgbouncer directory. Skip the last group if you want to keep PgBouncer for your own databases.
sudo systemctl stop pgbouncersudo -u postgres dropdb pooldemo
sudo -u postgres dropuser pooldemo_app
sudo -u postgres dropuser pgbouncer_auth
(umask 077 && awk '!/^127\.0\.0\.1:\*:\*:pooldemo_app:/' ~/.pgpass > ~/.pgpass.new) && mv ~/.pgpass.new ~/.pgpasssudo apt-get purge -y pgbouncer
sudo rm -rf /etc/pgbouncer
sudo rm -f /var/log/postgresql/pgbouncer.logCheck it worked
sudo -u postgres psql -Atc "SELECT count(*) FROM pg_roles WHERE rolname IN ('pooldemo_app', 'pgbouncer_auth');"It prints 0, sudo -u postgres psql -l no longer lists pooldemo, and grep -c pooldemo_app ~/.pgpass prints 0.
Next steps
- Make sure the queries going through the pool are fast in the first place:
/tutorials/speed-up-slow-postgres-queries-with-explain. - Connect an application through PgBouncer with a driver that uses protocol-level prepared statements:
/tutorials/connect-to-postgresql-from-python-with-psycopg. - Start again from a clean server:
/tutorials/install-postgresql-18-on-ubuntu-26-04.
Related tutorials
- How to Install PostgreSQL 18 on Ubuntu 26.04 and Create Your First DatabaseYou will install PostgreSQL 18 from the official PostgreSQL apt repository, create a database and a user for your app, and connect to it with a password.
- How to Find and Fix Slow PostgreSQL Queries with EXPLAIN ANALYZEYou will read a PostgreSQL 18 query plan, add an index that turns a 40 ms table scan into a 0.2 ms lookup, and use pg_stat_statements to find which queries deserve that effort.
- Connect to PostgreSQL from Python with psycopg 3You will connect a Python 3.15 project to PostgreSQL 18 with psycopg 3.3, run parameterised queries, shape rows as dicts and dataclasses, group writes in transactions, load 100,000 rows with COPY, stream large results, share connections with a pool and handle errors by SQLSTATE.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials