Postgres "FATAL: sorry, too many clients already": your pool is not the size you think it is
Problem
Every deploy or traffic spike, the API starts throwing
FATAL: sorry, too many clients alreadymax_connections is 100. Our pg pool is configured to 20. The math never worked out, so someone doubled the pool size — which made it worse, faster.
Root cause
Count what actually holds connections, per process:
SELECT application_name, client_addr, count(*)
FROM pg_stat_activity
GROUP BY 1, 2
ORDER BY 3 DESC;In our case: 4 API pods x 2 worker threads x pool max 20 = 160 potential, plus a migration runner, plus psql sessions from engineers. The "pool size 20" figure in the config was per instance, and every instance of everything shared the same Postgres. Pools also grow lazily to max under load and never shrink quickly, so the exhaustion shows up on spikes even when average usage looks fine.
import { Pool } from 'pg';
const pool = new Pool({
… 4 more lines in the fix🔒 the fix — including 3 code blocks — is members-only. $1/mo unlocks everything.