What you'll learn: By the end of this lesson you will be able to say what a connection pool does and what
maximumPoolSizeandconnectionTimeoutcontrol, size a pool from arrival rate and time held (not from the number of web threads), explain why a remote call inside a transaction or a connection never closed can starve a pool while the database is calm, read the pool's active, idle and waiting counters, set the properties Spring Boot passes to HikariCP, and use a Java lab that exhausts a real pool and reports counters, not timings.
Picture a hire-car desk with ten cars. A customer takes a car, drives, returns it, and the next customer gets it. The desk works as long as cars come back quickly. Now one customer keeps a car for a week, and another forgets to return theirs. The queue grows, yet nothing is wrong with the cars; the fleet is simply out on loan. A connection pool is that desk, the cars are database connections, and the queue is every request thread waiting for one.
The thread pool lesson bounded the threads that run your code. This lesson bounds the connections they borrow.
Verified with the HikariCP README and wiki (the library resolved by Spring Boot 4.1.2 in the lab is HikariCP 7.0.2), the Spring Boot and Spring Framework references, and a lab compiled for Java 25 (--release 25) and run on JDK 27.0.1.1 over H2 2.4.240, on 2026-12-01.
The core idea
A connection pool keeps a bounded set of open database connections and lends them to callers; its size is a concurrency limit on the database, and the number of connections you need is set by how long each caller holds one, not by how many requests arrive. HikariCP's maximumPoolSize "controls the maximum size that the pool is allowed to reach, including both idle and in-use connections". When every connection is lent out, a caller waits, and after connectionTimeout "a SQLException will be thrown". The wait and the exception are where an overloaded or leaking application shows up first.
Three illustrations run through the lesson: a pool of three with eight threads in the Java lab (minimal), ShopStream's checkout holding a connection across a payment call (realistic), and a connection never closed on an error path (failure).
How a pool lends a connection
The caller asks the DataSource for a connection, uses it, and closes it; with a pool, closing is how the connection is handed back (the lab's first test checks that the active count drops after a close). The pool decides whether an idle connection is ready, whether it may open another (up to the maximum), or whether the caller must wait.
Figure 1. The three outcomes of a borrow. How to read this: a caller gets a connection at once, after a wait, or an exception. The middle path is where latency hides, and the last is where the error reaches users.
The settings that matter
HikariCP's own documentation names the defaults; the lab prints them from the library on the classpath (Part 1 of the output below), so the values here are what the running version reports.
| Setting | What it controls | Default (lab output) |
|---|---|---|
maximumPoolSize |
Most connections, idle plus in use | 10 |
minimumIdle |
Idle connections the pool tries to keep; the README recommends leaving it unset so the pool is fixed-size | -1, meaning "same as maximumPoolSize" |
connectionTimeout |
How long a caller waits for a connection; the README gives 250 ms as the minimum | 30000 ms |
maxLifetime |
Longest life of a connection; the README strongly recommends setting it | 1800000 ms |
leakDetectionThreshold |
Log a possible leak when a connection is out longer than this; 0 disables, and 2000 ms is the minimum to enable | 0 ms |
connectionTimeout is the longest a user-facing request will wait for a database slot, so it belongs inside the request's own time budget (see timeouts, retries, backoff and jitter); the 30 second default is long for most web requests. The lab's output also prints idleTimeout (600000 ms), keepaliveTime (120000 ms) and validationTimeout (5000 ms).
Lease time decides the size
Little's law, used in the thread pool lesson, applies unchanged. The average number of connections in use equals the arrival rate times the time each request holds a connection (the lease time). Two things follow.
First, lease time is a property of your code, not of the database. A request that opens a transaction, calls a remote service and then writes holds a connection for the whole remote call. Spring's DataSourceUtils.getConnection documentation says that "if an existing transaction already has a connection synchronized (linked) to it, that instance is returned", so inside a transaction every statement reuses the one connection that the transaction took at its start. Whatever else the method does while the transaction is open, the connection is held.
Second, the pool is a limit shared by every thread in the process. A pool of 10 with 200 request threads lets at most 10 of them talk to the database at once. HikariCP's pool-sizing article argues this is usually right: "You want a small pool, saturated with threads waiting for connections." It reasons from CPU time-slicing and I/O blocking, not user counts, offers connections = ((core_count * 2) + effective_spindle_count) as a starting point to test under load (core count excludes hyper-threads; spindle count is zero when the data set is fully cached), and warns that "pool sizing is ultimately very specific to deployments". It also gives a floor for avoiding self-deadlock when one thread holds several connections at once, pool size = Tn x (Cm - 1) + 1 (Tn threads, Cm connections held at once by one thread), and calls it the minimum, not the optimum.
Figure 2. The pool is the database's concurrency limit. How to read this: all request threads borrow through the pool; at most N of them reach the database at a time, and the rest wait in a state the pool can count. Raising N moves the limit onto the database.
The article cites a demonstration where shrinking the pool alone "decreased the response times of the application from ~100ms to ~2ms". Treat its formula as a hypothesis and measure active, idle and waiting counts under realistic load.
Reading the pool: the counters
HikariPoolMXBean exposes active (in use), idle, total and the "threads awaiting connections from the pool". Its documentation says each is "extremely transient and is a point-in-time measurement", so idle plus active can differ from total when you read them. A pool whose active count equals its maximum while waiting stays above zero is exhausted; the question is then whether the database is slow or something holds connections too long.
Figure 3. From a timeout to a cause. How to read this: the pool's counters split the problem in two. A calm database with an exhausted pool points at how long your code holds connections, not at the database.
Two ways to starve a healthy pool
A connection that is never returned. If an exception skips the close, the connection stays out. Each failed request takes one more until the pool is empty and every later caller times out, though the database is idle. The cure is mechanical: try-with-resources, or let a framework own the connection. leakDetectionThreshold logs a possible leak to help you find the code; it does not return the connection.
A slow call inside the transaction. Nothing is leaked here: the connection comes back, eventually. But if each request holds one while a payment provider takes hundreds of milliseconds, throughput falls to pool size divided by lease time, however fast the queries are.
Build it: exhausting a real pool
This is the minimal example. The lab uses a real HikariCP pool over an in-memory H2 database (no server, no Docker), so the pool's behaviour is HikariCP's and the database is a stand-in. It prints counters read after events, never timings. It does not show how a networked database, its max_connections or its failover behave.
Goal. See the pool run out, time a caller out, leak a connection, and watch a remote call inside a transaction make threads wait while the database is idle.
Setup. From the repository's examples/spring-labs folder:
./gradlew :labs:connection-pooling-hikaricp:test
./gradlew :labs:connection-pooling-hikaricp:test -PwriteGolden
The first command runs 8 tests. The second rewrites the golden file from a real run. The code is in examples/spring-labs/labs/connection-pooling-hikaricp/src/main/java/buildingai/labs/hikari/.
How it works. Pools builds the pool. Orders has the same query twice, leakyStatus (closes only on success) and safeStatus (try-with-resources). Checkout runs one step two ways inside a Spring TransactionTemplate; the first holds the transaction open across a slow RemotePayment call:
public String payCallingRemoteInsideTransaction(long orderId) {
return transaction.execute(status -> {
jdbc.queryForObject("select status from orders where id = ?", String.class, orderId);
String receipt = payment.charge(orderId);
jdbc.update("update orders set status = 'PAID' where id = ?", orderId);
return receipt;
});
}
The second calls payment.charge before the transaction opens. RemotePayment answers only when the lab releases it, so the lab waits for events, not for time.
Expected output, captured from a real run (HikariCP 7.0.2, H2 2.4.240, Spring Boot 4.1.2):
Connection pooling lab: real HikariCP pools over in-memory H2. Counters only; no timings are printed.
1. HikariConfig defaults (read from the HikariCP version on the classpath)
maximumPoolSize 10
minimumIdle -1 (-1 means: same as maximumPoolSize)
connectionTimeout 30000 ms
idleTimeout 600000 ms
maxLifetime 1800000 ms
keepaliveTime 120000 ms
leakDetectionThreshold 0 ms (0 means: disabled)
validationTimeout 5000 ms
initializationFailTimeout 1 ms
2. Pool of 3, eight request threads, each holds a connection until released
while all three connections are held: active=3 idle=0 total=3 threads awaiting a connection=5
after release: requests completed=8 of 8, most connections held at once=3
3. Pool of 2, connectionTimeout 250 ms, both connections held, a third caller asks
exception class: SQLTransientConnectionException
message: timeout - Connection is not available, request timed out after Nms (total=2, active=2, idle=0, waiting=0)
(the lab replaces the measured wait with N, because it varies by a millisecond or two)
4. A connection that is not closed on the error path (pool of 2, timeout 250 ms)
leaky call 1 failed with JdbcSQLSyntaxErrorException
leaky call 2 failed with JdbcSQLSyntaxErrorException
after two failures: active=2 idle=0
a normal call: SQLTransientConnectionException
try-with-resources version, after five failures: active=0
a normal call: NEW
5. Where the slow remote call sits (pool of 2, six request threads, the remote service hangs)
remote call inside the transaction:
while the remote service hangs: remote calls started=2 connections in use=2 threads awaiting a connection=4
after the remote service answers: checkouts completed=6 of 6
remote call before the transaction:
while the remote service hangs: remote calls started=6 connections in use=0 threads awaiting a connection=0
after the remote service answers: checkouts completed=6 of 6
6. What Spring Boot builds from spring.datasource.hikari.* properties (no web server, in-memory H2)
with properties: HikariDataSource pool-name=boot-pool maximum-pool-size=3 connection-timeout=250
without properties: HikariDataSource maximum-pool-size=10 connection-timeout=30000
7. Little's law for a pool (illustrative numbers; 58 checkouts per second is ShopStream's illustrative peak)
58 requests/s x 20 ms holding a connection -> 1.16 connections in use on average
58 requests/s x 420 ms (20 ms + a 400 ms remote call inside the transaction) -> 24.36 connections in use on average
a pool of 10 connections, 20 ms per request -> at most 500.00 requests/s
a pool of 10 connections, 420 ms per request -> at most 23.81 requests/s
What the output shows. Part 2: three connections, eight threads: three active, none idle, five waiting, and never more than three held at once. Part 3: the third caller gets SQLTransientConnectionException (the lab replaces the measured wait with N because it varies). Part 4: two failures on the leaky path leave both connections active and a normal call times out; the try-with-resources version is back to zero active. Part 5 is the realistic case: with the remote call inside the transaction, two threads hold the connections and four wait while the database does nothing; with the call before it, no connection is in use while six calls hang. Part 6 shows Boot building a HikariDataSource from spring.datasource.hikari.* properties, and the defaults when none are set. Part 7 is arithmetic, not measurement.
Break it. In Orders.safeStatus, replace the try-with-resources block with the body of leakyStatus: the behaviour test that compares the two fails, because the connection is no longer returned on the error path. Put the code back and run the tests again.
What the model leaves out: a networked database, server-side max_connections, maxLifetime expiry and failover.
Choosing: the trade-offs
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| Small fixed pool (the README's recommendation) | Few database sessions, predictable load | Callers wait when it is full | The pool is smaller than the work that must hold connections together |
| Larger pool | Fewer waiting threads | More concurrent work on the database | The database is the bottleneck |
| Remote calls outside transactions | Short lease time | More careful code: no atomicity across the call | The remote call and the write must commit together |
| A pool per workload | A report cannot take checkout's connections | More sizing and monitoring | Total database capacity is already tight |
In practice: ShopStream's checkout holds a connection across a payment
This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. Numbers other than ShopStream's shared checkout peak (about 58 per second) are illustrative.
This is a realistic scenario, not a case history.
The situation
ShopStream's orders service handles about 58 checkouts per second at peak. Its checkout method, written as one transaction, reads the order, calls the payment provider and marks the order paid. Assume, for illustration, that the database work takes 20 ms and the payment call 400 ms. The service uses the default pool of 10 connections.
Starting architecture
Figure 4. A connection held across a slow remote call. How to read this: the connection is taken when the transaction starts and returned when it ends, so the payment call's duration counts as database time to the pool.
By Little's law (the lab's Part 7), 58 requests per second holding a connection for 420 ms needs about 24.4 connections busy on average, and a pool of 10 can finish at most about 23.8 requests per second at that lease time. With the payment call moved out, lease time is 20 ms: about 1.2 connections on average.
Options considered
| Option | Behaviour | Risk |
|---|---|---|
| A. Raise the pool to 30 | Enough connections for the average | More database sessions; the next slowdown needs 40 |
| B. Call the payment provider before opening the transaction | Lease time is database time only | The order must handle "paid but not recorded" |
C. Keep the call inside but cut connectionTimeout |
Fast failures | Users see errors instead of waiting; the cause remains |
The decision
Option B, with the payment call made under an idempotency key so a retry cannot charge twice, and with a transaction that records the result afterwards. The ShopStream payments ledger lesson covers the ledger and idempotency that make that safe. The pool stays at its size until measurement says otherwise, and connectionTimeout is set below the request's time budget.
Rollout and verification
The team ships behind a flag to one instance and watches the pool's active and waiting counters beside the payment provider's latency. The lab's Part 5 is the model for a test: hang the remote call and assert how many connections are in use.
The 2 a.m. failure
The page reads: checkouts fail with "Connection is not available, request timed out". The payment provider slowed down, the old code held connections across it, and all ten were out with waiting threads queued behind them. The database's own dashboards looked calm, which is the clue: waiting is above zero, active equals the maximum, and the database is not busy. The checks are the pool's waiting count and the payment latency. The mitigation is a timeout on the payment call, or a roll back to the release with the call outside the transaction. The lasting fixes are the short lease time, an alert on waiting threads, and a test that fails when a remote call sits inside a transaction.
Architect's notes
- Size from lease time, add headroom, then measure; keep transactions short.
- Watch waiting, not only active. Waiting above zero for long is the alarm.
- Set
connectionTimeouton purpose, inside the request's budget. - Check what your framework holds. Spring Boot registers the open-entity-manager-in-view interceptor by default in web applications that use JPA; the reference says how to turn it off. Check what it does to connection hold time in your application.
Common mistakes
- Setting the pool size equal to the web thread count "so nobody waits".
- Calling a remote service inside a
@Transactionalmethod. - Closing a connection only on the success path.
- Raising the pool in an incident without asking why connections are held.
- Sharing one pool between checkout and reporting.
Key takeaways
- A pool is a concurrency limit on the database: borrow, use, return, and wait or fail when it is empty.
- Average connections in use equals arrival rate times lease time; a pool of N and lease time S finishes at most N over S requests per second.
- A remote call inside a transaction counts as database time to the pool.
- A connection not closed on an error path leaks until the pool is empty, even though the database is idle.
- The README recommends a fixed-size pool; the sizing article recommends a small one and treats its formula as a starting point.
- Alert on threads waiting for a connection, and set
connectionTimeoutto fit the request's budget.
Practice exercises
Exercise 1 (20 min). For 120 checkouts per second at a 30 ms lease time, compute the average connections in use; repeat at 300 ms.
Exercise 2 (45 min). Run the lab. Predict Part 5 for a pool of 4, change the lab and compare.
Exercise 3 (1 hour). Run "Break it" and explain why only the leaky version keeps connections active.
Exercise 4 (2 hours). Decide whether ShopStream's reporting job gets its own pool, how big, and what happens to it at checkout's peak.
Related reading
- Thread Pools, Executors and CompletableFuture: the same sizing law for threads.
- Spring @Transactional: what a transaction boundary holds.
- Blocking vs Reactive: Spring MVC and WebFlux: why the thread count and the connection count differ.
- Timeouts, Retries, Backoff and Jitter: the time budget around a borrow.
- JPA, Hibernate, N+1 and Batching: when one request issues many statements.
- Virtual Threads (Project Loom): why a pool acts as the limit.
Official documentation
- HikariCP README: configuration: every setting, default and minimum.
- HikariCP wiki: About Pool Sizing: the sizing reasoning and formulas.
- HikariPoolMXBean source: the counters and their caveats.
- Spring Boot: SQL databases: how Boot picks HikariCP and the
spring.datasource.hikari.*prefix. - Spring Framework: Synchronizing Resources with Transactions:
DataSourceUtils.getConnection.