KatInterview

Build a Thread-Safe Connection Pool with Lazy Setup

System DesignModel answer
MediumModel answerSystem Designconcurrencyconnection-poolthread-safety

Last updated

Design a lazily initialized, concurrency-safe connection pool with a wrapper class that returns connections on close, handles exhaustion via timeout, and supports clean shutdown.

Background

Database and network connections are expensive to open. A connection pool amortizes that cost by keeping a bounded set of live connections and lending them out to callers. Your job is to design and implement one from scratch, with a focus on correctness under concurrent access.

You are given a base class Connection that you may not modify. It exposes two methods:

  • query() — executes a query on the connection
  • close() — permanently closes the underlying connection

Implement two classes on top of it.


What to implement

ConnectionPool

__init__(maxConnectionNum)
getConnection() -> PooledConnection
close()

PooledConnection

__init__(parent: ConnectionPool, connection: Connection)
query()
close()

Requirements

  1. Lazy initialization. The pool's constructor must not open any connections. Connections are only created when getConnection() is first called and actually needs one.

  2. Prefer reuse over creation. When a caller requests a connection, hand back a previously returned idle connection if one is available. Only create a brand-new connection when there are no idle ones and the pool has not yet hit its cap.

  3. Hard cap. The total number of live underlying connections — whether in use or sitting idle — must never exceed maxConnectionNum.

  4. Exhaustion handling. When all connections are in use and the cap is reached, block the caller until one becomes available or a timeout expires. On timeout, raise an error. If no timeout is configured, block indefinitely.

  5. Return vs. destroy. Calling close() on a PooledConnection must return its underlying connection to the pool for reuse — not close it permanently. Calling close() on the ConnectionPool itself must close every underlying connection and cause any subsequent operation on the pool or on checked-out wrappers to raise an error.

  6. Guard against misuse. PooledConnection.query() must raise an error if the wrapper has already been returned or if the pool has been shut down.

  7. Concurrency safety. Multiple threads will call getConnection() and close() simultaneously. Identify which synchronization primitives you would use, explain where you need them, and implement accordingly. Specifically address: how you prevent two threads from both creating the last allowed connection, how you prevent the same connection from being returned to the pool twice, and how you avoid returning a connection that is still mid-query.

  8. Complexity analysis. Describe your core data structures and state the time and space complexity of getConnection() and ConnectionPool.close().


What a complete answer looks like

  • Working Python implementation of both classes
  • Explanation of every design decision (lazy creation, creating connections outside the lock, LIFO vs FIFO, shutdown sequence)
  • A concurrency analysis covering each of the three double-use hazards above
  • A complexity table
  • A list of edge cases and how your implementation handles each

Hints

Hint 1

Start by listing the three things the pool needs to track internally: idle (returned) connections ready for reuse, all live connections (so shutdown can close them), and slots currently being created but not yet registered. The core invariant is that those last two together never exceed the cap.

Hint 2

Opening a real connection involves a network round trip, TLS handshake, and auth. Think carefully about whether you want to hold the pool lock while that happens — and if not, how you safely reserve a slot before releasing the lock and register the new connection afterward without a race.

Hint 3

You need two levels of locking: one coarse lock (plus a condition variable) for pool-level state, and one fine-grained per-wrapper lock to make `close()` idempotent and to ensure a connection is never returned while a query is still running on it.