Why Did My App Exhaust Postgres Connections Under Load?

Traffic climbs, and then everything stops. The logs fill with FATAL: sorry, too many clients already, healthy requests start timing out, and the database looks pinned even though CPU is barely moving.

This is almost never a database that is too small. It is almost always an application that opens connections without a ceiling, multiplied by however many copies of that application are running. The fix has two halves: bound the pool inside each process, and put a real pooler in front of the database so the two limits actually agree with each other. Here is how to confirm the cause before you touch anything, and then how to close it.

Read pg_stat_activity before you change anything

PostgreSQL ships with max_connections = 100 by default, and a handful of those are held back by superuser_reserved_connections. That is the whole budget. The first job is to see who is spending it. Group the live sessions by state:

SELECT
    state,
    count(*)                       AS conns,
    max(now() - state_change)      AS max_age
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY state
ORDER BY conns DESC;

The number you care about is the idle in transaction row. A connection in that state is doing nothing useful and holding a slot open anyway: the client issued BEGIN, then wandered off to call an API, render a template or wait on a lock, without committing. Those connections are pure waste, and under load they are usually the ones that tip you over the edge. Find the worst offenders:

SELECT
    pid,
    usename,
    client_addr,
    application_name,
    state,
    now() - state_change   AS idle_for,
    left(query, 80)        AS last_query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY state_change
LIMIT 20;

If application_name and client_addr point back at your own service and idle_for is measured in seconds or minutes, you have found the leak. The database is not the problem; it is the victim.

The arithmetic that actually breaks

Here is the trap most teams walk into. SQLAlchemy’s default QueuePool keeps pool_size = 5 connections and allows max_overflow = 10 more under pressure. That is fifteen connections per process, at peak. HikariCP defaults to a maximumPoolSize of ten. Neither default is wrong on its own. The problem is that nobody multiplies.

Run seven replicas of a Python service behind an autoscaler, each willing to burst to fifteen connections, and you have asked for a hundred and five. Your database allows roughly ninety-seven. The first six replicas are fine in a quiet hour; the moment traffic spikes and every replica reaches for its overflow at once, the seventh one starts printing too many clients already and cascading failures follow. Nothing changed on the database. What changed is that the load finally exercised a limit nobody had added up. The same maths applies to a headroom you have not measured elsewhere in the stack, whether that is connections or, as I have written about with memory and swap on a busy server, physical RAM.

Bound the pool inside the process

The first fix is a hard ceiling per process. In SQLAlchemy, set max_overflow = 0 so the pool can never exceed pool_size, and give it a pool_timeout so a starved request fails quickly and loudly instead of silently opening yet another connection:

from sqlalchemy import create_engine

engine = create_engine(
    "postgresql+psycopg://app:secret@pgbouncer:6432/appdb",
    pool_size=10,       # steady-state connections held by this process
    max_overflow=0,     # hard ceiling: never open more than pool_size
    pool_timeout=30,    # wait up to 30s for a free connection, then raise
    pool_pre_ping=True, # discard dead connections before handing them out
    pool_recycle=1800,  # recycle after 30 min to avoid stale sockets
)

Now the arithmetic is yours to control: replicas multiplied by pool_size is a number you choose deliberately, not one the framework picks for you. The same discipline applies on the JVM. HikariCP is happiest with a fixed, modest pool, so set the minimum equal to the maximum:

spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=10
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.max-lifetime=1800000

Keeping transactions short is the other half of this. Never hold an open transaction across a network call or a slow computation. Where your data access is tidied behind a clear boundary, as in the repository pattern for a FastAPI app, it is far easier to see and shorten the transaction than when session handling is scattered through your route handlers.

Put PgBouncer in front and let it absorb the fan-out

Bounded per-process pools are necessary but they do not scale infinitely; add enough replicas and the sum still exceeds the database. PgBouncer solves that by multiplexing many client connections onto a small set of real server connections. In transaction pooling mode a server connection is only assigned to a client for the duration of a single transaction, so a few dozen backends can serve thousands of clients:

[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb

[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 5000
default_pool_size = 20

PgBouncer’s default pool_mode is session, which holds a server connection for the whole client session and buys you almost nothing here; transaction is the mode that lets you fan in. One caveat worth knowing before you flip it: transaction mode breaks session-level features such as server-side prepared statements and SET that outlives a transaction, so point your application at port 6432 and disable driver-side prepared statements, or use a recent PgBouncer with max_prepared_statements set.

Stop leaked transactions holding connections forever

The last piece is a server-side backstop for the idle in transaction sessions you found earlier. PostgreSQL can kill them itself. The default of idle_in_transaction_session_timeout is 0, meaning disabled, which is why a leaked transaction can sit open until the process dies. Set a limit and reload:

ALTER SYSTEM SET idle_in_transaction_session_timeout = '30s';
SELECT pg_reload_conf();

Any transaction that sits idle for thirty seconds is now terminated, its connection returned, and the offending request fails visibly rather than quietly poisoning your capacity. That is a safety net, not a licence to leak, but it converts a slow strangulation into a loud error you can trace to a bad code path.

Put the three together and the failure mode disappears: bounded pools so each process has a known cost, PgBouncer so the fleet’s total cost stays small however many replicas you run, and an idle-in-transaction timeout so nothing holds a slot it is not using. The database was never too small. You just had not counted the connections you were asking it for.

Build and rescue work

Hands-on delivery of this kind is handled by Sixteen Pillars Studio.

Free interactive tool

Website compliance checklist

What your site has to do, based on what it actually does

Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.

Can you trust the architecture you have?

Architecture diagrams rarely show the reality of how systems actually operate. An independent review establishes what is really there.