How to Diagnose Connection Pool Exhaustion
Find why a connection pool runs dry, distinguish leaks from slowness, and size and instrument the pool so it recovers.
On this page
Introduction
A connection pool limits how many connections a service holds open to a database or another service. When every connection is in use and callers are queuing for one, the pool is exhausted, and the symptom is a service that becomes slow or returns errors even though the database itself is healthy. Pool exhaustion is a symptom with several distinct causes: a connection leak, queries that got slower, a burst of concurrency, or a pool that was never sized for the workload. This article shows how to tell those apart, what to measure, and how to make the pool recover instead of collapse.
What Pool Exhaustion Looks Like
The first sign is a growing wait time to acquire a connection, followed by acquire timeouts, followed by a cascade of request failures. Meanwhile the database may show normal CPU and few slow queries, which is confusing until you realize the bottleneck is the client-side pool, not the server. Every request that needs a connection waits behind the others, and a queue forms where there was none.
Distinguish two states: the pool is busy because the work is genuinely concurrent, versus the pool is starved because connections are held but idle. The first needs a bigger pool or faster queries; the second needs a leak fixed or a timeout added. The metrics that tell them apart are connections-in-use over time and the age of the oldest checked-out connection.
Measuring Pool Usage
Emit at least: total connections, idle connections, connections in use, waiters, and the wait time to acquire. The shape over time is the diagnosis. Connections in use pinned at the maximum with a non-empty waiter queue means saturation. Connections in use that step up and never come down suggests a leak: connections are checked out and never returned.
// Expose pool metrics (illustrative, using pg Pool internals via events)
const { Pool } = require('pg');
const pool = new Pool({ max: 20, connectionTimeoutMillis: 2000 });
setInterval(() => {
const total = pool.totalCount;
const idle = pool.idleCount;
const waiting = pool.waitingCount;
const inUse = total - idle;
metrics.gauge('db_pool_in_use', inUse);
metrics.gauge('db_pool_total', total);
metrics.gauge('db_pool_waiting', waiting);
if (waiting > 0) logger.warn({ inUse, total, waiting }, 'pool saturated');
}, 5000);
// Always release in a finally block; a missing release is the classic leak.
async function query(sql, params) {
const client = await pool.connect();
try {
return await client.query(sql, params);
} finally {
client.release();
}
}
Common Causes
The most common cause is a leak: a code path acquires a connection and returns early on an error before releasing it, or forgets to release at all. Over hours this consumes the pool one connection at a time. The second is slower queries: a query that used to take 10ms and now takes 1s holds its connection a hundred times longer, so the same load needs a hundred times the connections. The third is a concurrency spike: a new code path fans out without a bound and asks for more connections than the pool holds.
Less obvious causes include transactions left open, which hold a connection until commit or rollback, and connection-level statements such as SET that pin a session. Long-running transactions are especially damaging because they also hold row locks and can block other work, which is the same problem as lock contention viewed from a different angle.
Timeouts and Leaks
Two timeouts prevent a bad situation from becoming fatal. A connection acquire timeout bounds how long a request waits for a connection, so the request fails fast and the queue cannot grow without end. A statement timeout bounds how long a query may run, so a slow query releases its connection instead of holding it forever. Without the first, waiters accumulate; without the second, a single bad query can drain the pool.
-- Bound query runtime at the session level so a stuck query cannot hold a connection
ALTER ROLE app_user SET statement_timeout = '5s';
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '10s';
ALTER ROLE app_user SET lock_timeout = '2s';
-- Find long-running queries still holding connections
SELECT pid, now() - query_start AS runtime, state, left(query, 80) AS query
FROM pg_stat_activity
WHERE state = 'active'
ORDER BY runtime DESC
LIMIT 10;
Sizing the Pool
An oversized pool is not a fix. More connections than the database can serve concurrently simply moves the queue to the database, where it consumes memory and causes lock contention, and can make throughput worse. A useful starting point is a modest number per instance, sized so that total connections across all instances stay within what the database was provisioned for.
Calculate from the database’s capacity, not from the client’s concurrency. If the database handles two hundred active queries well, and you run four service instances, each pool should be well under fifty and should leave headroom. Add a bounded queue in front of the pool so excess requests wait predictably rather than multiplying connections. A pool with a queue and a fast failure is healthier than one with unlimited connections.
Backpressure and Recovery
The right response to exhaustion is to shed load, not to open more connections. When the pool queue exceeds a threshold, reject low-priority requests immediately so high-priority ones can get through. This keeps the service responsive under overload instead of timing out everything equally. Bounded concurrency at the call site achieves the same effect before the pool is even reached.
Make recovery automatic: release connections in a finally block so no path can leak, set the acquire and statement timeouts so a stuck operation self-terminates, and alert on pool-in-use sustained near the maximum so the team learns before users do. Test the pool under load with a deliberate slow query to confirm it recovers rather than spirals.
Conclusion
Pool exhaustion is a client-side bottleneck that looks like a database problem. Measure connections in use, idle, waiting and the acquire wait time; a leak shows as in-use that never falls, saturation as a queue at the maximum, and slowness as a pool that is busy because queries got longer. Bound the wait with an acquire timeout, bound the query with a statement timeout, size the pool from database capacity with a bounded queue, and shed load instead of opening more connections. Then exhaustion becomes a bounded, recoverable event rather than a spiral.
Sources: node-postgres: pool, PostgreSQL: connection limits, HikariCP: about pool sizing.
FAQ
- How do I tell a leak from simple saturation?
- Watch connections in use over time. Saturation shows in-use pinned at the maximum only while load is high and returning to idle afterward. A leak shows a step that never comes back down, because connections are checked out and never released.
- Is a bigger pool the fix for exhaustion?
- Usually not. More connections than the database can serve moves the queue to the database and can reduce throughput. Size the pool from database capacity, reserve headroom, and shed load with a bounded queue rather than adding connections.
Report a problem with this articleOpens a pre-filled issue on GitHub.