Sub topic 9
Sizing pools and connection limits
This chapter shows how to choose default_pool_size, max_client_conn and the related limits so that PgBouncer never asks PostgreSQL for more connections than it can serve. It assumes you can read a basic pgbouncer.ini, know the three pool modes, and know what max_connections does in PostgreSQL.
Two sides, two budgets
PgBouncer has two connection counts to size, and they limit different things.
- Client connections come from your applications to PgBouncer. They are cheap: PgBouncer is a single-process, event-driven program, and an idle client costs a small buffer and one file descriptor.
max_client_connlimits them. - Server connections go from PgBouncer to PostgreSQL. Each one is a full PostgreSQL backend process, so these are the expensive ones. Pool sizes limit them.
Pooling works because the first number can be large while the second stays small. Sizing means picking the small number deliberately and then making sure the sum of every pool that can exist still fits inside PostgreSQL.
What a pool is
PgBouncer keeps one pool for each (user, database) pair. If app_user and report_user both connect to appdb, PgBouncer creates two pools. Each pool is capped separately by default_pool_size (default 20). A pool can grow beyond that by reserve_pool_size connections when clients have waited longer than reserve_pool_timeout.
The worst-case number of server connections from one PgBouncer instance is therefore:
sum over all pools of (pool_size + reserve_pool_size)Pools are created lazily, but you cannot count on them staying idle. Size for the case where every pool is full at once.
| Setting | Default | What it limits |
|---|---|---|
| `max_client_conn` | 100 | Total client connections accepted by this PgBouncer |
| `default_pool_size` | 20 | Server connections per (user, database) pair |
| `min_pool_size` | 0 | Server connections kept open even when idle |
| `reserve_pool_size` | 0 | Extra server connections per pool, used after `reserve_pool_timeout` |
| `max_db_connections` | 0 (no limit) | Server connections per database across all users |
| `max_user_connections` | 0 (no limit) | Server connections per user across all databases |
The two max_* limits are safety caps layered over the pool sizes. Use them when several pools could together exceed what PostgreSQL can take.
Start from the PostgreSQL budget
Work from the database outward. Take max_connections and subtract everything that does not go through PgBouncer.
SHOW max_connections;
SHOW superuser_reserved_connections;
SELECT usename, count(*) AS connections
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY usename
ORDER BY connections DESC;The last query shows who holds connections now. Anything that connects directly stays outside the pooler and has to be budgeted: replication slots' walsenders, monitoring agents, migration tools, and your own psql sessions.
A worked example. The database has max_connections = 100 and superuser_reserved_connections = 3.
- Subtract 3 reserved for superusers: 97 left.
- Set aside 7 for direct connections (monitoring, migrations, replication, emergencies): 90 left.
- Two PgBouncer hosts share the 90, so each host gets 45.
- On each host,
app_usergets a pool of 20 plus 5 reserve (25), andreport_usergets a pool of 5 plus 5 reserve (10). That is 35 per host and 70 in total, which fits inside 90 with room to spare.
The most common sizing failure is forgetting that every PgBouncer instance has its own pools. Running a second instance for availability doubles the worst case.
Choosing the pool size itself
The budget gives you a ceiling. The right pool size is usually well below it.
A busy PostgreSQL server cannot run more queries in parallel than it has CPU cores and disk bandwidth. Extra active connections add context switching and lock contention without adding throughput. A good starting point is two to four times the number of CPU cores for the whole server, divided among the pools that are active at the same time.
You can check that against the workload with a rough queueing estimate:
busy server connections ≈ transactions per second × average transaction duration (seconds)If the app runs 2000 transactions per second and each takes 5 ms, then 2000 × 0.005 = 10 server connections are busy on average. A pool of 20 gives 2x headroom for bursts, which is reasonable. A pool of 200 would not make anything faster, and it would let a traffic spike push the database into overload.
The pool mode changes this arithmetic:
- Transaction mode: a server connection is held only for the length of a transaction, so the estimate above applies and pools can be small.
- Session mode: a server connection is held for the whole client session. You need roughly one server connection per concurrently connected client, so the pool must be as large as peak concurrency. Session mode gives much less multiplexing.
A configuration that matches the example
This excerpt sets the limits for one of the two hosts above. It defines two database entries that point at the same PostgreSQL database but use different users and pool sizes.
[databases]
appdb = host=10.0.0.5 port=5432 dbname=appdb user=app_user pool_size=20
appdb_reports = host=10.0.0.5 port=5432 dbname=appdb user=report_user pool_size=5
[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 2000
default_pool_size = 20
reserve_pool_size = 5
reserve_pool_timeout = 3
max_db_connections = 40
admin_users = pgbouncer_adminHere pool_size in [databases] overrides default_pool_size for that entry. max_db_connections = 40 is a backstop: even if the pool settings are edited carelessly later, this host will not open more than 40 server connections to any one database entry. The user= option forces every client of that entry to connect to PostgreSQL as that user, so make sure that is what you want before using it.
Setting max_client_conn
Pick max_client_conn from the application side. Add up the maximum client pool of every application instance that connects, then add headroom for deploys, when old and new instances overlap.
For example, 40 application instances with a driver-side pool of 25 connections each can open 1000 connections. Setting max_client_conn = 2000 leaves room for rolling deploys and a few ad hoc sessions.
Each client connection also uses a file descriptor, and so does each server connection. If the operating system limit is lower than the number PgBouncer needs, accepts fail under load. Check ulimit -n for the PgBouncer process, or set LimitNOFILE in the systemd unit, and keep it comfortably above max_client_conn plus the total of all pool sizes. When max_client_conn is reached, new clients are rejected with an error that mentions max_client_conn.
Verifying the numbers live
Connect to the admin console and compare the configuration with what is happening.
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncerSHOW DATABASES;
SHOW POOLS;
SHOW LISTS;In SHOW DATABASES, pool_size and current_connections show each entry's limit and current use. In SHOW POOLS, watch these columns:
cl_waiting: clients that have sent a query and are waiting for a server connection. A value that is often above zero means the pool is the bottleneck.sv_activeandsv_idle: busy and idle server connections. Ifsv_idleis large andcl_waitingis zero, the pool is bigger than needed.maxwait: seconds the oldest waiting client has waited. A growing value is an early warning before clients start timing out.
Tune in small steps. If cl_waiting is regularly above zero while PostgreSQL CPU is low, raise pool_size a few connections at a time. If PostgreSQL CPU is saturated and cl_waiting is also non-zero, a bigger pool will not help. The queries need tuning or the database needs more capacity. After editing the file, run RELOAD; in the console and check SHOW DATABASES again.
Common mistakes
- Counting only one instance. Multiply the worst case by the number of PgBouncer hosts, and add pools for each user.
- Pool size equal to
max_connections. This leaves nothing for superusers, monitoring or migrations, and one pool can starve the others. - Ignoring reserve pools.
reserve_pool_sizeadds to the worst case per pool. - Sizing for clients instead of transactions. In transaction mode, the number of application threads says little about how many server connections you need.
- Forgetting file descriptors. A low
ulimit -nshows up as failures only under high connection counts.
Exercise
PostgreSQL has maxconnections = 150 and superuserreservedconnections = 3. You keep 12 connections for direct use. Three PgBouncer hosts each serve one user and one database, with defaultpoolsize = 20 and reservepool_size = 5. What is the worst-case number of server connections from PgBouncer, and does it fit the budget?
Show answer
The budget is 150 - 3 - 12 = 135 connections. Each host can open 20 + 5 = 25 server connections for its single pool, so three hosts can open 75 in the worst case. 75 is below 135, so it fits with 60 connections to spare. If every host also served a second user with the same settings, the worst case would be 150, which would exceed the budget.