CAPSTONE: CONNECTION POOL

Everything in this path, in one 40-line class

L320 MINRACE CONDITIONS
PREDICT

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 &lt; 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.

▶ SIMULATION
THREAD A
conn: —
state: idle
—
THREAD B
conn: —
state: idle
—
THREAD C
conn: —
state: idle
—
POOL (max 2)
open = 0 / 2 · idle: none · checked out: none · leaked: 0
waiters: none · mutex: free · t = 0 s
✓ open <= max✓ no waiter waits longer than 3 s
SCHEDULE
01[A]A: if (open < max) → sees 0, ok
02[B]B: if (open < max) → sees 0, ok
03[C]C: if (open < max) → sees 0, ok
04[A]A: open++, connect()
05[B]B: open++, connect()
06[C]C: open++, connect()
Start of racy size check scenario. 6 steps.
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);

Watch the open &lt;= 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.

BREAK IT NOT YET

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

FIX IT NOT YET

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.

Mental model:

every pool, cache, semaphore and rate limiter is the same object: a bounded resource behind a check-then-act. Put the check and the act under one lock, release in a finally, and never wait without a deadline. If you can state the two invariants (never more than max, every acquire returns) you can review any pool implementation in five minutes.

IN PRODUCTION

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.

IN INTERVIEWS

“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.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.

USED IN

Chapters that build on this lesson.