The app gets "FATAL: sorry, too many clients already" from PostgreSQL. What do you do?

IntermediateTroubleshootingPostgreSQL
Answer

Short answer

All max_connections slots are used. Find which app/user holds them, check for idle and idle in transaction sessions, size application pools properly, and put PgBouncer (or RDS Proxy) in front if many app instances connect. Raising max_connections is a last resort — each connection costs memory.

Investigate

SHOW max_connections;
SELECT usename, application_name, client_addr, state, count(*)
FROM pg_stat_activity GROUP BY 1,2,3,4 ORDER BY 5 DESC;

SELECT pid, now() - state_change AS idle_for, query
FROM pg_stat_activity WHERE state = 'idle in transaction' ORDER BY idle_for DESC;

Fixes

Cause Fix
Pods × pool size too high Reduce pool size; account for HPA max
Idle-in-transaction sessions Fix app code; idle_in_transaction_session_timeout = '60s'
Many short-lived connections (serverless, PHP) PgBouncer in transaction mode / RDS Proxy
Leaks Pool leak detection, max lifetime

Emergency

SELECT pg_terminate_backend(pid) FROM pg_stat_activity
WHERE state = 'idle' AND now() - state_change > interval '10 minutes';

Note: superuser_reserved_connections keeps a few slots so admins can still log in.

What to say in the interview

"I group pg_stat_activity by user, app and state to find who holds connections, kill long idle sessions if needed, then fix pool sizing and idle-in-transaction bugs. For many instances or serverless, PgBouncer or RDS Proxy multiplexes connections; raising max_connections costs memory, so it's not my first fix."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: PostgreSQL basics

More on PostgreSQL