Skip to content

PgBouncer connection pooling for PostgreSQL

Install PgBouncer in front of PostgreSQL, choose a pool mode, and size the pools so an application running on several replicas stays under max_connections.

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_active counts client connections that are linked to a server connection, or that are idle with nothing waiting.
  • cl_waiting counts clients that have sent a query and have not been given a server connection yet.
  • maxwait is 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

  1. Install PgBouncer.

    sudo apt update
    sudo apt install -y pgbouncer
    pgbouncer --version

    The last command prints the version. Note it, because step 8 depends on it.

  2. Create a userlist.txt that 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.txt

    The line written to the file should look like "orderapp" "SCRAM-SHA-256$4096:.... If the second field starts with md5, the role still has an MD5 password. Set the password again with password_encryption = scram-sha-256 in PostgreSQL, then export it again.

  3. 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      = 1

    admin_users and stats_users name the accounts that may open the admin console over the network. Each one needs its own line in userlist.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_file and client_tls_cert_file. If PostgreSQL runs on another host, also set server_tls_sslmode = verify-full and server_tls_ca_file.

  4. Restrict the file permissions. Both files must be readable by the account that runs PgBouncer, which you found with ps earlier.

    sudo chown postgres:postgres /etc/pgbouncer/pgbouncer.ini /etc/pgbouncer/userlist.txt
    sudo chmod 640 /etc/pgbouncer/pgbouncer.ini /etc/pgbouncer/userlist.txt
  5. Start and enable the service.

    sudo systemctl enable --now pgbouncer
    sudo systemctl status pgbouncer --no-pager

    The status should read active (running). If it does not, read journalctl -u pgbouncer. A typing mistake in pgbouncer.ini is the usual cause.

  6. 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
  7. Set default_pool_size from the PostgreSQL limit. default_pool_size is the maximum number of server connections for one database and user pair, and its default is 20. reserve_pool_size adds a few more that PgBouncer opens only when a client has waited longer than reserve_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 under max_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 = 80

    For 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.

  8. 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_statements is 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 add max_prepared_statements = 200 to 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=0 to the connection string.
    • Psycopg 3 (Python): set prepare_threshold=None on the connection.
    • PHP with PDO: set PDO::ATTR_EMULATE_PREPARES to true.

    Without one of the two, queries fail at random with “prepared statement does not exist”.

  9. Apply a configuration change without dropping clients.

    sudo -u postgres psql -h /var/run/postgresql -p 6432 -U pgbouncer pgbouncer -c "RELOAD;"

    RELOAD reads pgbouncer.ini and userlist.txt again. The command prints RELOAD when 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 HOLD cursors and SQL-level PREPARE do not work in transaction mode. NOTIFY does. For a client that needs them, add a second entry under [databases] with pool_mode=session, or connect that client directly to PostgreSQL.
  • SQL-level PREPARE and EXECUTE. 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_query is skipped. The reset query (DISCARD ALL by default) runs only in session mode. In transaction mode, anything a transaction leaves on the session stays there for the next client.
  • max_client_conn and file descriptors. Each connection uses a file descriptor, the handle the operating system gives a process for every open socket. The documented upper bound is max_client_conn plus the pool size multiplied by databases and users. For the example that is 2000 + 40 x 2 x 2 = 2160. Check the limit of the running process with grep 'open files' /proc/$(pidof pgbouncer)/limits.
  • userlist.txt goes stale. When a password changes in PostgreSQL, export the secret again and run RELOAD. To avoid the file, set auth_user and let PgBouncer look secrets up with auth_query.
  • server_lifetime = 0 does 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.