KatInterview

Design a Database Connection Pool

Data Structure DesignModel answer
MediumModel answerData Structure Designdesign-dsobject-oriented-designresource-management

Last updated

Implement a resource-managing connection pool wrapper that enforces pool limits, reuses idle connections, and handles lease lifecycles safely.

You are tasked with designing a database connection manager that controls access to low-level physical connections. The underlying resource is represented by an unmodifiable DBConnection class:

class DBConnection:
    def initialize(self) -> None:
        """Sets up the physical connection. Must be called once before querying."""
        pass

    def query(self, sql: str) -> str:
        """Executes a SQL query on the physical connection."""
        pass

    def close(self) -> None:
        """Destroys the physical connection permanently."""
        pass

Implement two classes, ConnectionPool and PoolConnection, according to the following requirements:

ConnectionPool(max_conn: int)

  • Initialization: Must raise a ValueError if max_conn <= 0.
  • get_connection() -> PoolConnection | None:
    • Checks out a connection lease to the caller.
    • If the count of currently checked-out active connections equals or exceeds max_conn, return None.
    • If an idle physical connection is available in the internal pool, reuse it.
    • If no idle connection exists and capacity allows, instantiate a new DBConnection, invoke its initialize() method, and return it wrapped inside a PoolConnection.

PoolConnection

  • Represents a single-use lease handle owned by the caller.
  • query(sql: str) -> str:
    • Delegates the call to the underlying DBConnection.query(sql).
    • Throws a RuntimeError if invoked on a lease that has already been closed.
  • close() -> None:
    • Relinquishes the lease and returns the underlying DBConnection back to the parent ConnectionPool for future reuse.
    • Must not call DBConnection.close() (do not destroy the physical connection).
    • Calling close() more than once on the same PoolConnection instance must raise a RuntimeError.
    • Once closed, any subsequent attempt to call query(...) on this handle must fail.

Hints

Hint 1

Distinguish between the lifetime of the underlying DBConnection resource and the lifetime of the PoolConnection lease object.

Hint 2

Consider what happens when a connection is returned: how do you ensure the handle cannot be reused by the original caller while preventing double-return bugs?

Hint 3

Think about error handling during initialization: if DBConnection.initialize() raises an exception, ensure the active count state is correctly rolled back.