PgBouncer is a connection pooler for PostgreSQL: a small proxy that accepts many client connections and serves them from a short list of real database connections. You need one when your application opens more connections than the database can hold. PostgreSQL starts a separate backend process for every connection, and it refuses new ones once max_connections is reached. The steps below install PgBouncer on the database host, set it to transaction pooling, and size the pools. A later section covers an application that runs on several replicas, with a connection pool in each one.
How to verify
Open PgBouncer’s admin console. The user name pgbouncer is let in without a password when you connect through the Unix socket from the same Unix account that runs the PgBouncer process. Find that account with ps -o user= -C pgbouncer. The command below assumes it is postgres and that the socket directory is /var/run/postgresql, as set in step 3.
sudo -u postgres psql -h /var/run/postgresql -p 6432 -U pgbouncer pgbouncer
-- Current pools and their state
SHOW POOLS;
-- Per-database aggregate stats
SHOW STATS;
-- Active client and server connections
SHOW CLIENTS;
SHOW SERVERS;
-- Configuration in effect
SHOW CONFIG;
SHOW POOLS prints one row per database and user pair. Three columns tell you whether the pool is large enough:
cl_activecounts client connections that are linked to a server connection, or that are idle with nothing waiting.cl_waitingcounts clients that have sent a query and have not been given a server connection yet.maxwaitis how long, in seconds, the oldest client in the queue has waited.
A cl_waiting above zero for a moment is normal under a burst. A maxwait that keeps growing means the queries are slow or the pool is too small. In SHOW STATS, avg_wait_time gives the same signal as an average, in microseconds.
What’s happening
PgBouncer accepts client connections on its own port (6432 by default) and forwards them to PostgreSQL on 5432. It keeps one pool of server connections for each database and user pair. When a client needs the database, PgBouncer hands it an idle server connection from that pool, or makes it wait until one is free.
The pool mode decides when a server connection goes back to the pool:
- Session mode is the default. A client keeps its server connection until it disconnects. Every PostgreSQL feature works, but there is no sharing. PgBouncer only caps the number of server connections.
- Transaction mode gives a client a server connection for one transaction, then takes it back. Many clients can share a few server connections. Features that depend on session state stop working, which the pitfalls section lists.
- Statement mode returns the server connection after every statement, so transactions with more than one statement are refused. It is rarely the right choice.
Transaction mode is the usual choice for web applications, because most of their connections sit idle between requests.
As of November 2026, the current stable release is PgBouncer 1.26.1, published on 2026-10-14. It fixes three security issues that affect 1.26.0 and earlier releases. Your distribution’s package may be older, so check the installed version with pgbouncer --version after step 1.
The procedure
-
Install PgBouncer.
sudo apt update sudo apt install -y pgbouncer pgbouncer --versionThe last command prints the version. Note it, because step 8 depends on it.
-
Create a
userlist.txtthat holds each application user and its SCRAM secret, the salted hash PostgreSQL stores in place of the password. PgBouncer uses it to check the client’s password, and to log in to PostgreSQL as that user.# Copy the stored SCRAM secret from PostgreSQL for each user sudo -u postgres psql -At -c "SELECT '\"' || rolname || '\" \"' || rolpassword || '\"' \ FROM pg_authid WHERE rolname = 'orderapp';" \ | sudo tee -a /etc/pgbouncer/userlist.txtThe line written to the file should look like
"orderapp" "SCRAM-SHA-256$4096:.... If the second field starts withmd5, the role still has an MD5 password. Set the password again withpassword_encryption = scram-sha-256in PostgreSQL, then export it again. -
Configure
/etc/pgbouncer/pgbouncer.ini. This example assumes PgBouncer and PostgreSQL share a host, and that applications reach it at 10.0.0.5.[databases] orders = host=127.0.0.1 port=5432 dbname=orders reports = host=127.0.0.1 port=5432 dbname=reports [pgbouncer] listen_addr = 10.0.0.5 listen_port = 6432 unix_socket_dir = /var/run/postgresql auth_type = scram-sha-256 auth_file = /etc/pgbouncer/userlist.txt admin_users = postgres stats_users = pgmonitor pool_mode = transaction max_client_conn = 2000 default_pool_size = 35 reserve_pool_size = 5 reserve_pool_timeout = 3 server_idle_timeout = 600 server_lifetime = 3600 query_wait_timeout = 30 client_idle_timeout = 0 log_connections = 1 log_disconnections = 1 log_pooler_errors = 1admin_usersandstats_usersname the accounts that may open the admin console over the network. Each one needs its own line inuserlist.txt. Do not put a user name in the[databases]lines: PgBouncer can only reuse a SCRAM secret to log in to PostgreSQL when the database definition has no forced user.This example carries no TLS (Transport Layer Security) settings, so traffic between the application and PgBouncer is not encrypted. To encrypt it, set
client_tls_sslmode,client_tls_key_fileandclient_tls_cert_file. If PostgreSQL runs on another host, also setserver_tls_sslmode = verify-fullandserver_tls_ca_file. -
Restrict the file permissions. Both files must be readable by the account that runs PgBouncer, which you found with
psearlier.sudo chown postgres:postgres /etc/pgbouncer/pgbouncer.ini /etc/pgbouncer/userlist.txt sudo chmod 640 /etc/pgbouncer/pgbouncer.ini /etc/pgbouncer/userlist.txt -
Start and enable the service.
sudo systemctl enable --now pgbouncer sudo systemctl status pgbouncer --no-pagerThe status should read
active (running). If it does not, readjournalctl -u pgbouncer. A typing mistake inpgbouncer.iniis the usual cause. -
Point the application at PgBouncer. Change the port in the connection string from 5432 to 6432.
postgresql://orderapp:strong-password@10.0.0.5:6432/orders -
Set
default_pool_sizefrom the PostgreSQL limit.default_pool_sizeis the maximum number of server connections for one database and user pair, and its default is 20.reserve_pool_sizeadds a few more that PgBouncer opens only when a client has waited longer thanreserve_pool_timeout. The most PgBouncer can open is therefore the number of pairs multiplied by the sum of the two settings. That total must fit undermax_connections, after you set aside the connections that bypass the pooler.Example sizing: PostgreSQL max_connections = 100 (the usual default) superuser_reserved_connections = 3 (the default) Kept for direct connections = 17 (admin sessions, backups, monitoring) Budget for PgBouncer = 80 Two (database, user) pairs: orders+orderapp, reports+reportapp Per pair: default_pool_size 35 + reserve_pool_size 5 = 40 Total: 2 x 40 = 80For a hard ceiling that does not depend on how many users connect, set
max_db_connections. It limits server connections per database across all users. -
Check prepared statements. A prepared statement is a query the driver sends once and then runs many times by name, and it lives on one server connection. In transaction mode the next transaction may land on a different server connection. Since version 1.21, PgBouncer tracks these statements and prepares them again where needed, as long as
max_prepared_statementsis above zero. From 1.24 on its default is 200, so there is nothing to change. On 1.21 to 1.23 the default is 0, so addmax_prepared_statements = 200to the[pgbouncer]section.On a version older than 1.21, turn prepared statements off in the driver instead:
- JDBC (the Java database driver): add
prepareThreshold=0to the connection string. - Psycopg 3 (Python): set
prepare_threshold=Noneon the connection. - PHP with PDO: set
PDO::ATTR_EMULATE_PREPAREStotrue.
Without one of the two, queries fail at random with “prepared statement does not exist”.
- JDBC (the Java database driver): add
-
Apply a configuration change without dropping clients.
sudo -u postgres psql -h /var/run/postgresql -p 6432 -U pgbouncer pgbouncer -c "RELOAD;"RELOADreadspgbouncer.inianduserlist.txtagain. The command printsRELOADwhen it succeeds.
Size the pools when the application runs on several replicas
A pool inside the application looks small until you multiply it. Take an application that runs on 8 replicas (copies of the application, each in its own container or virtual machine). Each replica starts 4 worker processes, and each worker keeps a pool of 20 connections. Together they can open 8 x 4 x 20 = 640 connections. Sent directly to a PostgreSQL server with max_connections = 100, most of them are refused with FATAL: sorry, too many clients already.
Raising max_connections to 640 treats the symptom. Each of those connections is a backend process, and most would sit idle. First, see where the connections come from. Run this on PostgreSQL:
SELECT client_addr, state, COUNT(*)
FROM pg_stat_activity
GROUP BY client_addr, state
ORDER BY 3 DESC;
Without a pooler you get a few rows per replica address, and the idle counts are often far larger than the active ones. That idle count is what a pooler removes. Where you place PgBouncer changes the arithmetic.
One shared PgBouncer in front of the database. Every replica connects to the same PgBouncer. PostgreSQL only sees the pools from step 7, at most 80 connections in the example, however many replicas exist. The number that must grow is max_client_conn, PgBouncer’s limit on client connections. Its default is 100. Set it above this product, counted at the largest replica count your autoscaling allows:
max_client_conn > replicas_max x workers_per_replica x application_pool_size
Example: 8 x 4 x 20 = 640, so max_client_conn = 2000 leaves room to grow
One PgBouncer beside each replica. Some teams run PgBouncer as a sidecar, a helper process started next to every copy of the application. Each PgBouncer then keeps its own pools, so the multiplication comes back on the server side:
server connections = replicas_max x pairs x (default_pool_size + reserve_pool_size)
Example: budget of 80, 8 replicas, 1 pair
80 / 8 = 10 per replica -> default_pool_size = 8, reserve_pool_size = 2
Use the maximum replica count here, not today’s. If autoscaling can reach 16 replicas, the same budget gives 5 connections per replica. When that number gets too small to be useful, move to one shared PgBouncer.
In both layouts, reduce the pool inside the application as well. A worker that handles one request at a time uses one connection at a time, so a pool of 20 per worker mostly holds idle connections.
The article on connection limit ceilings on PaaS database nodes explains how to find the real limit when you do not control max_connections yourself.
Common pitfalls
- Session features in transaction mode.
SET,LISTEN, session-level advisory locks,WITH HOLDcursors and SQL-levelPREPAREdo not work in transaction mode.NOTIFYdoes. For a client that needs them, add a second entry under[databases]withpool_mode=session, or connect that client directly to PostgreSQL. - SQL-level
PREPAREandEXECUTE. The tracking from step 8 covers statements prepared through the driver’s protocol calls only. Statements prepared with SQL commands are passed straight through and are not tracked. server_reset_queryis skipped. The reset query (DISCARD ALLby default) runs only in session mode. In transaction mode, anything a transaction leaves on the session stays there for the next client.max_client_connand file descriptors. Each connection uses a file descriptor, the handle the operating system gives a process for every open socket. The documented upper bound ismax_client_connplus the pool size multiplied by databases and users. For the example that is2000 + 40 x 2 x 2 = 2160. Check the limit of the running process withgrep 'open files' /proc/$(pidof pgbouncer)/limits.userlist.txtgoes stale. When a password changes in PostgreSQL, export the secret again and runRELOAD. To avoid the file, setauth_userand let PgBouncer look secrets up withauth_query.server_lifetime = 0does not mean “forever”. It makes PgBouncer close each server connection after a single use. Keep the default of 3600 seconds so connections are recycled once an hour.query_wait_timeout. A client that waits longer than this for a server connection is disconnected. The default is 120 seconds. The example uses 30 so that a full pool shows up as an error in the application quickly.
The PgBouncer configuration reference documents every setting used here, and the PostgreSQL manual covers max_connections and the reserved slots. For the limits of transaction mode in more depth, see PgBouncer transaction-pool mode for PostgreSQL.
If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.