How to Implement a Connection Pool from Scratch
Build a bounded connection pool with acquire and release, idle reaping, health checks and fair waiting, and understand why pools exhaust.
On this page
Introduction
Opening a connection is expensive: a TCP handshake, a TLS negotiation, authentication, and for a database a server-side session with memory attached. A pool amortises that cost by keeping a set of open connections and lending them out. But a pool is also a backpressure device and a failure mode: done badly it deadlocks, leaks, or hands out connections that are already broken. Building one from scratch makes the mechanics obvious and teaches the invariants that off-the-shelf pools rely on.
The Core Invariant
A pool has a bounded set of resources. Acquire either returns an idle resource immediately, creates one if under the limit, or waits until one is released. Release returns the resource to the pool and wakes exactly one waiter. The count of resources handed out plus the count idle plus the count being created must never exceed the maximum size, and every acquisition must eventually be paired with a release even when the caller throws.
The most common bug is a leaked connection: a code path that acquires and then throws before releasing, or forgets to release in an error branch. The fix is structural, not disciplinary: make release part of a finally block or a scoped helper so it cannot be skipped.
class Pool<T> {
private idle: T[] = [];
private waiters: Array<(conn: T) => void> = [];
private total = 0;
constructor(
private max: number,
private create: () => Promise<T>,
private destroy: (c: T) => Promise<void>,
) {}
async acquire(): Promise<T> {
const conn = this.idle.pop();
if (conn) return conn;
if (this.total < this.max) {
this.total++;
try {
return await this.create();
} catch (err) {
this.total--;
throw err; // do not leak a slot on failure
}
}
return new Promise<T>((resolve) => this.waiters.push(resolve));
}
release(conn: T): void {
const waiter = this.waiters.shift();
if (waiter) waiter(conn); // hand off directly, no idle hop
else this.idle.push(conn);
}
}
Fair Waiting and Timeouts
Waiters should be served fairly, usually first-in-first-out, so a slow caller cannot starve a fast one. A plain array of waiters shifted from the front gives FIFO. Without fairness, a burst of requests can reorder arbitrarily and some requests wait far longer than others for no reason the user can see.
Every acquire needs a timeout. If the pool is exhausted and no connection frees up, a caller that waits forever holds a request open until its own deadline fires, which is usually too late. Acquire with a deadline returns an error that the caller can map to a clear 503 with a retry hint, and it releases the waiter slot so the queue does not grow unbounded.
acquireWithTimeout(ms: number): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
const i = this.waiters.indexOf(entry);
if (i >= 0) this.waiters.splice(i, 1); // remove stale waiter
reject(new Error('pool_timeout'));
}, ms);
const entry = (conn: T) => { clearTimeout(timer); resolve(conn); };
// push via acquire() fast-path or enqueue the entry
this.waiters.push(entry as unknown as (c: T) => void);
// ... fast path omitted for brevity: try idle/create first
});
}
Idle Reaping and Max Lifetime
Idle connections waste server resources and can be closed silently by a firewall or a database idle timeout, so they must not be kept forever. Reap idle connections after a short idle timeout and close them gracefully. Also cap the maximum lifetime of a connection: recycling a connection after, say, thirty minutes bounds the damage from a slow memory leak on the server side and lets rolling restarts take effect.
Reaping must not close a connection that is about to be used. Only reap from the idle list, and only when the pool is above a minimum size so a quiet period does not drain the pool to nothing and force a thundering herd of new connections on the next burst.
// Periodic maintenance: close idle and over-age connections.
setInterval(async () => {
const now = Date.now();
while (this.idle.length > this.min && now - this.idleAt[0] > this.idleTimeoutMs) {
const conn = this.idle.shift();
if (conn) {
this.total--;
await this.destroy(conn);
}
}
}, this.reapIntervalMs);
Health Checks and Broken Connections
A pool must not hand out a dead connection. Connections die from server restarts, network partitions and idle timeouts, and a caller that receives one fails for a reason unrelated to its request. Validate a connection before handing it out, either with a cheap liveness query or by tracking errors and evicting a connection that fails.
For database pools, a one-line validation query such as SELECT 1 is cheap but not free; run it only when a connection has been idle beyond a threshold, not on every acquire. For failing connections discovered during use, destroy them and do not return them to the pool, so a broken connection is retired rather than recycled.
async acquire(): Promise<T> {
while (true) {
const conn = this.idle.pop();
if (!conn) return this.createOrWait();
if (this.isHealthy(conn)) return conn; // may run SELECT 1 if stale
this.total--;
await this.destroy(conn); // evict the broken one, try again
}
}
Sizing the Pool
Bigger is not better. A pool larger than the downstream system can serve converts database load into overload: hundreds of connections each competing for the same CPU and locks make the database slower than a modest pool with a queue. Size to the downstream capacity, and let the pool’s waiters be the backpressure signal.
As a starting point, size a database pool to a small multiple of the database’s CPU cores, because most queries are CPU or lock bound rather than network bound. Then measure. If wait time is high while the database is not saturated, the pool is too small; if the database is saturated and latency is climbing with the pool size, it is too big.
# pool sizing heuristic for a database
max = cores * 2 + effective_spindle_count_approx (start here)
then watch:
pool_wait_time high + db not saturated -> grow a little
db saturated + latency rises with max -> shrink
checkouts_outstanding ~= max always -> callers are leaking
Observability and Leak Detection
Export pool metrics: total, idle, in-use, waiters, wait time and acquisition count. The in-use count pinned at the maximum with a growing waiter queue is exhaustion; a steadily rising total that never returns to idle is a leak. Because leaks are the most common pool bug, a counter of checkouts with no matching check-in over time is worth building explicitly.
Attach a stack trace to each checkout in development so a leak can be traced to the line that forgot to release. In production, a sampled version of the same idea, or a count of outstanding checkouts older than a threshold, catches the leak without the memory cost.
Common Pitfalls and Conclusion
Do not forget to release on the error path. Do not create unbounded connections when the pool is exhausted; queue instead. Do not validate on every acquire if validation is expensive. Do not keep idle connections forever. Do not size the pool larger than the downstream can serve. And do not ignore pool metrics, because exhaustion and leaks are invisible until requests start timing out.
A connection pool is a small, well-understood concurrency primitive: a bounded set of resources, fair waiting with timeouts, idle reaping, health checks and honest metrics. Build it once and the invariants become obvious, which makes you far better at debugging the pools you do not build yourself.
Sources: HikariCP: About pool sizing, node-postgres: Pooling, Go: sync.Pool.
FAQ
- Should the pool create connections eagerly or lazily?
- Lazily, on demand, avoids paying for connections that are never used. A small warm pool at startup can smooth the first burst, but creating eagerly up to the maximum wastes resources when load is low.
- What is the most common pool bug in production?
- Leaked connections: an acquire path that throws before releasing, so the in-use count creeps up until the pool is exhausted. Fix it structurally with scoped helpers and detect it with a checkouts-versus-check-ins counter.
Report a problem with this articleOpens a pre-filled issue on GitHub.