Connection Pooling
Build a connection pool as code: a bounded set of reusable connections, a wait with a timeout, validation, lifetime limits, and the sizing math from HikariCP and PostgreSQL.
Overview
Opening a database connection is several network round trips: the TCP handshake, usually a TLS handshake, then authentication and session setup on the server. Doing that for every query would spend more time connecting than querying, and the server would hold a session for every request in flight. A connection pool opens a small number of connections once, hands them out for the length of one query or transaction, and takes them back.
The interview question looks like a data-structure exercise, and the first half is: a bounded set of objects, a blocking acquire with a timeout, a release. The second half is where the marks are: what happens when the pool is empty, how you notice a leaked connection, why a connection that sat idle for an hour may be dead, and how many connections a database can actually use. This topic builds the pool in Python and takes the numbers from HikariCP's and PostgreSQL's own documentation.
What the pool does per request
The application never opens a connection itself. It borrows one, runs the query and returns it, and the expensive handshake happened once, at startup or on first use. One request goes through the pool in five steps.
- The application calls acquire(timeout) on the pool.
- The pool hands back a connection, c1, that was idle and has been validated.
- The application sends its query to the database over c1.
- The database returns the rows.
- The application calls release(c1). The connection is idle again, and a waiting thread, if there is one, gets it.
Set side by side, the two ways of working differ in three of their four stages. Without a pool, every request pays to connect (TCP, TLS, authenticate, set up the session) and then pays again to close, tearing down the session and the socket. With a pool, the connect cost is paid once per connection, at startup or first use, and 'closing' only returns the connection, which stays open. Running the query is the same either way. The biggest difference is on the server: without a pool it holds one session per in-flight request, with no upper bound; with a pool it holds at most the pool's maximum.
Interview questions
- Design a connection pool. What is the core data structure?
- How do you size a connection pool correctly?
- What is connection pool exhaustion, and how do you detect and prevent it?
- How do you handle stale connections that the database or network has broken?
- Where does a server-side pooler such as PgBouncer fit, and what does transaction pooling break?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio