Sizing HikariCP connection pools and diagnosing wait times
How HikariCP pool sizing works, how to spot pool exhaustion with Micrometer metrics, and why REQUIRES_NEW causes pool deadlocks in Spring Boot.
Making a connection pool larger sounds like an easy way to speed up a database-backed app, but pushing past what the database can process at once only shifts the queue and increases latency. This post covers the reasoning and limits behind the HikariCP sizing formula, how to diagnose exhaustion with metrics, and how nested
REQUIRES_NEWtransactions cause pool deadlocks.
Tested with Spring Boot 3.1.3, Java 17, HikariCP 5.0.1, and PostgreSQL 15.4. Metrics were collected through Spring Boot Actuator (Micrometer).
Background
When I load-tested a toy event registration service for my department, requests started failing at around 200 concurrent users—every failed call timed out at the exact 30-second mark. The logs showed the classic HikariCP timeout exception:
1
java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms.
My first instinct was to bump maximumPoolSize from 10 to 100. The timeout errors dropped, yet average response time got worse and database CPU pinned at 100%. That test taught me a basic rule: you don’t size a connection pool for incoming request count. You size it for the amount of concurrent work the database can execute efficiently.
How HikariCP borrows connections
Borrowing a connection in HikariCP follows a fast path before falling back to a wait queue. When a thread calls getConnection(), HikariCP first checks a ThreadLocal list of connections that the same thread recently returned. If none are free there, it scans the shared list of idle connections. When every connection is busy, the thread blocks in a wait queue until a connection frees up or connectionTimeout (30 seconds by default) expires.
flowchart TD
A["Thread calls getConnection()"] --> B["Check ThreadLocal recent list"]
B --> C["Scan shared list for idle connection"]
C --> D{"Idle connection available?"}
D -->|"Yes"| E["Return connection"]
D -->|"No"| F["Wait in queue until connectionTimeout"]
HikariCP implements this lock-light structure in ConcurrentBag. The number of threads waiting in that queue is exposed via HikariPoolMXBean.getThreadsAwaitingConnection(), which Micrometer publishes as the hikaricp.connections.pending gauge.
The HikariCP wiki’s “About Pool Sizing” page suggests this formula as a starting point:
1
connections = (core_count * 2) + effective_spindle_count
That formula doubles the database server’s CPU core count and adds the number of effective disk spindles. A single CPU core executes one instruction stream at a time, so running far more concurrent queries than cores mainly adds context-switching overhead on the database host. The spindle term leaves headroom for another query to run while one query waits on disk I/O.
This formula has clear limits, though. If your working set fits in RAM, the spindle term approaches zero, and on NVMe or SSD storage the idea of a physical “spindle” barely applies. More importantly, the number represents the total connections across the database server, not per app instance. If you run four Spring Boot instances against one PostgreSQL node, each instance gets a slice of that budget. I treat the formula as an initial baseline for load testing, not a fixed answer.
Diagnosing pool symptoms and deadlocks
Before touching pool size, match the symptom to the metrics so you fix the actual bottleneck instead of masking it.
| Symptom | Key metrics | Likely cause | Fix |
|---|---|---|---|
SQLTransientConnectionException after 30s | pending rises, active hits max | Slow queries or long transactions | Tune queries, shrink transaction scope |
| Higher pool size increases latency | DB CPU saturated | Pool exceeds DB throughput | Shrink pool, optimize queries |
| All requests freeze at once | active at max, DB shows no running queries | Nested transaction pool deadlock | Recalculate pool size or refactor |
| Active connections never drop | High usage duration | Unreturned connection leak | Enable leakDetectionThreshold |
The third row is what actually bit me. My registration service ran inside @Transactional and called an audit log method annotated with @Transactional(propagation = Propagation.REQUIRES_NEW). REQUIRES_NEW suspends the outer transaction while keeping its database connection checked out, then requests a second connection from the same pool. With a pool of 10, if 10 requests arrive together and each grabs its first connection, none of them can acquire a second one. Every thread sits there for 30 seconds and fails together.
The HikariCP wiki gives a formula for the minimum pool size needed to avoid that deadlock:
1
2
pool size = Tn x (Cm - 1) + 1
Tn: maximum concurrent threads, Cm: max simultaneous connections held per thread
If 8 worker threads can each hold 2 connections at the same time, you need 8 x (2 - 1) + 1 = 9 connections so at least one thread can always finish and release its pair.
When you should not enlarge the pool: If your transactions run slow queries or wait on external HTTP calls while holding a database connection, raising maximumPoolSize only moves the queue from the app onto the database server. Move external API calls outside @Transactional, and replace REQUIRES_NEW with the same transaction or an asynchronous domain event whenever possible.
Configuration and verification
I updated application.yml to fail faster, catch leaks early, disable OSIV, and expose Micrometer metrics:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# src/main/resources/application.yml
spring:
datasource:
hikari:
maximum-pool-size: 10
connection-timeout: 3000 # Default 30s delays failure detection
leak-detection-threshold: 10000
pool-name: app-pool
jpa:
open-in-view: false # Release connections before view rendering
management:
endpoints:
web:
exposure:
include: health,metrics
During load tests, I polled the four key HikariCP Actuator metrics to watch queue depth and acquisition time:
1
2
3
4
curl -s localhost:8080/actuator/metrics/hikaricp.connections.pending
curl -s localhost:8080/actuator/metrics/hikaricp.connections.active
curl -s localhost:8080/actuator/metrics/hikaricp.connections.acquire
curl -s localhost:8080/actuator/metrics/hikaricp.connections.timeout
You can reproduce the REQUIRES_NEW pool deadlock locally in seconds by setting maximum-pool-size: 2 and sending two concurrent requests to a flow like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/main/java/com/example/apply/ApplyService.java
@Service
@RequiredArgsConstructor
public class ApplyService {
private final ApplicationRepository applicationRepository;
private final AuditService auditService;
@Transactional
public void apply(Long eventId, Long memberId) {
applicationRepository.save(new Application(eventId, memberId)); // Holds connection 1
auditService.record("APPLY", memberId); // Requests connection 2
}
}
// src/main/java/com/example/apply/AuditService.java
@Service
@RequiredArgsConstructor
public class AuditService {
private final AuditLogRepository auditLogRepository;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void record(String action, Long memberId) {
auditLogRepository.save(new AuditLog(action, memberId));
}
}
On the database side, checking pg_stat_activity for sessions stuck in idle in transaction shows you where a transaction stays open without executing SQL. If lock waits inside transactions are stretching your connection hold times, see my note on row locks, gap locks, and deadlock diagnosis.
Production pitfalls and checklist
Watch out for two defaults that quietly break pool budgets. First,
spring.jpa.open-in-viewdefaults totruein Spring Boot, which keeps the connection checked out until the controller finishes rendering the HTTP response. Second, if the sum ofmaximumPoolSizeacross all app instances exceeds PostgreSQL’smax_connections(100 by default), new instances fail to connect during scale-out. During rolling deployments, old and new pods run side by side, so include that temporary overlap in your math.
The workflow that worked best for me is simple: pick a starting size with the formula, verify it under load using HikariCP metrics, and shorten how long each request holds a connection.
- Does the combined
maximumPoolSizeacross all instances—including rolling-deploy overlap—stay safely below the databasemax_connections? - Are
hikaricp.connections.pendingandhikaricp.connections.acquirevisible on your monitoring dashboard? - Is
connectionTimeoutshorter than upstream HTTP and gateway timeouts? - If any path holds two connections per thread (such as
REQUIRES_NEW), does the pool satisfyTn x (Cm - 1) + 1or can you remove the nested transaction? - Are external API calls and long waits kept outside
@Transactionalboundaries?