LOAD-BEARINGfree
Low-level design dojoTier 13 · unit 27 of 31

Connection pool

A connection pool in front of a database that accepts a hard maximum of 100 connections. Callers borrow, use and return. It must survive callers that throw, and it must not become the outage it was built to prevent.

Every connection is in use and another caller asks for one. What should acquire() do?

  • Open an additional connection beyond the maximum
  • Return null and let the caller decide
  • Block until one frees, up to a timeout, then fail
  • Retry in a loop until one is available
Why

The maximum exists because the database has its own ceiling; exceeding it moves the outage rather than preventing it. Blocking with a bounded timeout is backpressure — callers queue briefly, and an unreasonable wait fails fast with a clear error instead of piling up invisibly. Returning null spreads the decision across a hundred call sites, and an untimed loop is a busy wait that hides the saturation.

Assign each responsibility.

Hand out an idle connection, or make the caller wait
Pool
Return itself to the pool when the caller closes it
PooledConnection
Open a brand new physical connection to the database
ConnectionFactory
Hold the maximum size, idle timeout and acquire timeout
PoolConfig
Discard a connection the database has already closed
Pool
Why

The wrapper is what makes correctness the default: callers write close() and get "return to the pool" for free, because the object they hold was never the real connection. Separating the factory means the pool holds no opinion about drivers or credentials, which is exactly what lets you test it against a fake.

Under load the pool empties and never refills, yet the database shows no running queries. Most likely cause?

  • The database is too slow
  • Connections are not returned when the caller throws
  • The maximum is set too low
  • The idle timeout is too short
Why

A connection borrowed on a path that throws before the return call is leaked permanently, and a leak looks exactly like saturation right up until you notice the connections are idle. The structural fix is the language scoped-cleanup construct — try-with-resources, defer, using — so the return happens on every exit path rather than only the happy one.

Queries are slow, so the team raises the pool maximum from 20 to 200. What usually happens?

  • Throughput rises roughly tenfold
  • Latency improves, throughput is unchanged
  • Throughput falls and latency gets worse
  • Nothing until the database is resized
Why

The database has a fixed number of cores and disks. Past that point extra concurrent queries do not run in parallel — they contend for locks, memory and CPU, and everything slows down together. A pool smaller than the database useful concurrency is a feature, not a limitation: the queue is where waiting is cheap, visible and survivable.