KatInterview

Build a Bounded, Thread-Safe Resource Pool with Timeouts

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencythread-safetycondition-variable

Last 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, and close_all may 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.