Build a Thread-Safe Connection Pool with Lazy Setup
System DesignModel answerLast 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 connectionclose()— 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
-
Lazy initialization. The pool's constructor must not open any connections. Connections are only created when
getConnection()is first called and actually needs one. -
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.
-
Hard cap. The total number of live underlying connections — whether in use or sitting idle — must never exceed
maxConnectionNum. -
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.
-
Return vs. destroy. Calling
close()on aPooledConnectionmust return its underlying connection to the pool for reuse — not close it permanently. Callingclose()on theConnectionPoolitself must close every underlying connection and cause any subsequent operation on the pool or on checked-out wrappers to raise an error. -
Guard against misuse.
PooledConnection.query()must raise an error if the wrapper has already been returned or if the pool has been shut down. -
Concurrency safety. Multiple threads will call
getConnection()andclose()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. -
Complexity analysis. Describe your core data structures and state the time and space complexity of
getConnection()andConnectionPool.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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The pool maintains three pieces of state under a single lock:
_idle— a stack (deque) of connections that have been returned and are ready to lend out again._all— a set of every live underlying connection, in-use or idle, needed so shutdown can close everything._reserved— a count of slots currently being created: a thread has claimed the right to create a new connection but hasn't finished yet.
The core invariant: len(_all) + _reserved <= maxConnectionNum. As long as this holds, the cap cannot be breached.
getConnection() works through three cases in order:
- If
_idleis non-empty, pop and return a wrapper around the top connection — O(1), no new connection needed. - If the pool is under the cap, increment
_reserved, release the lock, create the connection, then register it and decrement_reserved. - Otherwise, wait on a
Conditionuntil a connection comes back or the deadline passes, then re-check from case 1.
Design decisions
Create connections outside the lock. Opening a connection is slow (network, TLS, auth). Holding the pool lock during construction would serialize every concurrent borrower. Instead, the thread increments _reserved under the lock — claiming the slot atomically — then drops the lock to do the actual construction. If construction fails, _reserved is rolled back and a waiter is notified, so a failed attempt never permanently consumes capacity.
LIFO idle stack. Popping the most recently returned connection keeps "warm" connections active. Connections that nobody needs gradually go cold at the bottom, making them straightforward to identify for idle-timeout eviction if you add that feature later.
Exhaustion policy via Condition.wait. The wait runs in a while loop, which correctly handles spurious wakeups and the case where another thread wins the race when a connection is returned. The deadline is computed with time.monotonic() so clock adjustments don't affect the timeout.
Shutdown sequence. Set _closed, snapshot _all, clear internal state, call notify_all() to wake every blocked waiter, then close the snapshot outside the lock. Connections still checked out are closed immediately; any subsequent query() on them fails, and their eventual close() becomes a harmless no-op.
Concurrency safety
Pool-level races (two threads creating the last slot, missed wakeups): one threading.Lock plus a Condition built on it protects all pool state. Every read-modify-write on _idle, _all, _reserved, and _closed is inside with self._available. The "check idle → check cap → reserve" sequence is atomic, so two threads cannot both see capacity and both create a connection.
Double return (same connection returned twice, leading to two borrowers getting the same underlying connection): each PooledConnection carries a _returned flag and its own small lock. close() does an atomic check-and-set: if _returned is already True, it returns immediately. The connection can never land in _idle twice.
Use after return (connection returned while a query is still running on it): query() acquires the wrapper lock and checks _returned before calling through. close() also acquires the same wrapper lock, so it cannot mark the connection as returned while a query holds the lock. A slow query completes before the wrapper is released back to the pool.
The wrapper lock is per-instance, so a slow query on one borrowed connection does not block borrowers of other connections.
Complexity
| Operation | Time | Notes |
|---|---|---|
getConnection() — idle path | O(1) | deque pop + set lookup |
getConnection() — create path | O(1) amortized pool work + connection open cost | deque/set updates are O(1); network cost dominates |
getConnection() — wait path | O(1) pool work after wakeup | excludes time blocked |
PooledConnection.close() | O(1) | deque append + notify() |
ConnectionPool.close() | O(n), n ≤ maxConnectionNum | closes every connection in the snapshot |
| Space | O(maxConnectionNum) | idle stack + all-set + one small wrapper per checkout |
Edge cases
maxConnectionNum <= 0: raiseValueErrorin the constructor.timeout=0: non-blocking try — raise immediately when exhausted, nowait()call.Connection()raises: roll back_reserved, notify one waiter, re-raise.- Pool closed during creation: close the newly created connection and raise
PoolClosedError. - Pool closed while threads are waiting:
notify_all()wakes them; they re-check_closedand raisePoolClosedError. - Double
close()on pool or wrapper: idempotent. query()after wrapperclose()or after poolclose(): raisesPoolClosedError.
Implementation
import threading
import time
from collections import deque
_UNSET = object()
class PoolClosedError(RuntimeError):
pass
class PoolExhaustedError(TimeoutError):
pass
class ConnectionPool:
def __init__(self, maxConnectionNum, timeout=None, connection_factory=None):
if maxConnectionNum <= 0:
raise ValueError("maxConnectionNum must be a positive integer")
self._max = maxConnectionNum
self._timeout = timeout # None means block forever
self._factory = connection_factory or Connection
self._lock = threading.Lock()
self._available = threading.Condition(self._lock)
self._idle = deque() # ready-to-reuse connections (LIFO)
self._all = set() # every live underlying connection
self._reserved = 0 # slots claimed but not yet created
self._closed = False
@property
def closed(self):
return self._closed
def getConnection(self, timeout=_UNSET):
timeout = self._timeout if timeout is _UNSET else timeout
deadline = None if timeout is None else time.monotonic() + timeout
with self._available:
while True:
if self._closed:
raise PoolClosedError("pool is closed")
# Case 1: reuse an idle connection
if self._idle:
return PooledConnection(self, self._idle.pop())
# Case 2: under the cap — reserve a slot
if len(self._all) + self._reserved < self._max:
self._reserved += 1
break
# Case 3: exhausted — wait
if deadline is None:
self._available.wait()
else:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise PoolExhaustedError(
"timed out waiting for an available connection"
)
self._available.wait(remaining)
# Create the connection outside the lock so we don't block other callers.
try:
conn = self._factory()
except Exception:
with self._available:
self._reserved -= 1
self._available.notify()
raise
with self._available:
self._reserved -= 1
if self._closed:
# Pool was shut down while we were creating — close and bail.
try:
conn.close()
except Exception:
pass
raise PoolClosedError("pool was closed during connection setup")
self._all.add(conn)
return PooledConnection(self, conn)
def _release(self, conn):
"""Return a connection to the idle stack. Called by PooledConnection.close()."""
with self._available:
if self._closed or conn not in self._all:
# Pool shut down after this connection was checked out;
# it was already closed in ConnectionPool.close().
return
self._idle.append(conn)
self._available.notify()
def close(self):
with self._available:
if self._closed:
return
self._closed = True
snapshot = list(self._all)
self._all.clear()
self._idle.clear()
self._reserved = 0
self._available.notify_all()
# Close everything outside the lock.
for conn in snapshot:
try:
conn.close()
except Exception:
pass
def __enter__(self):
return self
def __exit__(self, *_):
self.close()
class PooledConnection:
def __init__(self, parent: ConnectionPool, connection):
self._pool = parent
self._conn = connection
self._lock = threading.Lock()
self._returned = False
def query(self):
# Hold the wrapper lock for the duration of the query so close()
# cannot return the connection while a query is in flight.
with self._lock:
if self._returned:
raise PoolClosedError(
"query called on a connection that has already been returned"
)
if self._pool.closed:
raise PoolClosedError("pool is closed")
return self._conn.query()
def close(self):
with self._lock:
if self._returned:
return # idempotent — double-return is a no-op
self._returned = True
self._pool._release(self._conn)
def __enter__(self):
return self
def __exit__(self, *_):
self.close()
Common mistakes
- Holding the lock while creating a connection. This serializes all borrowers during the slowest part of the operation. Reserve a slot (increment
_reserved) under the lock, then create outside it. - Skipping the
whileloop aroundwait(). A singleifmisses spurious wakeups and races where another thread takes the returned connection first. - Using a plain flag without a lock for
_returned. Without the per-wrapper lock, two concurrentclose()calls can both seeFalseand both append to the idle stack, breaking the "one connection per borrower" guarantee. - Not rolling back
_reservedon failed creation. If the factory throws and_reservedis not decremented, the pool permanently believes one more slot is occupied than actually is, silently reducing effective capacity. - Closing connections inside the pool lock.
close()on aConnectionmay block (flushing buffers, graceful disconnect). Do it outside the lock to avoid starving other callers.