Tuning HikariCP in Spring Boot for High-Throughput Database Performance
Why a Larger Pool Can Reduce Throughput#
HikariCP is Spring Boot's default JDBC connection pool. It maintains a fixed set of pre-opened database connections that application threads borrow, use, and return, eliminating the TCP-handshake overhead that would otherwise hit every query. At 1M requests per minute, paying that overhead on each request would be catastrophic.
The instinct behind a large pool is reasonable: more connections means more parallelism, and more parallelism means more throughput. The problem is that this reasoning stops one layer too early. A database server is not infinitely parallelizable. PostgreSQL, for example, spawns an OS process per connection. At some point, the overhead of context-switching between 200 processes costs more CPU than the queries save in wait time. Throughput flattens and then drops while latency rises, which is precisely the pattern a too-large pool produces. Setting maximumPoolSize to 200 and watching p99 latency climb instead of fall is one of the most common HikariCP mistakes.
This tutorial walks through exactly why that happens and the specific parameter changes that will get a Spring Boot application to 1 million requests per minute without repeating it.
HikariCP is Spring Boot's default JDBC connection pool, included automatically in Spring Boot 3.x without any additional dependency.1 When a thread requests a connection and the pool is fully borrowed, the thread waits up to connectionTimeout milliseconds before receiving an exception. That blocked thread cascades in a high-concurrency system.
Slow database responses are among the most common performance bottlenecks in Spring Boot applications, and HikariCP misconfiguration is a primary cause.1 The misconfiguration is almost never a pool that is too small. More often, the pool is sized independently of the database server's actual connection capacity, the thread model of the application, and the average query hold time. These three factors together determine the right pool size, and the math is simpler than it looks.
There is also a cloud-specific dimension worth flagging early. A Spring Boot application tuned for a dedicated host behaves as a noisy neighbor when deployed on a multi-tenant environment like AWS, Azure, or Cloud Foundry, because the default HikariCP configuration is sized for a single-tenant world.2 The remaining sections treat both scenarios and show you how to arrive at a pool size that fits your deployment target, not just your local load test.
How HikariCP Manages Connections Under Load#
To understand why a large pool can hurt more than help, it helps to trace what HikariCP actually does when a request arrives, a connection becomes idle, and the pool ages over time.
At the most basic level, HikariCP maintains a fixed set of reusable database connections in memory. When your application thread needs to run a query, it borrows a connection from the pool, executes its work, and returns the connection when the transaction or statement block closes. The connection itself is never destroyed between requests under normal conditions. This is the core win over raw JDBC, where every request would open and close a TCP socket to the database.
HikariCP achieves this with remarkably little machinery.3 The entire library is roughly 165 KB, and it tracks connection state with a single concurrent bag structure rather than a queue or stack. When a thread requests a connection, HikariCP first checks whether the requesting thread previously returned a connection. If so, it hands that same connection back preferentially, reducing contention on shared state. Only if that fast path misses does it scan the shared pool.
What happens when every connection is in use. If all connections are borrowed and a new request arrives, HikariCP parks the calling thread and waits up to connectionTimeout milliseconds. If a connection is returned within that window, the waiting thread unparks and proceeds. If the timeout expires first, HikariCP throws a SQLTimeoutException and the request fails. At 1M requests per minute, that is roughly 16,700 requests per second, and a pool that is too small will start shedding load this way long before your database is actually saturated.
Idle tracking. HikariCP runs a background housekeeper thread that monitors connections not currently borrowed. Once a connection has sat idle longer than idleTimeout, the housekeeper removes it if the current pool size is above minimumIdle. This matters under variable traffic: a pool that expanded to handle a burst will shrink back down rather than holding expensive database-side resources permanently. If minimumIdle equals maximumPoolSize (a common recommendation for steady high-throughput workloads), idle eviction is effectively disabled because the pool never drops below maximum.
Connection lifetime and silent churn. Every connection has a wall-clock age tracked from the moment it was created. When that age exceeds maxLifetime, HikariCP retires the connection gracefully and opens a replacement, cycling the pool on a rolling schedule rather than all at once. This matters because network infrastructure such as load balancers, proxies, and firewalls often silently kills long-lived TCP connections on their own schedule. Without a sensible maxLifetime, you accumulate connections the pool believes are healthy but the database has already closed, leading to errors that only surface when the connection is next borrowed.
With this lifecycle in mind (borrow, execute, return, idle-track, age-out), the five tuning parameters in the next section become concrete controls on real behavior rather than knobs to turn on intuition.
Diagram as text
sequenceDiagram participant AT as AppThread participant HC as HikariCP participant DB as Database AT->>HC: getConnection() alt idle connection available HC-->>AT: hand out idle conn AT->>AT: execute query AT->>HC: close() / return HC->>HC: mark connection idle else no idle, pool not full HC->>DB: open new connection DB-->>HC: connection established HC-->>AT: hand out new conn AT->>AT: execute query AT->>HC: close() / return HC->>HC: mark connection idle else pool full, no idle HC->>HC: wait up to connectionTimeout alt connection freed in time HC-->>AT: hand out conn else timeout exceeded HC-->>AT: throw SQLTimeoutException end end
The Five Parameters That Actually Matter#
HikariCP exposes dozens of configuration properties, but five of them determine almost all of the pool's behavior under production load. This section names those five, explains what each one actually controls, and describes what breaks when you set it in the wrong direction.
maximumPoolSize sets the ceiling on total connections HikariCP will hold, counting both in-use and idle.1 Its default is 10. This is the number most people reach for first, and as the earlier section explained, pushing it too high causes the database server to spend more time on connection management than on query execution.
minimumIdle tells HikariCP the floor: the number of idle connections it tries to keep warm in the pool at all times.1 Its default is equal to maximumPoolSize. The HikariCP authors recommend leaving these equal so the pool behaves as a fixed-size pool, which eliminates the overhead of constant connection creation and destruction during traffic spikes.
connectionTimeout is the maximum number of milliseconds a calling thread will wait for a connection before HikariCP throws a SQLTransientConnectionException.1 The default is 30,000 ms (30 seconds). At 1M requests per minute, a 30-second wait means a thread is sitting blocked while thousands of subsequent requests queue behind it. Setting this too low, on the other hand, causes spurious failures during brief saturation events that a slightly longer wait would have resolved cleanly.
idleTimeout controls how long a connection can sit unused before HikariCP removes it from the pool.1 The default is 600,000 ms (10 minutes), and it only takes effect when the pool has more connections than minimumIdle. If you follow the advice of matching minimumIdle to maximumPoolSize, this setting becomes largely academic, but it matters when running a variable-size pool to handle unpredictable traffic shapes.
maxLifetime sets the absolute maximum age of a connection, after which HikariCP retires it and creates a replacement.1 The default is 1,800,000 ms (30 minutes). Its purpose is to stay safely under whatever wait_timeout your database server enforces. If the database closes a connection after 60 minutes of inactivity and your maxLifetime is 30 minutes, HikariCP recycles it first. Set maxLifetime above the database timeout, and your application gets handed a dead connection at the worst possible moment.
The table below gives a quick-reference summary before the next section works through how to derive the right value for each parameter given your specific thread count and database capacity.
| Parameter | Default value | What it controls | Wrong-direction failure |
|---|---|---|---|
maximumPoolSize | 10 | Ceiling on total connections (idle + in-use) | Too high: database CPU spends cycles on connection overhead instead of queries |
minimumIdle | Equal to maximumPoolSize | Floor on idle connections kept warm | Too low with variable traffic: pool spends time creating connections mid-spike |
connectionTimeout | 30,000 ms | How long a thread waits before failing fast | Too high: threads pile up; too low: spurious failures during brief saturation |
idleTimeout | 600,000 ms (10 min) | How long an idle connection is kept before removal | Irrelevant when minimumIdle equals maximumPoolSize; wrong otherwise causes churn |
maxLifetime | 1,800,000 ms (30 min) | Maximum age of any connection before forced recycling | Set above DB server timeout: application receives closed connections under load |
Diagram as text
stateDiagram-v2 state "Created" as CREATED state "Idle" as IDLE state "In-Use" as INUSE state "Closed" as CLOSED state "Retired / Replaced" as RETIRED [*] --> CREATED: connectionTimeout governs acquisition wait CREATED --> IDLE: connection established IDLE --> INUSE: borrowConnection() INUSE --> IDLE: returnConnection() IDLE --> CLOSED: idleTimeout exceeded CLOSED --> [*] IDLE --> RETIRED: maxLifetime exceeded (clock starts at creation) INUSE --> RETIRED: maxLifetime exceeded (clock starts at creation) RETIRED --> [*]
Deriving maximumPoolSize from a Formula, Not a Feeling#
Oversizing the pool creates contention rather than relieving it. What the earlier sections left open is the practical question: if not "as large as possible," then what number should you actually use?
There is a formula that gives you a defensible starting point. HikariCP's own documentation, drawing on work by database performance researchers such as Brett Wooldridge and the pool-sizing analysis published by Percona,2 expresses it as:
The parallelism factor accounts for the fact that most queries spend some of their time waiting on I/O rather than consuming CPU. A value between 2 and 4 is common for OLTP workloads on SSDs; spinning-disk or high-latency storage may push it slightly higher, but the overhead should stay small. For a 4-core database server with SSD-backed storage, the calculation comes out to roughly 4 × 2 = 8, plus a small buffer of 1 or 2 connections for monitoring or background processes. That lands you at a maximumPoolSize of 10, which aligns with the evidence that keeping pool size under 10 connections per application instance is the recommended practice for cloud-deployed applications.2
This formula is equivalent to cores × (1 + I/O wait / service time), where the parallelism factor represents 1 + wait/service. The flowchart below uses that expanded form; the two expressions produce the same result given the same inputs.
The Worked Example: 4-Core DB at 1M Requests/Minute#
Assume a 4-core RDS instance and a target of one million requests per minute, served by 20 Spring Boot instances behind a load balancer. One million requests per minute is roughly 16,667 requests per second, meaning each application instance handles about 833 requests per second.
Even at that volume, the bottleneck is not connection count, it is DB-side CPU. With 4 cores, the database can parallelize only 4 queries at once regardless of how many connections are waiting. Opening 200 connections does not give you 200 parallel query executions. It gives you 4 running and 196 waiting.
Apply the formula: 4 cores × 2 (parallelism factor for SSD, short OLTP queries) + 2 (overhead) = 10 connections per instance. Across 20 app instances, total database connections stay at 200, safely within the recommended ceiling of 1,000 total connections across all instances to avoid noisy-neighbor effects in multi-tenant environments.
Feeding the Formula with Real Numbers#
The formula only works if you supply accurate inputs. Before setting a single property, gather these three:
- DB CPU core count, find this in your instance specification (AWS RDS console, GCP Cloud SQL instance details, or the output of
nprocon a self-hosted server). This is the multiplier; getting it wrong scales all your other decisions incorrectly. - Storage type, listed in the same instance spec or storage configuration panel. SSD-backed instances (gp2, gp3, io1) support a lower parallelism factor (2 to 3); magnetic or high-latency network storage warrants 3 to 4.
- Average query latency under load, pull this from your slow query log or your APM tool's p50 query latency. If your p50 is under 5ms, you are in OLTP territory and the lower parallelism factor applies. If queries routinely run 20ms to 50ms under load, connections stay occupied longer and a slightly higher factor may be justified.
With those three numbers in hand, the formula stops being advisory and becomes a calculation. The next section covers how connectionTimeout, idleTimeout, and maxLifetime interact with this pool size to prevent the connections you have from going stale or blocking threads unnecessarily.
Diagram as text
flowchart LR A["DB Server CPU Cores"] --> F B["Avg Query Time (ms)"] --> F C["Target Concurrent Requests"] --> F F["pool_size = cores × (1 + wait/service)"] --> R["Recommended maximumPoolSize"] R --> E["Example: 4 cores\n10ms query\n→ pool ≈ 8-10"]
Timeout and Lifetime Tuning: Eliminating Silent Connection Churn#
Once pool size is derived from the formula, a second failure mode appears: stale-connection errors and cascading latency spikes that occur even when the pool is sized correctly. These come from the three timeout parameters. Each has a default that works acceptably in low-throughput systems and causes real problems at 1M requests per minute.
connectionTimeout is the maximum time a thread will wait for HikariCP to hand it a connection. The default is 30 seconds. At 16,700 requests per second, a 30-second timeout allows up to roughly 500,000 requests to arrive before the first blocked thread is rejected, each consuming a parked JVM thread and heap memory. That is a memory exhaustion risk. Reducing the timeout to 3,000 ms caps that exposure to roughly 50,000 requests before the pool begins rejecting overflow cleanly. The application fails fast rather than accumulating a backlog that brings the JVM down. Treat any connection-acquisition failure as a signal that your pool size or database capacity needs revisiting, not a reason to raise the timeout further.
idleTimeout controls how long HikariCP keeps a connection open when it is not being used, subject to the constraint that the pool will never shrink below minimumIdle. The default is 10 minutes. At high throughput, a 10-minute idle window means connections released after a traffic burst sit open against the database for up to 10 minutes, consuming file descriptors and server-side process slots. A value between 1 and 2 minutes is more appropriate for high-concurrency workloads: long enough to absorb momentary lulls without triggering churn, short enough to release capacity quickly when traffic subsides. If you are running multiple application instances and need to stay under 1,000 total database connections, prompt idle release is what keeps that ceiling from being breached after a traffic spike.
maxLifetime is the ceiling on how long any connection lives, regardless of whether it is idle or active. Its purpose is to prevent HikariCP from handing out a connection that the database server has already closed on its end. Most PostgreSQL and MySQL deployments set wait_timeout or tcp_keepalives_idle somewhere between 8 and 30 minutes. Set maxLifetime at least 30 to 60 seconds below whatever your database's own connection timeout is. If your DBA sets MySQL's wait_timeout to 600 seconds, maxLifetime should be no higher than 540,000 ms. HikariCP retires connections a few seconds before maxLifetime actually expires, staggering replacements so the pool does not attempt to open a batch of new connections simultaneously.
These three values form a coherent picture: connectionTimeout keeps threads from accumulating while waiting; idleTimeout releases unused connections quickly enough to stay within database server limits; maxLifetime ensures the pool never serves a connection the server already considers dead. Getting pool size right from the formula is necessary but not sufficient. These lifetimes are what keep the pool healthy across the full traffic cycle, not just during peak load.
Putting It Together: Spring Boot Configuration for 1M Requests/Minute#
The previous sections derived pool size from the concurrency formula, set timeout values against your infrastructure's actual limits, and explained why oversizing a pool creates contention rather than relieving it. This section assembles those results into a single application.properties block you can copy, adjust for your numbers, and deploy.
The Reference Configuration#
The block below targets a Spring Boot 3.x application1 running against a PostgreSQL instance with 8 DB-side CPU cores, an average query time of 10ms, and a measured network round-trip of 1ms. Working through the formula from the earlier section (8 cores × (1 + 11ms/10ms) = ~18, rounded to 20 with a small buffer) produces a maximumPoolSize of 20. Your numbers will differ; the structure of the block will not.
maximum-pool-size=20 and minimum-idle=20 are set equal to hold a fixed pool. Allowing idle connections to drain and rebuild adds latency spikes under burst load. connection-timeout=3000 gives a request 3 seconds to acquire a connection before failing fast, reconciled against observed wait percentiles so callers surface errors quickly rather than piling up in the queue. idle-timeout=300000 (5 minutes) and max-lifetime=900000 (15 minutes) sit safely inside most cloud and firewall TCP idle-kill windows, which typically start at 20 to 30 minutes.2
One constraint that applies to every multi-tenant or cloud deployment: keep the total connection count across all application instances below 1,000.2 If you run 10 instances, that ceiling means each instance should be configured to at most 90 to 95 connections, regardless of what the formula suggests for a single instance. The formula gives you the per-instance optimum; the 1,000-connection ceiling gives you the cross-instance constraint. When they conflict, the ceiling wins.
Validation Checklist#
Once deployed under realistic load, work through these four checks in order.
- Pool wait time is near zero. The Micrometer metric
hikaricp.connections.pending(or the olderHikariPool-1.pool.Waitin JMX) should read 0 under steady-state throughput. A sustained non-zero value means the pool is undersized for actual concurrency or a slow query is holding connections longer than estimated. - Active DB connections match the formula output. Run
SELECT count(*), state FROM pg_stat_activity WHERE datname = 'yourdb' GROUP BY state;under peak load. Theactiverow should be close to yourmaximum-pool-size. A count well below it means your load estimate was conservative; a count hitting the ceiling means you should recheck query latency before increasing the pool. - No connection timeout errors in logs. Search application logs for
Connection is not available, request timed out after. Any occurrence under expected load indicates callers are waiting longer thanconnection-timeout, which means the pool is exhausted and the size or query duration estimate needs revisiting. - Connections are not churning due to premature eviction. The Micrometer counter
hikaricp.connections.creationshould be flat after warm-up. A steadily climbing value means connections are being closed and recreated, which points to amax-lifetimeoridle-timeoutset below your infrastructure's actual kill window.
Add a Micrometer alert on hikaricp.connections.pending > 0 for 30s to your dashboard so the pool signals distress before it cascades into HTTP 500s. That single alert covers the most common misconfiguration scenario you will encounter once the rest of this configuration is in place.
Sources
Keep reading
How Spring Data JPA, JPA, and Hibernate Work Together
Spring Data JPA is a Spring Framework module that lets Java backend developers query a relational database without writing SQL, by generating database access code from annotated...
What a forward deployed engineer does, and how to prepare
A forward deployed engineer is a software engineer who works inside the customer's organization rather than inside the product team. The job is to build and ship custom solutions...
Chain of Thought or ReAct: Choosing Between Them
A support queue needs priorities. Every incoming ticket has to carry a label, P1 through P4, before it reaches a human, and you have been handed the feature. Two implementations...