A brand-new taxi every time
Ana is at the station and needs to get to the hotel. There's no taxi rank, so for every trip a brand-new taxi has to be found. It drives up, the driver checks the hotel's badge to be sure it's the real hotel, the driver gives the password, and the hotel sets up a parking bay and a helper just for that taxi.
Only then does the trip happen, and it takes a minute. Afterwards the taxi is sent away for good. The next rider starts all over again. Most of the time goes on getting a taxi, not on the ride. Each of those taxis is a connection.
Why opening a connection is expensive
A database connection is a long-lived network session between your application and the database server. Opening one costs far more than a typical short query:
- TCP handshake: one network round trip before any bytes flow.
- TLS handshake: more round trips, a certificate check and key exchange (if the connection is encrypted, as it should be).
- Authentication: the server checks credentials, for example with SCRAM-SHA-256 in PostgreSQL.
- Server-side session: PostgreSQL forks a whole backend process per connection; MySQL dedicates a thread. Each holds memory for buffers, caches and session state.
A query on an indexed key might take a millisecond; setting up the connection for it can take several, more across regions. Opening and closing a connection per request wastes that time on every request and churns processes on the server.
The taxi rank
So the station sets up a taxi rank, which is a connection pool. When the day starts, a few taxis are found, signed in at the hotel, and left waiting at the rank with their engines running.
Ana walks up, takes the first free taxi, rides to the hotel and back, and the taxi returns to the rank. Nobody scraps it. Ben takes the next one. Taking a taxi now takes a second, because all the checks were done hours ago. The rank's marshal tidies each taxi when it comes back, so the next rider finds nothing left behind.
The pool: borrow and return
A connection pool opens connections up front and keeps them open. Code borrows one, uses it, and returns it; the physical connection survives for the next borrower.
In JDBC, the pool hides behind a DataSource. getConnection() hands out an idle pooled connection (no handshake),
and close() on it returns it to the pool rather than closing the socket. On return, HikariCP rolls back uncommitted
work (when auto-commit is off) and resets what the borrower changed through JDBC setters (auto-commit, isolation level,
read-only, catalog, schema, network timeout). State set with SQL, such as SET search_path or temp tables, is not
reset, so avoid it or undo it before close().
1HikariConfig config = new HikariConfig();2config.setJdbcUrl("jdbc:postgresql://db.internal:5432/orders");3config.setUsername("app");4config.setPassword(System.getenv("DB_PASSWORD"));5config.setMaximumPoolSize(10);6HikariDataSource dataSource = new HikariDataSource(config); // one per app, shared78try (Connection conn = dataSource.getConnection(); // borrow9PreparedStatement ps = conn.prepareStatement("SELECT name FROM customer WHERE id = ?")) {10ps.setLong(1, id);11try (ResultSet rs = ps.executeQuery()) {12// ...13}14} // close() returns it
HikariCP is Spring Boot's default pool: the JDBC and JPA starters bring it in, and Boot builds the DataSource from
spring.datasource.*. Spring then borrows for you: JdbcTemplate borrows per call, and a
transaction (@Transactional, see Spring transactions) holds one connection from begin to commit or rollback, since a
transaction lives on a single connection.
All the taxis are out
The rank has only so many taxis. Ana asks hers to wait outside a shop while she browses for half an hour. Ben gets to the hotel and simply never sends his taxi back.
Now Cleo arrives and the rank is empty. She queues, but not forever: after a set time she gives up and goes home upset. That waiting limit is called the timeout. A good marshal also keeps a watch: if a taxi has been gone far too long, they write down who took it, so the station can find out why it never came back.
Pool exhaustion and timeouts
When every connection is checked out, getConnection() blocks. After connectionTimeout (HikariCP default 30 seconds)
it throws:
1java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available,2request timed out after 30000ms (total=10, active=10, idle=0, waiting=24)
The usual causes aren't "too small a pool" but connections held too long:
- Long transactions: a
@Transactionalmethod that calls a slow HTTP API, sends email or waits on a lock holds its connection the whole time. Do slow non-database work outside the transaction. - Leaks: code that borrows and never calls
close()(no try-with-resources) loses a connection forever.leakDetectionThreshold(default 0, off; at least 2000 ms when on) logs a warning with the borrower's stack trace when a connection stays out longer than the threshold. - Nested borrowing: a thread holding one connection that asks for a second (for example a
REQUIRES_NEWtransaction) can deadlock the pool under load when every thread holds one and waits for another.
Prefer a short connectionTimeout (a few seconds) so requests fail fast instead of piling up, and watch the pool's
metrics (with Actuator, Spring Boot publishes them through Micrometer as hikaricp.connections.active, .idle and
.pending).
How many taxis?
The hotel sits on a narrow street with room for only so many taxis, and it has a handful of porters. More taxis than porters don't make anything faster: they just sit in the street, blocking each other. A short line of taxis that keep moving beats a traffic jam.
And the street is shared. If three stations each send forty taxis, the street fills up and the last ones are turned away. So each station keeps a small rank. When a crowd of riders turns up all at once, they queue calmly at the station, not in the hotel's street.
Sizing the pool
The database does useful work on only as many connections as it has CPU cores and disk I/O to serve; beyond that, extra connections add context switching, lock contention and memory. Small pools usually win:
- HikariCP's "About Pool Sizing" page quotes a PostgreSQL-project starting point:
connections = ((core_count * 2) + effective_spindle_count), counted for the database server. Treat it as a starting point to load-test, not a rule. HikariCP's defaultmaximumPoolSizeis 10. - The database's limit is shared. PostgreSQL's
max_connectionsdefaults to 100 (minus slots reserved for superusers), and every app instance has its own pool. Keepinstances ร maximumPoolSize, plus migrations and admin tools, below it, and remember autoscaling adds instances. Past the limit, PostgreSQL refuses new sessions with a FATAL error (remaining connection slots are reserved ...for ordinary roles, orsorry, too many clients alreadyonce every slot is used). - HikariCP recommends a fixed-size pool: leave
minimumIdleat its default (equal tomaximumPoolSize). If you set it lower,idleTimeout(default 10 minutes) closes connections idle beyond it, down tominimumIdle.
Virtual threads change the thread side, not the database side. With thousands of cheap
threads, thousands of requests can be waiting in getConnection() at once, so the pool becomes the real limit on
concurrent database work. That's the point of it: don't raise maximumPoolSize to match the thread count. Keep it sized
for the database, and use a short connectionTimeout or a Semaphore so the queue doesn't grow without bound.
The barrier that closes quietly
On the road to the hotel there's a barrier with a guard. If a taxi sits still too long, the guard quietly closes its lane without telling anyone. The taxi at the rank still looks fine, but the next rider who takes it gets nowhere.
So a careful marshal does three things. They check a taxi that's been sitting a while before handing it over. They send waiting taxis for a short drive now and then, so the guard sees them moving. And they retire every taxi after a set shift, its maximum lifetime, shorter than the guard's limit, bringing in a fresh one before the lane is ever closed.
Stale connections and maxLifetime
Pooled connections live a long time, and things between the app and the database don't always tolerate that: firewalls,
NAT gateways and load balancers drop idle TCP flows silently, and the database may enforce its own limits (MySQL's
wait_timeout, PostgreSQL's idle_session_timeout). The pool then holds a socket that looks open but is dead.
HikariCP defends in layers:
- Validation on borrow: a connection that has been idle for more than 500 ms is checked with JDBC4
Connection.isValid()(bounded byvalidationTimeout, default 5 s) before it's handed out; a dead one is evicted and replaced. Don't setconnectionTestQueryif your driver supports JDBC4. keepaliveTime(default 2 minutes since HikariCP 6.2.1, as shipped by Spring Boot 3.5+; 0, meaning off, in older versions such as 5.x; minimum 30 s): idle connections are pinged periodically, so idle-timeout middleboxes see traffic.maxLifetime(default 30 minutes): a connection is retired once it reaches this age, at the next point it's idle, and replaced. HikariCP shortens each connection's lifetime by a random amount (up to 25% in 6.x and later) so they don't all retire at once, and recommends setting it several seconds shorter than any database or infrastructure connection time limit.
Validation can't save a connection that dies mid-query: that statement fails with an I/O error, and the transaction
must be retried. On managed databases, a short maxLifetime also helps connections follow DNS after a failover (see
RDS).
1spring:2datasource:3url: jdbc:postgresql://db.internal:5432/orders4username: app5password: ${DB_PASSWORD}6hikari:7maximum-pool-size: 10 # sized for the database, not for threads8connection-timeout: 3000 # fail fast when the pool is exhausted9max-lifetime: 1500000 # 25 min: below a 30 min firewall or server limit10keepalive-time: 12000011leak-detection-threshold: 20000
A shuttle desk at the hotel
Some hotels get so many taxis from so many stations that they put a shuttle desk, a kind of pooler, at the end of the street. Taxis stop at the desk, and a few hotel shuttle carts carry riders the last stretch. When a rider's trip is done, their cart takes the next rider, from any station.
There's a catch. You may get a different cart on every trip, so you can't leave your bag in a cart and expect to find it next time. Anything you need, you bring along on each trip.
Server-side poolers
An app-side pool limits one process. When many instances, serverless functions or languages share a database, a pooler in front of it caps the total:
- PgBouncer (PostgreSQL) accepts many client connections and maps them onto few server connections. In session mode a client keeps one server connection until it disconnects (little gain for pooled apps). In transaction mode, the usual choice, a server connection is assigned per transaction and returned when the transaction ends (commit or rollback), so many clients share it.
- The catch with transaction mode: session state doesn't survive between transactions.
SETandRESET(useSET LOCALinside the transaction instead), session advisory locks (pg_advisory_lock; usepg_advisory_xact_lock),LISTEN,WITH HOLDcursors and SQL-levelPREPAREaren't supported. Protocol-level prepared statements, which JDBC drivers use, need PgBouncer'smax_prepared_statements(added in 1.21, on by default with 200 since 1.24); on older setups, disable server-side prepares in the driver (pgjdbcprepareThreshold=0). - RDS Proxy does the same for Amazon RDS and Aurora. Session state there causes pinning, which ties a client to one database connection and removes the benefit.
Keep the app-side HikariCP pool even behind a pooler: it still saves the client-to-pooler handshakes. Size the two together, so the app pools don't just move the queue to the pooler.