CAPSTONE: CONNECTION POOL
Everything in this path, in one 40-line class
A connection pool’s acquire(), in single-threaded Node: `if (this.open < this.max) { const c = await connect(); this.open++; return c; }`. Is it racy?
A connection pool is a bounded set of expensive objects with an acquire and a release. Every bug in this path lives in those two methods. if (open < max) followed by open++ is a check-then-act: two threads pass the check and the bound is gone. open++ itself is a read-modify-write that loses updates. A thread that acquires and throws without releasing leaks a connection, and after max leaks every waiter waits forever. A waiter with no timeout turns that leak into a hang. The fix is the same three moves each time: one lock around the whole decision, release in a finally, and a bounded wait that fails loudly.
class Pool {
async acquire() {
if (this.free.length) return this.free.pop();
if (this.open < this.max) { // check...
const c = await connect(); // ...act, later. Two callers both pass the check.
this.open++;
return c;
}
return new Promise((res) => this.waiters.push(res)); // no timeout: waits forever
}
release(c) { const w = this.waiters.shift(); w ? w(c) : this.free.push(c); }
}
const c = await pool.acquire();
await c.query(sql); // throws → c is never released
pool.release(c);class Pool {
async acquire(timeoutMs = 3000) {
await this.mutex.lock(); // check and act under one lock
try {
while (!this.free.length && this.open >= this.max) {
if (!(await this.cv.wait(this.mutex, timeoutMs))) throw new PoolTimeoutError();
} // woken: recheck, another caller may have won
if (this.free.length) return this.free.pop();
this.open++;
try { return await connect(); } catch (e) { this.open--; throw e; }
} finally { this.mutex.unlock(); }
}
async release(c) {
await this.mutex.lock();
try { this.free.push(c); this.cv.notify(); } finally { this.mutex.unlock(); }
}
}
const c = await pool.acquire();
try { await c.query(sql); } finally { pool.release(c); } // released on every path Watch the open <= max strip go red on the last create in RACY SIZE CHECK, and the waiter strip go red on the fourth second of LEAKED CONNECTION. In FIX: TIMEOUT ON WAIT the leak is still there, and the strip stays green because C gives up and says so.
Someone "fixed" the pool by taking a mutex around open++; connect(). The size check is still outside the lock. Three threads start on a cold pool with max = 2. Find the order that opens a third connection.
GOAL: open exceeds max at some point
Make the pool safe. acquire must never open more than max connections, must hand out idle ones, must throw when a timed wait expires instead of returning nothing, and withConn must release on every path. The pool state lives behind api, and the grader tries every interleaving of those calls across two or three threads: a racy create, a freed connection stolen before the woken waiter runs, a handler that throws, and a wait that times out.
pg-pool, HikariCP, SQLAlchemy's QueuePool, Go's database/sql, HTTP client connection pools, worker pools, semaphores and token buckets. The symptoms are a too-many-connections error from the database, or a service that stops answering while every thread waits on acquire.
“Design a thread-safe connection pool.” Write acquire and release with a mutex and a condition variable, state the two invariants out loud, then volunteer the three failure modes: racy size check, leak on exception, wait without timeout. The follow-ups are about fairness (FIFO waiters), validation of idle connections, and what happens when connect() itself fails under the lock.
USED IN
Chapters that build on this lesson.
- Connection handling, pooling and the process modelDatabases
- Technical decisions as a managerEngineering Manager