FATAL: sorry, too many clients already means PostgreSQL has handed out every slot allowed by max_connections, including the ones reserved for superusers, so it refuses new connections. To fix "too many clients already" in the short term, find and close the sessions holding slots, usually idle or idle in transaction connections from an application pool. The long-term fix is to cap and pool connections, typically with PgBouncer in transaction mode. Raising max_connections is not the fix. Below I reproduce the error on PostgreSQL 18.6, show the queries that find the culprits, and walk through a PgBouncer 1.26 setup with what breaks in transaction mode.
Reproducing "Too Many Clients Already"
I started a throwaway PostgreSQL 18.6 cluster on a spare port with max_connections = 5 and superuser_reserved_connections = 1. Then I opened four sessions as a normal app role, each one running BEGIN; SELECT …; and then doing nothing, which is what a leaked transaction in an app pool looks like. The next connection attempt by app failed with the first of two messages you will see in production:
psql: error: connection to server at "127.0.0.1", port 55432 failed:
FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute
A superuser could still get in using the reserved slot. Once that slot was taken too, everyone got the error this article is about:
psql: error: connection to server at "127.0.0.1", port 55432 failed:
FATAL: sorry, too many clients already
The server log recorded both:
2026-12-02 08:29:28.753 IST [93497] FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute
2026-12-02 08:29:38.970 IST [93607] FATAL: sorry, too many clients already
The first message is a warning. Your application is locked out, but you can still connect as a superuser to diagnose it. The second means even the emergency slot is gone. Per the connection settings docs, superuser_reserved_connections defaults to 3. PostgreSQL 16 added reserved_connections for roles granted pg_use_reserved_connections. Use it to keep a slot for your monitoring and on-call role that isn't a full superuser.
Why Raising max_connections Isn't the Fix
Raising max_connections from 100 to 1,000 is the most common response, and it usually makes things worse:
- It needs a restart. The docs say: "This parameter can only be set at server start." On a primary with streaming replicas, the standbys must have the same or a higher value, or they stop accepting queries.
- Every connection is a process. PostgreSQL forks one backend per connection. Each backend has its own private memory, and
work_memapplies per sort or hash operation inside each one. The docs also note that "PostgreSQL sizes certain resources based directly on the value ofmax_connections", including shared memory. A thousand mostly idle connections still cost memory, and a thousand active ones will contend for CPU, locks and I/O far beyond what the hardware can run at once. - It hides the bug. Running out of slots almost always means connections are leaking, idling in a transaction, or being multiplied by autoscaling. A higher limit only postpones the outage, and the next one hits a database with more contention.
Throughput peaks when the number of actively running queries is close to the cores and I/O channels available. The HikariCP project's pool sizing guide gives a starting point of connections = ((core_count * 2) + effective_spindle_count), adding that "Pool sizing is ultimately very specific to deployments." The goal is a few dozen busy server connections shared by however many clients you have. Connection pooling is how you get there.
Step 1: Find the Connection Hogs with pg_stat_activity
Connect as a superuser (or a role with reserved slots) and group sessions by who opened them:
SELECT usename, application_name, client_addr, state, count(*) AS conns,
max(now() - state_change) AS longest_in_state
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY 1, 2, 3, 4
ORDER BY conns DESC;
In my reproduction, a fake worker that set PGAPPNAME=billing-worker showed up right away:
usename | application_name | client_addr | state | conns | longest_in_state
----------+------------------+-------------+---------------------+-------+------------------
app | billing-worker | 127.0.0.1 | idle in transaction | 3 | 00:00:02.979908
postgres | psql | 127.0.0.1 | active | 1 | -00:00:00.000002
This is why you should set application_name in every service's connection string. Without it, every row says app and you are guessing from IP addresses.
How to read the state column:
| state | Meaning | Usual cause |
|---|---|---|
active |
Running a query now | Real load, or slow queries |
idle |
Connected, no transaction | Pool holding warm connections (normal, but counts against the limit) |
idle in transaction |
Inside BEGIN, waiting on the client |
Missing commit/rollback, HTTP call inside a transaction, crashed worker |
idle in transaction (aborted) |
Transaction failed, client hasn't rolled back | Error-handling bug |
Then list the worst idle in transaction sessions, the ones that also block vacuum and hold locks:
SELECT pid, usename, application_name,
now() - xact_start AS xact_age,
now() - state_change AS idle_for,
left(query, 60) AS last_query
FROM pg_stat_activity
WHERE state LIKE 'idle in transaction%'
ORDER BY xact_start;
query shows the last statement the session ran, not what it is waiting on, so it points you to the code path that opened the transaction. To free slots during an incident, terminate the obvious offenders:
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle in transaction'
AND now() - state_change > interval '5 minutes'
AND usename = 'app';
Long-open transactions also stop vacuum from removing dead rows. If you find hours-old xact_start values, check bloat next with our guide on finding and fixing PostgreSQL table bloat.
Step 2: Add Timeouts So Leaks Fix Themselves
PostgreSQL can enforce what your application forgot. All of these default to 0 (disabled). Per the client connection defaults docs, the main ones are:
| Setting | Ends | Use it for |
|---|---|---|
idle_in_transaction_session_timeout |
Sessions idle inside an open transaction | Leaked transactions. Set this one first. |
transaction_timeout (PostgreSQL 17+) |
Any transaction longer than the limit, idle or not | Hard ceiling for OLTP roles |
statement_timeout |
A single statement | Runaway queries (set per role, not globally) |
idle_session_timeout |
Idle sessions with no transaction | Interactive users only. The docs warn poolers "may not react well to unexpected connection closure" |
Set them per role so batch jobs and humans get different limits:
ALTER ROLE app SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE app SET statement_timeout = '15s';
ALTER ROLE analyst SET idle_session_timeout = '15min';
ALTER ROLE etl SET statement_timeout = '0';
Settings take effect for new sessions. Here is the timeout firing in my test cluster with a 5-second limit:
BEGIN
?column?
----------
1
(1 row)
FATAL: terminating connection due to idle-in-transaction timeout
server closed the connection unexpectedly
The server logs the same line. Alert on it, because each occurrence is a bug in application code that you want to find.
Step 3: Size the Application Pools
Before adding PgBouncer, do the arithmetic most teams skip:
total connections = Σ (instances × pool max) for every service
+ cron jobs, migrations, admin tools, replicas' monitoring
Twelve API pods with a pool of 10 each already exceed PostgreSQL's default of 100 connections, before workers, a deploy that briefly doubles the pod count, or a human running psql. Each service's pool maximum should come from a budget, not a library default. For example, node-postgres defaults to max: 10 and connectionTimeoutMillis: 0. The docs warn that with 0, pool.connect will "hang indefinitely". Set a timeout so a full pool fails fast instead of piling up requests:
import pg from 'pg';
export const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
application_name: 'checkout-api',
max: 5, // per instance; budgeted, not default
idleTimeoutMillis: 10_000,
connectionTimeoutMillis: 3_000,
});
If the sum still doesn't fit or autoscaling makes it unpredictable, put a pooler in front of PostgreSQL.
Step 4: Set Up PgBouncer
PgBouncer is a single-process, event-driven pooler. Thousands of client connections share a small set of server connections. The current release is 1.26.1 (14 October 2026). Run it, or at least 1.26.0. The changelog lists several security fixes in 1.25.1 through 1.26.1, including pre-authentication crashes and hangs and a SCRAM impersonation issue (CVE-2026-107350) affecting 1.17.0 to 1.26.0.
Pooling modes
| Mode | Server connection returned to pool | Use when |
|---|---|---|
session (default) |
When the client disconnects | Apps need session features. This mode only caps connections, so slots still fill up. |
transaction |
At the end of each transaction | Most web apps and workers. This is the one that fixes "too many clients". |
statement |
After each statement; multi-statement transactions are disallowed | Autocommit-only workloads |
What breaks in transaction mode
From the PgBouncer features page:
| Feature | Transaction pooling |
|---|---|
SET / RESET |
Never |
LISTEN |
Never |
WITH HOLD cursors |
Never |
SQL-level PREPARE / DEALLOCATE |
Never |
| Protocol-level prepared statements | Yes, when max_prepared_statements > 0 |
| Session-level advisory locks | Never (pg_advisory_xact_lock is fine) |
Temp tables (PRESERVE/DELETE ROWS) |
Never (ON COMMIT DROP is fine) |
LOAD |
Never |
Two details have changed recently and many older guides get them wrong:
- Prepared statements work now. PgBouncer 1.21 added tracking of protocol-level prepared statements in transaction mode, and since 1.24
max_prepared_statementsdefaults to 200. Drivers that use the extended protocol's named statements (JDBC,asyncpg, Npgsql, node-postgres withname:) no longer needprepareThreshold=0orstatement_cache_size=0, as long as you run 1.24 or later or set the value yourself. SQL-levelPREPARE foo AS …still breaks. - Some
SETs are safe now. 1.26.0 tracks every parameter PostgreSQL reports by default. On PostgreSQL 18+ that includessearch_path, so one client'sSET search_pathno longer leaks to another client sharing the server connection. OtherSETs still leak. UseSET LOCALinside the transaction, or role- and database-level defaults.
If an app needs LISTEN/NOTIFY or session advisory locks, give that component a separate session-mode pool or a direct connection.
pgbouncer.ini
[databases]
; client-facing name = real server
shop = host=10.0.0.5 port=5432 dbname=shop
[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
auth_user = pgbouncer_auth
auth_query = SELECT uname, phash FROM pgbouncer.user_lookup($1)
pool_mode = transaction
; client sockets PgBouncer accepts
max_client_conn = 2000
; server connections per user/database pair
default_pool_size = 20
min_pool_size = 5
reserve_pool_size = 5
reserve_pool_timeout = 3
; hard cap per database across all users
max_db_connections = 60
; fail queued clients after 30s instead of the 120s default
query_wait_timeout = 30
server_idle_timeout = 600
max_prepared_statements = 200
admin_users = pgbouncer_admin
stats_users = pgbouncer_stats
; JDBC sends this at startup; ignore instead of rejecting
ignore_startup_parameters = extra_float_digits
The defaults I changed or kept, from the configuration reference: max_client_conn defaults to 100, default_pool_size to 20, query_wait_timeout to 120 seconds, and auth_type to md5. Leave auth_type at md5 only if your server still stores MD5 hashes. PostgreSQL's default password_encryption is SCRAM.
max_db_connections is the setting that ends the outage. Keep it below max_connections minus the superuser and reserved slots, minus whatever bypasses the pooler, so PostgreSQL never hits its own limit. When the pool is full, clients wait in PgBouncer's queue, and query_wait_timeout turns that wait into a clean error instead of a hang.
userlist.txt and auth_query
auth_file only needs the auth_user itself. Copy its SCRAM secret straight from the catalog:
SELECT format('"%s" "%s"', rolname, rolpassword)
FROM pg_authid WHERE rolname = 'pgbouncer_auth';
"pgbouncer_auth" "SCRAM-SHA-256$4096:W4xF67Nd7MjjN…"
Every other user is looked up at login with auth_query. Don't give the lookup role access to pg_authid. Wrap the lookup in a SECURITY DEFINER function, created by a superuser, in each database PgBouncer connects to (or in the one named by auth_dbname):
CREATE ROLE pgbouncer_auth LOGIN PASSWORD 'change-me';
CREATE SCHEMA pgbouncer AUTHORIZATION pgbouncer_auth;
CREATE OR REPLACE FUNCTION pgbouncer.user_lookup(p_user text, OUT uname text, OUT phash text)
RETURNS record
LANGUAGE sql
SECURITY DEFINER
SET search_path = pg_catalog, pg_temp
AS $$
SELECT rolname::text,
CASE WHEN rolvaliduntil < now() THEN NULL ELSE rolpassword END
FROM pg_catalog.pg_authid
WHERE rolname = p_user AND rolcanlogin;
$$;
REVOKE ALL ON FUNCTION pgbouncer.user_lookup(text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION pgbouncer.user_lookup(text) TO pgbouncer_auth;
I ran this on PostgreSQL 18.6. As pgbouncer_auth, SELECT * FROM pgbouncer.user_lookup('app') returned the SCRAM secret, while SELECT * FROM pg_authid failed with permission denied for table pg_authid. That is the intended privilege boundary.
Point the app at PgBouncer and watch the pools
Change the port to 6432 and keep everything else. Use PgBouncer's admin console to check that it is working:
psql -h pgbouncer.internal -p 6432 -U pgbouncer_admin pgbouncer -c 'SHOW POOLS;'
psql -h pgbouncer.internal -p 6432 -U pgbouncer_admin pgbouncer -c 'SHOW STATS;'
In SHOW POOLS, cl_waiting greater than zero for long periods means default_pool_size or max_db_connections is too small, or queries are slow. maxwait shows how long the oldest client has been queued. Graph both.
PgBouncer is single-threaded. To use more cores, run several processes with so_reuseport = 1. 1.26.0 removed the old online restart (-R) in favour of rolling restarts on a shared port.
Serverless, Supavisor and Managed Poolers
Serverless functions are the hardest case: every warm instance holds its own pool, and you don't control how many instances exist. Supabase's connection docs recommend its shared Supavisor pooler in transaction mode (port 6543) for serverless and edge functions, with a client created once at module scope, a pool size of 1, and SSL required. Their docs state: "The shared pooler doesn't support prepared statements in transaction mode", so turn them off in the driver there. Supabase's dedicated PgBouncer pooler on Pro plans does support them. Neon, AWS RDS Proxy and others have their own poolers with similar trade-offs. Our Neon vs Supabase comparison covers how each handles connections, and the PostgreSQL 19 features overview covers what is new on the server side.
Frequently Asked Questions
What does "FATAL: sorry, too many clients already" mean?
Every connection slot in max_connections is in use, including those reserved for superusers, so PostgreSQL rejects the new connection. The related message "remaining connection slots are reserved for roles with the SUPERUSER attribute" means only the reserved slots are left. You can still log in as a superuser to investigate.
How do I see how many connections PostgreSQL has?
Run SELECT count(*) FROM pg_stat_activity WHERE backend_type = 'client backend'; and compare it with SHOW max_connections;. Group by usename, application_name and state to see which service holds them and whether they are actually working.
Should I just increase max_connections?
Only as a small, temporary change while you fix the cause, and it requires a restart. Each connection is a separate backend process, and resources scale with the setting. Very high values usually lower throughput under load. Pooling plus timeouts fixes the cause.
Does PgBouncer support prepared statements in transaction mode?
Yes, for protocol-level prepared statements, since PgBouncer 1.21. They are on by default since 1.24 (max_prepared_statements = 200). SQL-level PREPARE/EXECUTE is still not supported in transaction mode. Some hosted poolers, such as Supabase's shared Supavisor pooler, don't support prepared statements in transaction mode at all.
What pool size should I use with PgBouncer?
Start with default_pool_size near two times the database server's CPU cores and adjust it using cl_waiting and query latency. Set max_db_connections so PgBouncer can never exceed PostgreSQL's usable slots. Keep each application's own pool small (a handful per instance), because PgBouncer does the multiplexing.
Bottom Line
"Too many clients already" is almost always a connection-management bug, not a capacity problem. Connect through a reserved slot, find the hogs in pg_stat_activity, and terminate the idle-in-transaction ones. Then set idle_in_transaction_session_timeout per role so leaks clean themselves up, budget application pool sizes explicitly, and put PgBouncer 1.26.1 in transaction mode in front of the database with max_db_connections below the server's limit. Keep max_connections at a modest value and let the pooler absorb the client count.