
Everything works for months. Then a traffic spike or a deploy hits, and the logs fill with errors like this:
FATAL: sorry, too many clients alreadyOr, from SQLAlchemy, a different version of the same problem:
QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30.00The first means Postgres ran out of connection slots. The second means your app's own pool did. Both come from the same root cause, and this post shows how to fix it: do the math, size your pools, and put PgBouncer in front.
Sources: the numbers and behavior come from the PostgreSQL docs and wiki, the PgBouncer docs and release notes, the SQLAlchemy docs and the HikariCP pool-sizing guide. Check the current versions before you deploy anything.
Why connections run out
Postgres limits how many clients can connect at once with max_connections. The default is typically 100, and changing it requires a server restart. A few of those slots are held back for superusers, 3 by default, so that you can still log in to fix things.
You'd think raising the limit solves it. It rarely does. The Postgres wiki explains that throughput climbs as connections increase, then hits a knee and falls off. Internal structures sized by max_connections scale badly, and more active connections means more contention for disk and CPU.
Each connection is also a separate server process with its own memory. Most of your connections are idle most of the time, but they still cost something.
The result: you want few connections doing real work, and many clients waiting their turn.
The arithmetic of exhaustion
Every app process has its own pool, and the pools multiply. SQLAlchemy's default pool keeps 5 connections and allows 10 more under load, so one process can hold up to 15:
def worst_case_connections(instances, workers, pool_size=5, max_overflow=10):
return instances * workers * (pool_size + max_overflow)
print(worst_case_connections(instances=10, workers=4)) # 600Ten pods with four workers each can ask for 600 connections against a database that allows 100.
Pools don't create connections up front, so you can run for a long time without noticing. The problem shows up when load rises and every pool grows at once. Rolling deploys can make it worse by briefly running old and new instances together.
flowchart LR
A["10 pods × 4 workers<br/>up to 600 connections"] --> B["Postgres<br/>max_connections = 100"]
B --> C["too many clients already"]Step 1: See where your connections go
Start by looking at what's actually connected:
SHOW max_connections;
SELECT count(*) AS total
FROM pg_stat_activity
WHERE backend_type = 'client backend';
SELECT application_name, state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY application_name, state
ORDER BY count(*) DESC;You'll usually find a pile of idle connections, which are pooled connections waiting for work. Watch for idle in transaction. Those hold a connection and any locks while doing nothing, and they hurt pooling the most.
Step 2: Size your app pools
The Postgres wiki and the HikariCP guide agree on a starting point for how many connections can do useful work at once:
connections = (core_count * 2) + effective_spindle_countCount physical cores, not hyperthreads. The spindle count is zero if your data is fully cached. It's a starting point, so load-test around it.
The number applies to the whole database, not to each app instance. A 4-core server with one disk lands around 9 or 10 active connections, which surprises people. HikariCP's guide notes that a tuned pool sits right at the limit of what the database can process at once.
Leave headroom, too. The wiki advises making max_connections a bit bigger than your pools combined, so there are always slots for maintenance and monitoring.
Here's a SQLAlchemy engine with limits you can reason about:
from sqlalchemy import create_engine
engine = create_engine(
"postgresql+psycopg://app:secret@db:5432/appdb",
pool_size=5, # connections kept open (the default)
max_overflow=5, # extra connections under load (the default is 10)
pool_timeout=10, # seconds to wait for a free connection (the default is 30)
pool_recycle=1800, # replace connections older than 30 minutes
pool_pre_ping=True, # test a connection before handing it out
)Failing after 10 seconds is usually kinder than hanging requests for 30. pool_pre_ping sends a cheap SELECT 1 on checkout, so a connection that died after a database restart gets replaced instead of raising an error.
Why app pools aren't enough
Small pools help, but they have a ceiling. Every process still holds its own connections, and the total grows with every pod and worker you add. You need something that shares a small number of real Postgres connections between all of them.
That's what PgBouncer does. Your apps connect to PgBouncer, which is cheap: its docs list a default of 2 kB per connection. PgBouncer keeps a small set of real connections to Postgres and lends them out only when needed.
flowchart LR
A["App pods<br/>1,000 client connections"] --> B["PgBouncer<br/>port 6432"]
B --> C["Postgres<br/>20 server connections"]The three pooling modes
Mode | A server connection is released... | Supports all Postgres features? |
|---|---|---|
| when the client disconnects | Yes |
| when the transaction ends | No, see below |
| after each statement | No, and multi-statement transactions are disallowed |
Session mode is safe but saves little, since each client keeps its server connection for as long as it stays connected. Transaction mode is where the big wins are for web apps, because most clients spend most of their time between transactions.
A minimal PgBouncer setup
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb
[pgbouncer]
; use your private interface here if your apps run on other hosts
listen_addr = 127.0.0.1
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20
reserve_pool_size = 5
reserve_pool_timeout = 3
stats_users = monitoringThen point your app at port 6432 instead of 5432. Nothing else about the connection string changes. The monitoring user is for the admin console, covered below. Like every user, it needs an entry in the auth file.
Rather than listing every user in userlist.txt, PgBouncer can look up passwords with auth_user and auth_query. Use a restricted function for that lookup instead of giving PgBouncer superuser access.
With scram-sha-256, the auth file must hold each user's SCRAM secret or plain-text password. If PgBouncer logs in to Postgres as each client user, which is the default, a secret in the file must be identical to the one on the server, not merely derived from the same password.
The settings that matter
default_pool_sizeis the number of server connections per user and database pair, and the default is 20. Two users on two databases means four pools, so 80 server connections. Multiply before you commit to a number. If you set a fixeduser=in a[databases]entry, that database has a single pool.max_db_connectionscaps server connections per database across all users. The default is unlimited, so set it to protectmax_connections.max_client_connis how many clients PgBouncer accepts. The default is 100. When you raise it, you may also need to raise the operating system's file descriptor limit.reserve_pool_sizeadds spare connections after a client has waitedreserve_pool_timeoutseconds. It's off by default.One CPU core per instance. PgBouncer is single-threaded. If one instance becomes the bottleneck, the docs describe running several with
so_reuseport.query_wait_timeoutdisconnects a client that waits too long for a server connection, after 120 seconds by default. Keep your app's timeouts in line with it, or retries will deepen the queue.
Heads up: run PgBouncer 1.26.1 or newer. The 1.26.1 release on 14 October 2026 fixed an authentication bypass: a client that knew one SCRAM user's password could log in as any other SCRAM user, admins included. Version 1.26.0 fixed three more CVEs, including crashes that unauthenticated clients could trigger. Check for newer releases before you install.
What breaks in transaction mode
In transaction mode, two statements in different transactions can run on different server connections. Anything that relies on connection state can silently misbehave. PgBouncer's feature table lists what works:
Feature | Transaction mode |
|---|---|
| Only for parameters PgBouncer tracks |
| Never ( |
| Never |
SQL-level | Never |
Protocol-level prepared statements | Yes, with |
| Never |
| Yes |
| Never |
Session-level advisory locks | Never |
Note: the feature table on PgBouncer's website still lists
SETandRESETas never working in transaction mode. The configuration docs describe the parameter tracking added since, and the table above follows them.
A few practical notes:
SET: PgBouncer can only keep a parameter consistent if it tracks it. Since 1.26 it tracks, by default, the parameters Postgres reports to clients and that clients can change, such asapplication_name,TimeZone,DateStyleanddefault_transaction_read_only, plussearch_pathon Postgres 18 and newer. On older Postgres, aSET search_pathmade after connecting isn't tracked and can leak to other clients that share the server connection. For anything untracked, set defaults per role withALTER ROLE app SET search_path TO myschema, public, or useSET LOCALinside a transaction.Advisory locks: use the transaction-level versions, such as
pg_advisory_xact_lock, which are released when the transaction ends.Migrations,
pg_dumpandLISTENworkers: connect these straight to Postgres, or through a session-mode pool.Long transactions: a transaction holds its server connection until it commits. Don't call external APIs inside one. Consider
idle_in_transaction_session_timeouton the Postgres side, or PgBouncer'sidle_transaction_timeout, as a safety net. Both are off by default.
Prepared statements and your driver
This is the gotcha that bites most Python apps. Since PgBouncer 1.21, it can track protocol-level prepared statements in transaction mode, and the setting is on by default (max_prepared_statements = 200) since 1.24. Drivers vary, though, and the guidance isn't uniform:
psycopg 3 starts preparing a statement automatically once it has run repeatedly (
prepare_threshold, 5 by default). Unless you run PgBouncer 1.22 or newer withmax_prepared_statementsabove 0, plus psycopg 3.2 and libpq 17 or newer, setprepare_threshold=None.asyncpg uses named prepared statements. Apache Airflow's docs say to disable its caching behind transaction-mode PgBouncer, while at least one vendor reports that defaults work on current PgBouncer. Test your exact stack. Even with the cache off, an asyncpg user reported that
copy_records_to_tablestill created named prepared statements.After a migration that adds a column or changes a column type, clients sharing a prepared query can hit
ERROR: cached plan must not change result type. RunningRECONNECTon the PgBouncer admin console clears it.
The conservative setup disables driver-side prepared statements until you've tested otherwise:
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import create_async_engine
# psycopg 3
engine = create_engine(
"postgresql+psycopg://app:secret@pgbouncer:6432/appdb",
connect_args={"prepare_threshold": None},
)
# asyncpg
async_engine = create_async_engine(
"postgresql+asyncpg://app:secret@pgbouncer:6432/appdb",
connect_args={
"statement_cache_size": 0, # asyncpg's own cache
"prepared_statement_cache_size": 0, # SQLAlchemy's cache
},
)Keep an app-side pool when you add PgBouncer, and keep it small. Client connections to PgBouncer are cheap, and the pool saves you from reconnecting on every request.
Watch the queue
PgBouncer has an admin console. Connect to the special pgbouncer database as a user listed in admin_users or stats_users:
psql -p 6432 -U monitoring pgbouncer -c "SHOW POOLS;"Four columns tell you most of the story:
Column | What it means |
|---|---|
| Clients currently linked to a server connection |
| Clients that sent a query but have no server connection yet |
| Server connections in use / free |
| How long the oldest waiting client has been queued |
If cl_waiting stays above zero while sv_idle is zero, the pool is too small or your queries are too slow. Check the slow queries first. A bigger pool only helps if Postgres has the capacity to use it.
Checklist
Know your numbers:
max_connections, and the worst case frominstances × workers × (pool_size + max_overflow).Keep app pools small, with a short
pool_timeoutandpool_pre_ping.Use PgBouncer in transaction mode, version 1.26.1 or newer.
Multiply
default_pool_sizeby your user and database pairs, and cap it withmax_db_connections.Avoid session-level features, or route them around the pooler.
Disable driver-side prepared statements until you've tested your stack.
Alert on
cl_waitingandmaxwait.
Start with Step 1. Once you can see where the connections are going, the fix is usually obvious.
Comments(0)
Join the discussion by logging into your account.
No comments yet. Be the first to comment!