What is HikariCP pool size tuning, and why does a bigger pool often run slower on Postgres?
HikariCP is the default connection pool in Spring Boot. It sits between your application threads and Postgres. When a request needs the database, it borrows an already-open connection from the pool, runs its queries, and returns the connection. HikariCP pool size tuning means choosing how many of those connections can exist at once, so that requests rarely wait and the database never has more connections than it can use.
Many teams assume a bigger pool means more throughput. On Postgres that assumption often fails, and the reason is how the server works. Postgres uses a process-per-connection model. Every client connection gets its own backend process, and that process has its own memory for sorts, hashes and caches.
A query only makes progress while it is running on a CPU core or waiting on disk I/O. Suppose the number of active connections is larger than the cores and I/O capacity the server actually has. The extra queries do not run in parallel. They wait in line. While they wait, they add costs of their own:
- context switching between processes
- contention on locks and shared buffers
- higher memory pressure
The result is that latency goes up and total throughput stays flat or drops.
This guide starts from the database's capacity, not from a number each service picks for itself. It is for backend and platform engineers running several services or replicas against one Postgres cluster. In that setup, each pool's size multiplies across every instance. Tuning matters most when you scale out, add a new service, or start seeing connection timeouts under load.
Service A, replica 1 Service A, replica 2 Service B, replica 1
+---------------------+ +---------------------+ +---------------------+
| app threads | | app threads | | app threads |
| | borrow/return | | | borrow/return | | | borrow/return |
| v | | v | | v |
| HikariCP pool: N | | HikariCP pool: N | | HikariCP pool: M |
+----------+----------+ +----------+----------+ +----------+----------+
| | |
+-----------------------+-----------------------+
|
total connections = sum over services of (pool size x replicas)
v
+----------------------------------------------------------------------+
| Postgres server: one backend process per client connection |
| +---------+ +---------+ +---------+ +---------+ +---------+ |
| | backend | | backend | | backend | | backend | | backend | ... |
| | process | | process | | process | | process | | process | |
| | + mem | | + mem | | + mem | | + mem | | + mem | |
| +----+----+ +----+----+ +----+----+ +----+----+ +----+----+ |
| | | | | | |
| v v v v v |
| +---------------------------------------------------------------+ |
| | wait queue: active backends beyond what cores/I/O can serve | |
| | cost: context switches, lock + buffer contention, memory | |
| +-------------------------------+-------------------------------+ |
| v |
| +---------------------------------------------------------------+ |
| | CPU cores + disk I/O (the real limit on parallel work) | |
| +---------------------------------------------------------------+ |
+----------------------------------------------------------------------+
Every replica's HikariCP pool adds to the Postgres connection total, and each connection is a backend process with its own memory; once active backends exceed what the CPU cores and disk I/O can serve, the extra ones wait and add contention instead of throughput.
Who should use this approach to pool size tuning?
Use this approach if you run Spring Boot services against Postgres and any of the following apply:
- Several services or replicas share one Postgres cluster. Each pool's
maximum-pool-sizeis multiplied by the replica count, so a value that looks harmless in one service's config can add up to more connections than the database should hold. - You autoscale or do rolling deploys. The replica count changes at runtime, and the connection total changes with it.
- You see
SQLTransientConnectionExceptiontimeouts, rising p99 latency under load, or Postgres rejecting connections becausemax_connectionshas been reached. - You own the database as a platform team and need a way to give each service a connection allocation instead of letting each team pick its own number.
If you run a single instance with modest traffic and the default pool works, you likely do not need to tune anything beyond confirming that max-lifetime fits your network path. The methods here pay off as the number of instances and services grows.
How does HikariCP pool sizing work?
HikariCP keeps a set of open JDBC connections to Postgres and hands them out to application threads. The relevant behaviour:
- Borrowing. When code needs a connection, for example when a
@Transactionalmethod starts, it asks the pool. If an idle connection is available, the pool hands it over right away. - Growing. If no connection is idle and the pool holds fewer than
maximum-pool-sizeconnections, HikariCP opens a new one in the background. That means a TCP connection, optional TLS, and Postgres authentication, and Postgres starts a new backend process for it. - Waiting. If the pool is already at
maximum-pool-sizeand every connection is in use, the caller blocks. If no connection is returned withinconnection-timeout, the caller gets aSQLTransientConnectionException. - Returning. When the transaction ends, the connection goes back to the pool. The Postgres backend process stays alive and is reused by the next borrower.
- Housekeeping. A background task closes connections above
minimum-idleonce they have been idle longer thanidle-timeout, and opens new ones to keep the pool atminimum-idle. Connections that reachmax-lifetimeare retired. A connection that is in use when it reaches its lifetime is closed after it is returned, not taken from the borrower.keepalive-timeperiodically checks idle connections so broken ones are found before a request borrows them.
maximum-pool-size is therefore a hard cap on how many Postgres backends one application instance can open. It also caps how many of that instance's threads can be doing database work at the same moment. Every thread beyond that waits in the application. Tuning means deciding where that waiting should happen. A small queue in the application, with a bounded timeout, is usually cheaper than a large queue inside Postgres, where waiting backends still use memory and compete for locks and CPU.
How do you calculate the total Postgres connection budget across all instances?
The ceiling you're budgeting against is Postgres max_connections, and every client shares it. The formula is:
total = (pool size × instances per service × number of services) + migrations + admin sessions + replication + monitoring
Keep that total below max_connections with headroom. Some slots are also held back for superusers via superuser_reserved_connections, so your applications can't use all of them.
Illustrative estimate (assumed numbers, not a benchmark). Assume:
- 3 services, each with
maximumPoolSize= 10 and 4 replicas: 120 connections. - Reserved slots: 2 for migrations, 5 for admin sessions, 2 for replication and 3 for monitoring: 12 connections.
max_connections= 200.
| Scenario | App connections | Reserved | Total | Against 200 |
|---|---|---|---|---|
| Steady state | 3 × 4 × 10 = 120 | 12 | 132 | Fits |
| One service autoscales to 8 replicas | (4 + 4 + 8) × 10 = 160 | 12 | 172 | Tight |
| Rolling deploy, 100% surge on all services | 3 × 8 × 10 = 240 | 12 | 252 | Exceeds |
Budget for the worst case, not the steady state. During a rolling deploy, old pods keep their pools open while new pods start theirs, so for a short window you pay for both. The autoscaler's maximum replica count belongs in the formula, not the typical count.
Raising max_connections is a weak fix. Each backend is a separate operating system process with its own memory. Settings such as work_mem apply per sort or hash operation, not per server. A single complex query can use several multiples of work_mem, and that cost multiplies across hundreds of backends. A burst of concurrent heavy queries can then push the host into out-of-memory conditions. More active backends also mean more context switching and lock contention, so the CPU spends more time scheduling and less time executing queries.
How should you choose a starting pool size?
Start from the database, not the application. Take the number of CPU cores on the Postgres host, multiply by a small factor, and treat the result as the total number of active connections the server should handle. Then divide that figure across every client that connects: each application instance, batch jobs, migration tools, and admin sessions.
A commonly cited rule of thumb is (cores × 2) + effective spindles. The multiplier lets one backend use the CPU while another waits on I/O. The spindle term comes from spinning disks, where each independent head could serve one request at a time. On SSD-backed or network-attached cloud storage, "spindles" has no clean equivalent. I/O waits are shorter and less predictable, so the formula gives you a rough order of magnitude at best.
Illustrative estimate: an 8-core database gives roughly 16–20 active connections. Shared across four application instances, that is about 4–5 per pool, which is smaller than most teams expect.
Pool sizes from someone else's benchmark do not carry over to your system. Query mix, transaction length, hardware, and network latency between app and database all change where throughput peaks. Treat every number as a hypothesis and check it under realistic load.
A small pool also has a cost. It protects the database, but during bursts requests wait in the application for a free connection. Throughput can stay flat while p99 latency rises. Watch pool wait time alongside database load when you adjust the size.
Configuring Spring Datasource Hikari properties: pool size, timeouts and lifetimes
In application.yml, these settings live under spring.datasource.hikari as maximum-pool-size, minimum-idle, connection-timeout, idle-timeout, max-lifetime and keepalive-time. Durations are in milliseconds. The properties interact, so tune them together.
| Setting | Fixed pool (minimum-idle = maximum-pool-size) |
Elastic pool (minimum-idle < maximum-pool-size) |
|---|---|---|
| Postgres connections held | Always the maximum | Shrinks when idle |
| Burst latency | No setup cost | New connections pay TCP, TLS and authentication |
idle-timeout |
Has no effect | Controls how quickly idle connections close |
| Good fit | Steady, latency-sensitive traffic | Low-traffic services, or many mostly idle replicas sharing one database |
HikariCP's own guidance favours a fixed pool. An elastic pool makes sense when idle connections from dozens of quiet replicas would consume the database's connection budget. The cost is that each new connection needs a TCP and TLS handshake plus Postgres authentication, and SCRAM authentication adds round trips. That work lands on the requests that triggered the growth.
Set max-lifetime a little shorter than the shortest limit in the path. That includes NAT and firewall idle timers, proxy or load balancer timeouts, and server-side settings such as idle_session_timeout. If an infrastructure component silently drops a connection first, the pool hands out a dead socket. A shorter lifetime increases connection churn, so pick the longest value that stays safely under those limits. keepalive-time sends periodic checks on idle connections and must be lower than max-lifetime.
connection-timeout sets how long a request waits for a free connection. A short timeout fails fast and makes pool saturation visible in your error rates. A long timeout hides saturation while request threads pile up waiting, until the thread pool is exhausted and the whole service stops responding.
spring:
datasource:
url: jdbc:postgresql://db.internal.example:5432/orders?sslmode=verify-full
username: orders_app
password: ${DB_PASSWORD} # injected at runtime, never committed
hikari:
# Elastic pool: scales down to 2 when quiet so many idle replicas
# don't use up the database's connection budget.
# For a fixed pool, set minimum-idle equal to maximum-pool-size.
maximum-pool-size: 10
minimum-idle: 2
# Close connections above minimum-idle after 5 idle minutes.
# This only applies when minimum-idle < maximum-pool-size.
idle-timeout: 300000 # 5 min
# Retire connections before any NAT, firewall, proxy, load balancer
# or server-side limit (e.g. idle_session_timeout) can drop them.
# Assumed shortest limit in the path: 30 min, so stay a few minutes under it.
max-lifetime: 1680000 # 28 min
# Check idle connections periodically so silent drops are found
# before a request borrows one. Must be lower than max-lifetime.
keepalive-time: 120000 # 2 min
# Wait at most 3 s for a free connection, then throw.
# Failing fast surfaces saturation instead of tying up request threads.
connection-timeout: 3000 # 3 s
An elastic HikariCP pool for Postgres in application.yml, with max-lifetime set below an assumed 30-minute infrastructure limit, keepalive-time below max-lifetime, and a short connection-timeout so pool saturation fails fast.
Why are you getting connection timeout errors, and how do you diagnose them?
A SQLTransientConnectionException saying the pool timed out waiting for a connection usually means connections are held too long. The pool size is rarely the real problem. The number of connections in use is roughly throughput multiplied by hold time, so any increase in hold time raises demand on the pool even when traffic stays flat.
Illustrative estimate (assumed numbers, not a benchmark): busy connections ≈ requests per second × hold time in seconds. At 200 req/s and 50 ms per transaction, about 10 connections are busy (200 × 0.05). Add a 250 ms HTTP call inside the transaction and the result becomes 200 × 0.3 = 60.
Common causes of long hold times:
- Slow queries.
- Long transactions.
- Remote calls made inside
@Transactional. - Open-session-in-view, which keeps a connection for the whole web request, including view rendering.
Raising the pool size to absorb any of these moves the queue into Postgres. More concurrent backends compete for CPU, locks and I/O, so each query slows down and hold times grow further.
Measure before and after every change:
- Hikari metrics through Actuator and Micrometer:
hikaricp.connections.active,idle,pendingandacquire. A sustained pending count with active pinned at maximum confirms saturation. pg_stat_activitygrouped bystate: many sessions inidle in transactionmean the application holds an open transaction while doing something other than database work.
Setting leakDetectionThreshold makes Hikari log a warning with the stack trace of where the connection was borrowed whenever it is held longer than the threshold. The warning identifies the code that holds the connection, and the connection may still be returned later. The setting is diagnostic only and changes nothing about the pool's behaviour.
Bumping the pool size and redeploying can repeat for weeks without a fix. Correlating acquire time, session states and leak traces usually identifies the cause in one investigation.
spring:
datasource:
url: jdbc:postgresql://db.example.internal:5432/orders
username: orders_app
password: ${DB_PASSWORD} # injected from the environment, never committed
hikari:
pool-name: orders-pool # appears in log lines and as the metric 'pool' tag
maximum-pool-size: 10 # deliberately unchanged while diagnosing
connection-timeout: 30000 # ms a caller waits before SQLTransientConnectionException
# Log a warning with the borrowing stack trace when a connection is held
# longer than 5 s. Diagnostic only: the connection is not reclaimed or closed.
# Hikari's minimum is 2000 ms; 0 disables it.
leak-detection-threshold: 5000
# Shows up as application_name in pg_stat_activity, so these sessions can be
# filtered when grouping by state.
data-source-properties:
ApplicationName: orders-service
jpa:
# Release the connection when the transaction ends instead of holding it
# for the whole web request, including view rendering.
open-in-view: false
management:
endpoints:
web:
exposure:
include: health,metrics
Spring Boot configuration that turns on Hikari leak detection, exposes the Hikari pool metrics through Actuator, tags sessions for pg_stat_activity and disables open-session-in-view, all while the pool size stays fixed so the bottleneck can be measured rather than moved.
When should you avoid one shared pool and size each workload separately?
A single pool treats every borrower as equal, but a request handler that holds a connection for a few milliseconds has very different needs from a nightly export that holds one for minutes. Once a batch job checks out most of the shared pool, request threads queue behind it and hit connectionTimeout, even though Postgres itself may be lightly loaded.
| Workload | Connection hold time | Pool size | Acquire timeout | Failure preference |
|---|---|---|---|---|
| OLTP requests | Short, many borrowers | Moderate | Short, fail fast | Return an error quickly rather than queue |
| Batch jobs | Long, few workers | Small, matched to worker count | Long | Wait rather than abort mid-run |
| Reporting | Long, unpredictable queries | Small | Moderate | Cap concurrency to protect the primary |
In Spring Boot, define one DataSource bean per workload, each bound to its own property prefix with @ConfigurationProperties. Mark the request-serving bean @Primary so auto-configured JPA and repositories use it, and wire batch or reporting code to the others explicitly. Give each pool a distinct poolName so its metrics and logs can be told apart. On the database side, separate Postgres roles per pool let you enforce CONNECTION LIMIT and a role-level statement_timeout as a backstop.
Pool isolation only splits connections. It does not split CPU or I/O. If reporting queries still degrade OLTP latency through disk or lock contention, or if the per-pool totals across all instances exceed the connection budget, the next step is a replica or an external pooler.
Each extra pool also carries ongoing cost. You need its own transaction manager, and sometimes its own entity manager. Tests must cover the wiring. Every pool's size also has to be rechecked whenever the instance count changes.
// application.yml (HikariCP properties bind directly, so use jdbc-url, not url):
// app.datasource.oltp: { jdbc-url: jdbc:postgresql://db:5432/app, username: app_oltp,
// maximum-pool-size: 10, connection-timeout: 2000, pool-name: oltp }
// app.datasource.batch: { jdbc-url: jdbc:postgresql://db:5432/app, username: app_batch,
// maximum-pool-size: 2, connection-timeout: 60000, pool-name: batch }
@Configuration
public class DataSourceConfig {
// Request traffic: @Primary so auto-configured JPA and repositories use this pool.
// A short connection-timeout fails fast instead of letting requests queue.
@Bean
@Primary
@ConfigurationProperties("app.datasource.oltp")
public HikariDataSource oltpDataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
// Batch jobs: a small pool sized to the worker count. A long timeout lets
// workers wait for a connection instead of aborting mid-run.
// This pool cannot take connections from the OLTP pool.
@Bean
@ConfigurationProperties("app.datasource.batch")
public HikariDataSource batchDataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
// Batch code must opt in explicitly. It uses its own transaction manager,
// so its transactions never borrow from the OLTP pool.
@Bean
public PlatformTransactionManager batchTransactionManager(
@Qualifier("batchDataSource") DataSource batchDataSource) {
return new DataSourceTransactionManager(batchDataSource);
}
}
Two separately sized HikariCP pools in Spring Boot. The request-serving pool is marked @Primary and fails fast. The batch pool is small and patient, with its own transaction manager, so long jobs cannot exhaust the connections that requests need.
What are the alternatives when HikariCP tuning alone isn't enough?
Once the sum of every instance's pool exceeds what Postgres should hold open, per-instance tuning stops helping. An external pooler such as PgBouncer sits between the applications and the database. Many client connections share a small set of server connections, so the database sees a fixed number of backends no matter how many replicas you scale to.
The usual mode for this is transaction pooling, which comes with a cost. A server connection belongs to a client only for the length of one transaction. Anything tied to the session can then leak into another client's work or disappear between transactions. That includes SET parameters, temporary tables, advisory locks and LISTEN. Server-side prepared statements carry the same risk. Check whether your pooler supports them in transaction mode. If it doesn't, turn them off in the JDBC driver. Settings that must apply to every query belong on the database role, not in a SET after connecting.
The pooler is also another component on the request path. You have to deploy it with redundancy, monitor its queue wait time and server-connection usage, and include it when you debug latency.
| Option | Helps when | Main cost |
|---|---|---|
| External pooler | Many replicas, short transactions | Session-state limits, new component to run |
| Fewer replicas | Replicas idle on connections | Less headroom for traffic spikes |
| Shorter transactions | Connections held during non-DB work | Code changes |
| Read replicas | Read-heavy traffic | Replication lag, routing logic |
Raise max_connections |
Server has spare memory and CPU | Per-backend memory, contention |
Before adding any of these, do the connection math across all instances. It often shows that shorter transactions or smaller pools fix the problem, and those changes cost much less to build and run than a new piece of infrastructure.
How can pool size tuning save engineering time?
Most of the time saved comes from replacing guesswork with a method that gives the same answer every time someone applies it.
- Fewer repeated "bump the pool and redeploy" cycles. Checking Hikari's
pendingandacquiremetrics,pg_stat_activitysession states and leak-detection traces together points at the actual cause: a slow query, a remote call inside a transaction, or open-session-in-view. One focused investigation replaces a series of config changes that each need a deploy and a wait for the next incident. - Capacity planning without load tests for every change. The connection budget formula tells you before a deploy whether a new service, a higher autoscaler maximum, or a deploy surge setting will exceed
max_connections. That turns a production outage into a review comment. - Clear ownership of the database's connections. When a platform team allocates a per-service connection budget, service teams have a concrete number to work within, and conflicts over a shared database become arithmetic rather than debate.
- Faster incident triage. Named pools,
ApplicationNametags and per-workload pools mean an on-call engineer can see which service and which workload is holding connections, instead of inferring it from aggregate database load. - Avoiding infrastructure you don't need. If the math shows that shorter transactions or smaller pools are enough, you skip deploying, monitoring and debugging an extra component on the request path.
Illustrative estimate (assumed numbers, not a measured result): assume each blind pool-size change takes 1 hour of engineer time to make, deploy and observe, and that a team goes through 4 such changes before the real cause is found. That is 4 hours per incident. If a single investigation using the metrics above takes an assumed 2 hours and ends with a fix, the saving is 2 hours per incident, before counting the time spent on the user-facing impact while each guess was in production. Substitute your own team's figures; the point is that the diagnostic approach replaces repeated cycles with a single one.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to hikaricp pool size tuning, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.