How to Implement Database Connection Pooling
Size and configure a database connection pool correctly: match it to database limits, detect leaks, set timeouts, and avoid the full-pool stall.
On this page
Introduction
Opening a database connection costs a TCP handshake, authentication, and often a server process or thread allocation. Doing that per request is expensive, so applications keep a pool of ready connections and borrow one for the duration of a query. A pool that is too small queues requests; one that is too large overwhelms the database. The tuning is easy to get wrong because the symptoms look like a database problem while the cause is a client-side configuration.
This tutorial explains how to size a pool against database limits, how to set acquisition and idle timeouts, how to detect a connection leak, and how to make an exhausted pool fail fast instead of hanging. The examples reference PostgreSQL and common client libraries, but the reasoning applies to MySQL, SQL Server, and any wrapped pooler.
Size against the database, not the client
The upper bound on total connections is the database’s max_connections. Every application instance contributes its pool size times the number of process workers, and background jobs, migrations, and administrative sessions all consume connections too. Compute the total across all instances, leave headroom, and divide backward to a per-instance pool size. A pool of twenty across one instance is fine; the same value across twenty instances asks the database for four hundred.
Smaller than intuition suggests is usually right. When the database is CPU-bound, more connections do not add throughput; they add context switching and lock contention, making everything slower. A common starting point is a pool sized near the number of effective database cores per instance, then adjusted by measurement. Scale out with a pooler such as PgBouncer that multiplexes many client connections onto few server connections when the instance count is high.
-- inspect the server's limits and current usage
SHOW max_connections;
SELECT count(*) AS used,
count(*) FILTER (WHERE state = 'active') AS active
FROM pg_stat_activity
WHERE backend_type = 'client backend';
Set acquisition and idle timeouts
The acquisition timeout bounds how long a request waits for a free connection. Without it, the default is often infinite, so a full pool turns every request into a hang. Set a modest timeout, a few seconds, so the caller gets an error and can decide to retry, shed, or fail. A slow request that holds a connection too long is often better interrupted than allowed to block the pool.
The idle timeout closes connections that have been unused for a while so the database can reclaim resources, and so a connection does not sit out a network change and go stale. Set it below any server-side or proxy-side idle timeout so the client closes first, avoiding writes to a connection the server has already closed. Some pools also have a max lifetime that forces periodic recycling, useful when a proxy or firewall reaps long-lived connections.
import { Pool } from 'pg';
const pool = new Pool({
max: 10, // connections this process will open
connectionTimeoutMillis: 3000, // bound the wait for a free connection
idleTimeoutMillis: 30000, // close idle connections before the server does
maxUses: 7500, // recycle a connection after some uses
});
pool.on('error', (err) => {
// a backend connection died; log and let the pool replace it
console.error('idle client error', err.message);
});
Detect and prevent leaks
A connection leak is a connection borrowed and never returned, usually because an error path skipped the release. The pool’s in-use count climbs and never descends, and eventually the pool is empty and every request blocks. The structural prevention is to always acquire and release within the same scope, with the release in a finally block or managed by a helper that does it automatically.
Detect leaks by exposing the pool’s total, idle, and waiting counts as metrics. In a healthy pool, idle rises when traffic is low and waiting stays near zero. A steadily rising total with no idle is the signature of a leak; alert on it rather than waiting for the full-pool stall. Some libraries log a warning when a connection is held longer than a threshold, which pinpoints the slow or leaking caller.
async function withConnection<T>(fn: (client: unknown) => Promise<T>): Promise<T> {
const client = await pool.connect();
try {
return await fn(client);
} finally {
client.release(); // release even on error — prevents the leak
}
}
Fail fast when exhausted
A pool at its limit with a bounded acquisition timeout returns an error quickly. Treat that error as a load-shedding signal: return a 503 with a Retry-After, and increment a metric so the condition is visible. Do not queue the request behind an unbounded wait, because the wait is exactly what turns a transient load spike into a cascading timeout across the whole service.
Where the workload allows, use a pooler in transaction mode so many client requests share a small set of server connections between transactions. This decouples the application’s connection count from the database’s, letting you run many instances without exhausting server connections. Be aware that transaction-mode pooling forbids session-scoped state such as prepared statements keyed to a session or advisory locks held across transactions.
# drive the pool past its limit and assert fast failure, not a hang
seq 1 50 | xargs -P 50 -I{} curl -s -o /dev/null -w '%{http_code} %{time_total}\n' http://localhost:3000/heavy
# expect some 503s returned quickly rather than requests hanging for minutes
Test exhaustion and leak behavior
Write two tests. First, exhaust the pool and assert the caller receives an error within the acquisition timeout rather than hanging, which proves the timeout is set. Second, run a workload that throws inside the connection scope and assert the in-use count returns to zero afterward, which proves the release is unconditional. These tests turn the two failure modes, a hang and a leak, into caught regressions.
Common pitfalls
Sizing the pool per instance without multiplying by instance count, leaving the acquisition timeout unbounded, releasing a connection only on success, setting the client idle timeout longer than the server’s, and treating a full pool as a database problem instead of shedding load are the recurring mistakes. Computing the total, bounding acquisition, releasing in finally, aligning idle timeouts, and failing fast address them.
Conclusion
A connection pool is a small set of reusable connections guarded by timeouts and metrics. Size it from the database’s limit divided across instances, bound how long a request waits, release unconditionally, alert on a rising in-use count, and fail fast when exhausted. Self-check by exhausting the pool and asserting a quick error, and by throwing in the connection scope and asserting the count returns to zero. A well-tuned pool converts connection management from a mystery stall into a measured resource.
Sources: PostgreSQL: Connection and resource limits, PgBouncer: Pooling modes, HikariCP: About pool sizing.
FAQ
- How large should the pool be?
- Start small, often under ten connections per instance, and account for every instance: total connections must stay below the database's max_connections minus headroom for administration. A bigger pool is not faster when the database is the bottleneck; it just queues inside the database.
- Why do requests hang when the pool is exhausted?
- The default acquire behavior is to wait indefinitely for a free connection. When every connection is in use and none is released, requests queue forever. Set a bounded acquisition timeout so the caller fails fast and can retry or shed load.
Report a problem with this articleOpens a pre-filled issue on GitHub.