Lesson · JDBC
Connection Pools: borrow, return, and why bigger is not faster
15 min readConnection Pools
Opening a database connection is a TCP handshake, TLS, authentication and a new session on the server. A pool keeps a small set of those connections open and hands them out as logical handles, where close() returns the handle instead of killing the socket. Under pressure you meet the two signature incidents: leaks that starve the pool, and pools so large they slow the database down.
The cost you are paying per connection
The first version of almost every JDBC service opens its connection inside the request: DriverManager.getConnection(url, user, pass), run the query, close. It works on your laptop, and it hides a bill. Every one of those calls is a TCP handshake, a TLS negotiation, an authentication round trip, and a brand new session inside the database.
The database pays for as long as the connection lives. PostgreSQL forks a backend process per connection, and MySQL dedicates a thread, so a connection is expensive to create and not free to keep. Open one per request and you re-pay the creation cost at exactly the moment traffic peaks.
// The version that works on your laptop and falls over under load. public List<Order> recentOrders(long customerId) throws SQLException { try (Connection conn = DriverManager.getConnection( // TCP + TLS + auth + server session "jdbc:postgresql://db.internal:5432/shop", "shop_app", System.getenv("DB_PASSWORD")); PreparedStatement st = conn.prepareStatement( "SELECT id, total FROM orders WHERE customer_id = ? ORDER BY placed_at DESC")) { st.setLong(1, customerId); try (ResultSet rs = st.executeQuery()) { List<Order> orders = new ArrayList<>(); while (rs.next()) { orders.add(new Order(rs.getLong("id"), rs.getBigDecimal("total"))); } return orders; } } }
A database connection is a session, not a function call. Creating it costs network round trips and server-side setup; keeping thousands of them costs processes, threads and memory. A pool is how you pay that bill a fixed number of times.
A pool is a bounded set of handles
A pool opens a bounded number of physical connections at startup and keeps them open. dataSource.getConnection() hands out a logical wrapper around one of them, and close() on that wrapper returns it to the pool instead of closing the socket. Your code keeps the contract it always had: borrow a Connection, close it when the work is done.
That is why try-with-resources stays exactly right: it closes on every path, and the logical close is the return. A borrow that never closes is not an efficiency trick; it is a handle the next request cannot see.
try (Connection conn = dataSource.getConnection()) { // borrow runBusinessLogic(conn); // one unit of work, one transaction } // close(): the pool takes the handle back
- borrow:
getConnection()takes an idle connection, marks it active, and waits in a queue when every one is taken. - return:
close()on the logical handle puts the connection back, with the socket, TLS session and server session still open. - evict: the pool closes a physical connection when it is too old, too idle or fails a validation check, and replaces it in the background.
close() on a pooled handle means return. Same method, same guarantees for the caller, different physical meaning underneath.
DataSource first, HikariCP in practice
The interface your code should depend on is javax.sql.DataSource, not DriverManager: it is the JDBC spec's connection factory, and it hides the difference between a fresh connection and a pooled one behind a single method. Construct it once at startup, keep the reference, and hand it to the repositories.
HikariCP is the default choice in the Java ecosystem: a small dependency, bundled inside Spring Boot, and used by most production stacks. Its defaults are deliberately boring, and they are the numbers you should be able to reason about.
| Setting | Documented default | What to reason about |
|---|---|---|
| maximumPoolSize | 10 | The ceiling on physical connections. Every other setting describes behaviour under this ceiling. |
| minimumIdle | same as maximumPoolSize | A fixed-size pool by default: no shrinking below the ceiling, so no reconnect storm after a burst. |
| connectionTimeout | 30 s (minimum 250 ms) | How long getConnection waits before throwing. This is the number your alerts will quote. |
| idleTimeout | 10 min | Applies only when minimumIdle is lower: idle connections above the floor are closed. |
| maxLifetime | 30 min | Recycle age. Keep it under every database or proxy idle cutoff in the path. |
| keepaliveTime | 0 (disabled) | Periodic keepalive on idle connections; useful where a firewall closes quiet sockets. |
| validationTimeout | 5 s (minimum 250 ms) | How long a liveness check (Connection.isValid) may take before the connection is treated as dead. |
| leakDetectionThreshold | 0 (disabled) | Above its minimum, the pool logs the borrowing stack trace when a handle has not returned in time. |
These are widely documented HikariCP defaults, and versions adjust them. Treat them as starting points, and set the ones your infrastructure dictates (maxLifetime below the shortest idle cutoff) from fact rather than memory.
Connections that die while the pool believes they are good
Sockets do not die politely, and the pool can be the last to know. A restart, a failover, or a proxy that closes idle sessions leaves the pool holding handles to conversations the server has already ended, and the first request to borrow one finds out with a connection reset.
Two settings answer that. maxLifetime retires each connection before the infrastructure would, so the server's own timeout never wins the race; validation on borrow (HikariCP checks with Connection.isValid()) filters the connections that died anyway and replaces them.
- Keep maxLifetime under the shortest cutoff in the path: database, proxy, load balancer, connection pooler. When two layers disagree about who lives longer, the pool loses.
- Validate on borrow: one liveness round trip per borrow catches deaths the pool did not observe. It is a filter, not a substitute for maxLifetime.
- Expose the pool's metrics: active, idle and waiting counts, plus connection-acquire times. They tell you which layer is actually stuck.
The pool's view of a connection can outlive the server's. Recycling below the cutoff and validating on borrow are how you make that gap safe.
The leak: pool at its limit, database idle
The classic production incident draws a picture that does not add up: the application cannot get connections, the pool sits at its maximum, and the database is idle. The pool is not out of capacity, it is out of returns. Somewhere a borrow never reaches close(): an early return, a thrown exception, a branch that skips the cleanup.
connectionTimeout turns that into the error quoted in tickets: getConnection waits, then throws SQLTransientConnectionException: Connection is not available, request timed out after 30000ms. Fix the borrowing path rather than enlarging the pool; more handles only make the leak surface later, at higher cost.
// The leak: an exception skips close(), and the handle is never returned. public void exportOrder(long orderId) throws SQLException { Connection conn = dataSource.getConnection(); // borrowed PreparedStatement st = conn.prepareStatement("UPDATE orders SET exported = true WHERE id = ?"); st.setLong(1, orderId); st.executeUpdate(); if (orderId < 0) { throw new IllegalStateException("audit trail missing"); // close() below never runs } conn.close(); } // The fix: close() runs on the success path, the early return and the exception path. public void exportOrderFixed(long orderId) throws SQLException { try (Connection conn = dataSource.getConnection(); PreparedStatement st = conn.prepareStatement("UPDATE orders SET exported = true WHERE id = ?")) { st.setLong(1, orderId); st.executeUpdate(); } }
- leakDetectionThreshold: with it enabled, the pool logs the stack trace of the borrow that never returned. That log names the method to fix.
- Read the counters first: active pinned at maximum, idle at zero and a bored database is a leak signature, not a sizing signal.
- Search for borrows without try-with-resources instead of adding capacity. The fix belongs in the code the log names.
"Timeout waiting for connection" with an idle database means a borrow was never returned. The pool is describing your code accurately; believe it.
Connection pool 3 physical connections
The pool starts: three physical connections are opened and left idle. Each one already paid the TCP handshake, TLS and authentication, and holds a server-side session.
Bigger is not faster
The timeout reads like a request for a larger number, and enlarging is usually wrong. The database has finite cores, disk IO and memory; each extra connection adds a session, a stack and more context switching, and past a knee they contend for the same locks and buffers instead of doing useful work. Throughput falls as the pool grows.
The wait queue is backpressure: it bounds how much work reaches the database at once. If it is permanently full, the answer is shorter transactions or a faster query, not a bigger bound.
- Keep transactions short: most pool pressure is a connection held while the code does something that is not database work.
- Measure before resizing: run a load test at two pool sizes and compare throughput and p99 latency. The widely quoted cores x 2 + spindles heuristic from PostgreSQL performance work exists because the useful pool is smaller than people guess.
- Watch waiting over time: sustained waiting is a question about transaction duration first, and pool size second.
A pool bound protects the database, and the queue is information. Size from measurement, and treat a full queue as a question about your transactions.
Session state: what resets, what does not
A returned connection is not automatically a clean one; the pool makes it clean. HikariCP resets autoCommit, transaction isolation, read-only and the catalog on return, and rolls back transactions that were left open, which is what makes connections interchangeable between requests.
What the pool cannot clean is the rest of the session: temporary tables, session variables, advisory locks, anything a SET statement touched. Do not stash those across requests, because the next request gets whichever connection is free. And one transaction must stay on one connection from begin to commit.
Borrow, do one bounded unit of work, return. Session state belongs to the transaction that set it, and that transaction belongs to one connection.
The timeout is the pool, the leak is in your code
"Connection is not available, request timed out after 30000ms" reads like a capacity problem and usually is not: active sits at the ceiling while the database is idle, because a borrow somewhere skipped its return. Turn on leakDetectionThreshold, read the logged stack trace, fix that path. Enlarging the pool hides the leak and moves the pressure closer to the database's own limits.
Interview angles
Why not open a connection per request?+
Because a physical connection costs a TCP handshake, TLS, authentication and a server-side session, and the database keeps resources per session (PostgreSQL forks a backend process, MySQL dedicates a thread). Pooling pays that cost once per pooled connection instead of once per request.
What does close() on a pooled connection do?+
It returns the logical handle to the pool; the physical socket stays open and reusable. That is exactly why try-with-resources remains the right pattern: every path returns the handle.
Why must maxLifetime be shorter than the database's idle timeout?+
If the server or a proxy closes an idle connection first, the pool keeps a dead handle it believes is healthy, and the next borrower discovers the truth. Recycling below the cutoff means the pool always retires the connection before the infrastructure does.
Validation on borrow is the backstop: the pool can test with Connection.isValid() and evict a connection that fails, opening a replacement in its place. It is a filter for deaths the pool did not observe, and it costs a round trip, so it does not replace maxLifetime.
Follow-up: How would you find the real cutoff when the database is managed by a cloud provider?
Users report "Timeout waiting for connection" while database CPU is near zero. What do you check first?+
The pool's active, idle and waiting counts, plus the borrow paths in the code, not the pool size. Active pinned at maximum with the database idle is a leak signature, and leakDetectionThreshold gives you the stack trace of the borrower that never returned.
Common misconception: The instinct to raise maximumPoolSize turns one leak into a slower, more expensive leak. More connections cannot fix code that never returns a connection.
Why can a bigger pool reduce throughput?+
Because the database has finite cores, IO and memory: each connection is another session, stack and context switch, and past a knee they contend for the same locks and buffers instead of doing useful work. Keep transactions short and size from load, not intuition.
The queue is backpressure that bounds how much work reaches the database. Raise the bound without changing the database's capacity and latency grows, because the queue simply moves inside the server.
Can one transaction use two pooled connections?+
No: a transaction lives on a single connection from begin to commit. If you need work on another connection, you are starting another transaction or joining a distributed one, which is a much larger decision than a pool setting.