Build a Bounded, Thread-Safe Resource Pool with Timeouts
Data Structure DesignModel answerLast updated
Implement a thread-safe pool that lazily creates up to N connections, reuses healthy ones, blocks callers with a deadline when exhausted, and shuts down cleanly.
Bounded Connection Pool
Opening a database connection is slow, but allowing an unlimited number of them can overload the database. Build a thread-safe pool that caps the number of live connections, reuses them, checks their health, and makes callers wait when everything is in use.
You are given a connection type with this interface:
class Connection:
def is_valid(self) -> bool:
"""True if the connection is still alive."""
def close(self) -> None:
"""Release the underlying resource."""
Implement the following class:
from typing import Callable, Optional
class ConnectionPool:
def __init__(self, max_connections: int, factory: Callable[[], Connection]):
"""Set the capacity and remember the callable used to open new connections."""
def acquire(self, timeout: Optional[float] = None) -> Connection:
"""
Hand out a healthy connection.
- Reuse an idle one if available.
- Otherwise create a new one if the pool is below max_connections.
- Otherwise block until one is returned, or until `timeout` seconds
pass, in which case raise TimeoutError.
- If a connection taken from the idle set is not valid, discard it and
get or create another.
"""
def release(self, conn: Connection) -> None:
"""
Give a connection back. If it is no longer valid, close it and free its
slot so a replacement can be created later.
"""
def close_all(self) -> None:
"""
Close every idle connection and shut the pool down. Any later call to
acquire() must raise RuntimeError.
"""
Example
pool = ConnectionPool(max_connections=2, factory=create_db_connection)
# Thread 1
conn1 = pool.acquire(timeout=1.0)
# Thread 2
conn2 = pool.acquire(timeout=1.0)
# Thread 3: the pool is full, so this waits for a release
try:
conn3 = pool.acquire(timeout=0.5)
except TimeoutError:
print("Timed out waiting for connection")
pool.release(conn1)
conn3 = pool.acquire(timeout=0.5) # succeeds and receives conn1
Requirements and edge cases
1 <= max_connections <= 1000.acquire,release, andclose_allmay be called concurrently from many threads.- Connections must be created lazily, never all upfront.
- Releasing a dead connection must not permanently shrink the pool's capacity.
- Releasing a connection the pool did not hand out, or releasing the same one twice, must be detected and rejected.
What to deliver
Describe your design, show the code, explain why it is correct under concurrency, and state the complexity. Be ready to discuss what happens on timeouts, factory failures, and shutdown while threads are waiting.
Hints
Hint 1
Keep all bookkeeping behind a single lock: an idle deque, a set of checked-out connections, a counter of consumed slots, and a closed flag. Use a condition variable on that lock for waiting.
Hint 2
Do not call the factory, is_valid, or close while holding the lock, since they do network I/O. Instead, reserve a slot under the lock (pop an idle connection or increment the counter), do the slow work outside, then re-lock to commit or roll back.
Hint 3
Every path that destroys a connection or fails to create one must decrement the slot counter and notify a waiter. Compute one absolute deadline with a monotonic clock and wait only for the remaining time on each wakeup.
Hint 4
For shutdown, set the closed flag, close idle connections, and wake all waiters so they raise RuntimeError. Connections still checked out are closed when they come back.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A pool is a bounded resource manager, so the core is a small amount of shared state protected by one lock, plus a condition variable for blocking.
State (all guarded by one lock):
idle: deque of healthy connections ready for reuse.in_use: set of connections currently checked out. This is what catches double releases and foreign connections.total: the number of slots consumed, counting idle connections, in-use connections, and slots reserved for a connection being created or validated.closed: shutdown flag.
A threading.Condition on the lock lets acquire sleep when total == max and nothing is idle. Anything that frees capacity calls notify(): a connection going idle, an invalid connection being discarded, or a failed factory call.
Key design choice: no I/O under the lock
factory(), is_valid(), and close() can each take milliseconds. If they ran under the lock, every other thread would stall. So acquire has three phases:
- Reserve (locked). Wait until something is possible. Pop an idle connection, or increment
totalto claim a creation slot. - Slow work (unlocked). Create the connection, or validate the popped one.
- Commit (locked). Add to
in_useif the pool is still open. Otherwise give back the slot and close the connection.
Incrementing total before calling the factory is what enforces the cap. Two threads cannot both observe total < max and both create.
Why it is correct
- Capacity bound:
total <= max_connectionsalways holds because slots are claimed under the lock before creation. - No capacity leak: each path that destroys a connection (invalid on acquire, invalid on release, factory exception, release after shutdown) decrements
totaland notifies one waiter. - No lost wakeups: waiters re-check their predicate in a
whileloop, so spurious or stolen wakeups are harmless. One freed slot produces onenotify(). - Timeouts: compute
deadline = time.monotonic() + timeoutonce and wait fordeadline - noweach iteration, so repeated wakeups cannot stretch the total wait. - Shutdown:
close_allsetsclosed, closes idle connections, and callsnotify_all()so blocked callers raiseRuntimeError. In-use connections are closed when released. A thread in the middle of creating or validating re-checksclosedat commit time.
Code
import threading
import time
from collections import deque
from typing import Callable, Optional
class ConnectionPool:
def __init__(self, max_connections: int, factory: Callable[[], "Connection"]):
if max_connections < 1:
raise ValueError("max_connections must be >= 1")
self._max = max_connections
self._factory = factory
self._cond = threading.Condition(threading.Lock())
self._idle = deque()
self._in_use = set()
self._total = 0
self._closed = False
@staticmethod
def _safe_valid(conn) -> bool:
try:
return conn.is_valid()
except Exception:
return False
@staticmethod
def _safe_close(conn) -> None:
try:
conn.close()
except Exception:
pass
def _free_slot(self) -> None: # caller holds the lock
self._total -= 1
self._cond.notify()
def acquire(self, timeout: Optional[float] = None):
deadline = None if timeout is None else time.monotonic() + timeout
while True:
conn, create = None, False
with self._cond: # phase 1: reserve
while True:
if self._closed:
raise RuntimeError("pool is closed")
if self._idle:
conn = self._idle.pop() # LIFO: warmest first
break
if self._total < self._max:
self._total += 1
create = True
break
if deadline is None:
self._cond.wait()
else:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("timed out waiting for connection")
self._cond.wait(remaining)
if create: # phase 2: slow work
try:
conn = self._factory()
except BaseException:
with self._cond:
self._free_slot()
raise
elif not self._safe_valid(conn):
self._safe_close(conn)
with self._cond:
self._free_slot()
continue # try again
with self._cond: # phase 3: commit
if not self._closed:
self._in_use.add(conn)
return conn
self._free_slot()
self._safe_close(conn)
raise RuntimeError("pool is closed")
def release(self, conn) -> None:
with self._cond:
if conn not in self._in_use:
raise ValueError("connection not checked out from this pool")
self._in_use.remove(conn)
closed = self._closed
healthy = (not closed) and self._safe_valid(conn)
with self._cond:
if healthy and not self._closed:
self._idle.append(conn)
self._cond.notify()
return
self._free_slot()
self._safe_close(conn)
def close_all(self) -> None:
with self._cond:
if self._closed:
return
self._closed = True
to_close = list(self._idle)
self._idle.clear()
self._total -= len(to_close)
self._cond.notify_all()
for c in to_close:
self._safe_close(c)
Complexity
- Time: O(1) pool bookkeeping per
acquire/release, plus the cost offactory()andis_valid(). If several idle connections are dead,acquireloops once per dead one.close_allis O(k) for k idle connections. - Space: O(max_connections).
Edge cases
timeout=Nonewaits forever;timeout <= 0behaves as a non-blocking try and raisesTimeoutErrorimmediately if nothing is available.- If
factory()raises, the reserved slot is returned, a waiter is notified, and the exception propagates. - If
is_valid()raises, treat the connection as invalid. - Double release or a foreign connection raises
ValueErrorbecause it is not inin_use. - Release after
close_allcloses the connection and frees the slot without error. - A second
close_allis a no-op.
Common mistakes
- Calling the factory or
is_validunder the lock, which serializes all callers behind network latency. - Checking
total < maxand creating in separate critical sections, which lets the pool exceed its cap. - Using
ifinstead ofwhilearoundwait(), or restarting the full timeout after each wakeup. - Forgetting to decrement the counter on factory failure or invalid release, which slowly leaks capacity until every caller times out.
- Not waking waiters on shutdown, leaving them blocked forever.
- Tracking no set of checked-out connections, so a double release inserts the same connection into idle twice and two threads then share it.
Trade-offs and follow-ups
LIFO idle reuse keeps hot connections warm and lets surplus ones age out, but FIFO spreads load more evenly. Validating on every acquire adds a round trip; production pools often validate only after an idle period or on a background thread. Using notify() per freed slot avoids a thundering herd, while notify_all() is reserved for shutdown. Fairness is not guaranteed here; a FIFO queue of waiters would be needed if starvation matters.