Design a Database Connection Pool
Data Structure DesignModel answerLast 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
ValueErrorifmax_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, returnNone. - 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 itsinitialize()method, and return it wrapped inside aPoolConnection.
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
RuntimeErrorif invoked on a lease that has already been closed.
- Delegates the call to the underlying
close() -> None:- Relinquishes the lease and returns the underlying
DBConnectionback to the parentConnectionPoolfor future reuse. - Must not call
DBConnection.close()(do not destroy the physical connection). - Calling
close()more than once on the samePoolConnectioninstance must raise aRuntimeError. - Once closed, any subsequent attempt to call
query(...)on this handle must fail.
- Relinquishes the lease and returns the underlying
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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Architecture
The core objective is separating resource ownership from resource usage:
DBConnection: Represents the actual expensive network socket/session. Owned permanently byConnectionPool.PoolConnection: Represents a temporary, short-lived handle (lease) provided to the application client. The client owns this handle until calling.close().
To fulfill the requirements efficiently:
- The pool maintains a stack or list of idle
DBConnectionobjects and an integer counter tracking active leases. - Calling
get_connection()generates a newPoolConnectionwrapper every time, even if it wraps a recycledDBConnection. - Calling
PoolConnection.close()invalidates that specific wrapper (disarming further queries) and places the rawDBConnectionback into the idle pool.
Client Code
│
│ 1. get_connection()
▼
┌───────────────────┐ 2. Check idle / capacity ┌─────────────────────┐
│ ConnectionPool │────────────────────────────────────>│ PoolConnection │
│ - active_count │ │ (Lease Handle) │
│ - idle_list [ ] │<────────────────────────────────────│ - _db_conn │
└───────────────────┘ 3. close() returns DBConn │ - _is_closed │
│ without destroying it └─────────────────────┘
│ │
│ creates / stores │ delegates query()
▼ ▼
┌─────────────────────────────────────────────────────────────────────────────────┐
│ DBConnection │
└─────────────────────────────────────────────────────────────────────────────────┘
Key Considerations & Edge Cases
- State Isolation: A closed
PoolConnectionmust clear its internal reference toDBConnection. This prevents "use-after-return" bugs where a client retains a reference to a closed handle and executes queries against a connection that has since been leased to another worker. - Double-Close Guard: Closing a handle twice must throw an exception. Without this check, a double close would push the same physical
DBConnectioninto the pool's idle queue twice, resulting in two separate clients receiving handles to the exact same physical connection. - Initialization Failures: If
DBConnection.initialize()throws an exception, the pool's active connection count must be decremented back, preserving pool capacity. - Thread Safety: Access to the active count and idle pool should be protected by synchronization locks to guarantee safety under concurrent execution.
Implementation
import threading
from typing import Optional, List
class DBConnection:
"""Provided interface (stubbed for executable completeness)."""
def __init__(self):
self._is_active = False
self._is_destroyed = False
def initialize(self) -> None:
self._is_active = True
def query(self, sql: str) -> str:
if not self._is_active or self._is_destroyed:
raise RuntimeError("Connection is not active or has been destroyed.")
return f"Executed: {sql}"
def close(self) -> None:
self._is_destroyed = True
self._is_active = False
class ConnectionPool:
def __init__(self, max_conn: int):
if max_conn <= 0:
raise ValueError("max_conn must be a positive integer.")
self._max_conn = max_conn
self._active_count = 0
self._idle_connections: List[DBConnection] = []
self._lock = threading.Lock()
def get_connection(self) -> Optional["PoolConnection"]:
with self._lock:
if self._active_count >= self._max_conn:
return None
# Increment capacity reservation upfront
self._active_count += 1
if self._idle_connections:
raw_conn = self._idle_connections.pop()
else:
raw_conn = None
# Instantiate physical connection outside lock if needed
if raw_conn is None:
try:
raw_conn = DBConnection()
raw_conn.initialize()
except Exception:
with self._lock:
self._active_count -= 1
raise
return PoolConnection(self, raw_conn)
def _release_connection(self, raw_conn: DBConnection) -> None:
"""Returns a physical connection to the idle pool."""
with self._lock:
self._idle_connections.append(raw_conn)
self._active_count -= 1
class PoolConnection:
def __init__(self, pool: ConnectionPool, raw_conn: DBConnection):
self._pool = pool
self._raw_conn: Optional[DBConnection] = raw_conn
self._closed = False
self._lock = threading.Lock()
def query(self, sql: str) -> str:
with self._lock:
if self._closed or self._raw_conn is None:
raise RuntimeError("Cannot execute query on a closed connection lease.")
return self._raw_conn.query(sql)
def close(self) -> None:
with self._lock:
if self._closed:
raise RuntimeError("Connection lease has already been closed.")
self._closed = True
conn_to_return = self._raw_conn
self._raw_conn = None
if conn_to_return is not None:
self._pool._release_connection(conn_to_return)
Complexity Analysis
get_connection(): $O(1)$ time complexity for pool state operations. Creation of a physical connection depends on external IO.query(): $O(1)$ time complexity overhead added by the wrapper.close(): $O(1)$ time complexity for stack push and counter updates.- Space Complexity: $O(N)$ where $N = \text{max_conn}$, bounded by the max allocated physical connections stored in memory/idle list.