Database connection pooling and max connections for Postgres and MySQL
Every database connection uses server resources, so you cap them with max_connections, size each app's pool so the total fits under it, and add a pooler such as PgBouncer when many clients share few queries.
- Updated Nov 27, 2026
- Markdown
Find who holds your database connections, size app pools to fit max_connections, and decide when PgBouncer is worth adding.
- A running Postgres or MySQL server and an app that connects to it
When Postgres says FATAL: sorry, too many clients already, the server has used all of max_connections. The fix is rarely to raise the number. Find out who holds the connections, make the total of all app pools fit under the limit, set timeouts for stuck sessions, and add a pooler such as PgBouncer only when many short-lived clients are the real problem.
How it works#
Postgres starts one backend process per client connection. Each one uses memory and a slot, and max_connections (100 by default on a stock install, but check yours with SHOW max_connections;) caps the total. A few slots are reserved for superusers through superuser_reserved_connections, so a normal app can hit its ceiling while an admin can still log in. That reserve is why you also see FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute or for non-replication roles.
Apps do not open a connection per query. They keep a pool of open connections and lend them out. The pool size is set in the app or ORM, and the pool exists per process. So the total demand is:
pool size x processes per replica x replicas, plus workers, cron jobs and admin toolsIf that total is higher than max_connections, you get errors under load even though the database is mostly idle. MySQL and MariaDB work the same way in principle, with threads instead of processes and the error ERROR 1040 (HY000): Too many connections.
Step 1: See who holds the connections#
In psql as a superuser:
SELECT count(*) FROM pg_stat_activity;
SHOW max_connections;
SELECT state, count(*)
FROM pg_stat_activity
GROUP BY state
ORDER BY count(*) DESC;
SELECT datname, usename, application_name, client_addr, count(*)
FROM pg_stat_activity
GROUP BY 1, 2, 3, 4
ORDER BY count(*) DESC;The first shows how close you are to the limit. The state breakdown shows whether connections are active (running a query), idle (open and unused, normal for a pool) or idle in transaction (a transaction left open, which is a bug signal). The last query tells you which app and host owns them, which works best when apps set application_name in the connection string. Find stuck transactions:
SELECT pid, usename, now() - xact_start AS open_for, left(query, 60) AS last_query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY xact_start;Step 2: Size the app pools#
Add up the pool sizes first. Suppose you have 3 web replicas with a pool of 10 each, 1 worker with 10, and you want 10 spare slots for migrations and psql. That needs 50 connections, so a default of 100 is comfortable. Few queries run at once on a small server, so a smaller pool is often just as fast: connections beyond what the CPU and disk can serve only queue inside the database. Reduce pools before raising max_connections.
When you do raise it, edit postgresql.conf and restart (the setting needs a restart, not a reload):
max_connections = 200Each connection can use work_mem for sorts, so a higher count raises worst-case memory. Check memory and CPU usage and see fix out-of-memory kills if the box runs out of RAM.
Step 3: Set timeouts for stuck sessions#
ALTER ROLE app SET idle_in_transaction_session_timeout = '60s';
ALTER ROLE app SET statement_timeout = '30s';idle_in_transaction_session_timeout ends sessions that sit inside an open transaction too long, and statement_timeout cancels a single query that runs too long. Choose values that fit your slowest legitimate query. They apply to new sessions of that role. Fix the code that leaks the transaction too, because a timeout only limits the damage. Slow queries behind a proxy also show up as 504 gateway timeouts.
Step 4: Add PgBouncer when you need it#
PgBouncer is a small proxy that accepts many client connections and reuses a few server connections. Apps then connect to PgBouncer (run it as a systemd service), usually on port 6432, instead of Postgres. A minimal pgbouncer.ini:
[databases]
shop = host=127.0.0.1 port=5432 dbname=shop
[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
default_pool_size = 20
max_client_conn = 500The pool modes differ:
| Mode | Server connection is held for | Notes |
|---|---|---|
session | The whole client session | Safest, least savings |
transaction | One transaction | Best savings, breaks session state |
statement | One statement | Rarely suitable, no multi-statement transactions |
Transaction mode has caveats. Session-level SET, advisory locks, LISTEN and NOTIFY, and temporary tables do not behave as expected, because the next transaction may run on another server connection. Prepared statements need care: older PgBouncer versions cannot track protocol-level prepared statements in transaction mode, and newer ones add support under conditions you must check in the docs for your version. Many drivers have a setting to turn off server-side prepared statements. Test the app against it before switching.
Step 5: Do the same for MySQL#
SHOW VARIABLES LIKE 'max_connections';
SHOW STATUS LIKE 'Threads_connected';
SHOW FULL PROCESSLIST;Threads_connected against max_connections shows how close you are, and the process list shows who holds them. Raise max_connections under [mysqld] in the config and restart, after checking memory. wait_timeout closes connections that stay idle too long, which can surprise pools that hold connections open: set the pool’s maximum lifetime lower than the server’s wait_timeout.
Check it worked#
SELECT count(*) FROM pg_stat_activity;stays well belowSHOW max_connections;under normal load.- No sessions sit in
idle in transactionfor minutes. - After a deploy with more replicas, the connection count rises by the amount you calculated.
- The app log no longer shows
too many clientsduring peaks.
Edge cases and gotchas#
- Rolling deploys double the pools. During a zero-downtime deploy old and new containers run together, so connections can briefly double.
- Reserved slots protect you, not the app. Do not run the app as a superuser to bypass the limit.
- Idle is not free. Each idle connection still holds a backend process and memory.
- Serverless and short jobs. Functions that open a connection per invocation can exhaust a server quickly. A pooler fits there.
- Restart needed.
max_connectionsandsuperuser_reserved_connectionsneed a restart, so plan a window. - Pool max lifetime. Set it below firewall or server idle timeouts, or the app finds dead connections after a quiet period.
Troubleshooting#
| Symptom | Likely cause | Fix |
|---|---|---|
FATAL: sorry, too many clients already | Limit reached | Inspect pg_stat_activity, cut pool sizes, then consider raising the limit |
FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute | Only reserved slots left | Free connections, log in as admin to find the holders |
ERROR 1040 (HY000): Too many connections | MySQL max_connections reached | Check SHOW PROCESSLIST, fix pools, raise the limit |
Many rows idle in transaction | App leaks transactions | Fix code, set idle_in_transaction_session_timeout |
FATAL: terminating connection due to idle-in-transaction timeout | Timeout fired | Commit or roll back promptly in the app |
prepared statement "S_1" does not exist | Transaction pooling with prepared statements | Disable server-side prepares in the driver |
ERROR: unsupported startup parameter: ... via PgBouncer | Client sent a parameter the pooler rejects | Add it to ignore_startup_parameters |
ERROR 2006 (HY000): MySQL server has gone away | Idle connection closed by the server | Lower the pool’s max lifetime under wait_timeout |
no more connections allowed (max_client_conn) | PgBouncer client limit reached | Raise max_client_conn or reduce clients |
Quick reference#
SHOW max_connections;
SELECT state, count(*) FROM pg_stat_activity GROUP BY state;
SELECT pid, now() - xact_start AS age, left(query, 60)
FROM pg_stat_activity WHERE state = 'idle in transaction';
ALTER ROLE app SET idle_in_transaction_session_timeout = '60s';
-- MySQL
SHOW VARIABLES LIKE 'max_connections';
SHOW STATUS LIKE 'Threads_connected';pool size x processes x replicas + workers + admin < max_connectionsRelated lessons#
- Database connection strings explained: the URL where pool and SSL options go.
- Postgres roles and permissions: set per-role timeouts on the app role.
- Zero-downtime deploys: why connections briefly double.
- Fix out-of-memory kills: the cost of too many backends.
- Self-hosted Postgres in Docker, connect your app: wiring an app to the database.
Next#
Slow database calls often surface as proxy errors, so read fix 504 gateway timeout next.
Check what you learned
Frequently asked questions
What does FATAL sorry, too many clients already mean in Postgres?
The server has reached max_connections and refuses new sessions. Find what holds connections with pg_stat_activity, fix leaks or oversized pools, and only then consider raising the limit.
What is a good Postgres pool size?
There is no universal number. Start small, count the pool size times every app replica and worker, keep that total below max_connections with room for admin and migration sessions, and raise it only when you see queries waiting.
Do I need PgBouncer?
Not for a single small app with a sane pool. It helps when many app instances or serverless functions open many short connections, because it multiplexes them onto a few server connections.
What causes idle in transaction sessions?
Application code that opens a transaction and then waits, often on a network call or a crash path that never commits. They hold locks and a connection slot until they end or hit idle_in_transaction_session_timeout.
Sources
Keep going: guides and tutorials
- Self-Hosted Postgres in Docker: Connect It to Your App Run Postgres in Docker as its own resource with its own volume, connect your app with one command, and read the reachability badge before a timeout hits.
- Manage Secrets Self-Hosted: Env Vars and Master Key Rotation Set env vars and encrypted secrets on a self-hosted server, apply changes safely, and rotate the master key with no downtime without locking yourself out.