Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java: HikariPool connection is not available, request timed out

The HikariCP pool ran out of connections for the whole connectionTimeout. Read the counters, find leaks or slow queries, then size the pool.

~5 min readJava
#java#hikaricp#spring-boot#jdbc
HikariCP pool diagram with exhausted connection slots and a waiting queue of threads

Introduction & Quick Summary

A Spring Boot service starts returning 500s under load, and the log has one repeated cause:

code
java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms. at com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:696) at com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:193)

Quick answer: every connection in the pool was in use for the whole connectionTimeout, and the caller gave up waiting. That is an exhaustion problem, not a network problem — find out who is holding the connections:

# application.yml — make the pool observable before changing its size spring: datasource: hikari: maximum-pool-size: 10 connection-timeout: 30000 leak-detection-threshold: 20000 # logs a stack trace when a connection is held too long register-mbeans: true
java
// or read the counters directly HikariDataSource ds = (HikariDataSource) dataSource; HikariPoolMXBean pool = ds.getHikariPoolMXBean(); log.info("active={} idle={} total={} waiting={}", pool.getActiveConnections(), pool.getIdleConnections(), pool.getTotalConnections(), pool.getThreadsAwaitingConnection());

If active sits at maximumPoolSize and waiting grows, the pool is too small, the queries are too slow, or a code path leaks connections — three different fixes the numbers tell apart within a minute.

Core Mechanics, Signatures & Reproducible Setup

HikariCP is a fixed-size pool with a wait queue. A caller asking for a connection either gets an idle one, or blocks until connectionTimeout expires, at which point it throws SQLTransientConnectionException with the pool name.

SettingDefaultMeaning
maximumPoolSize10hard cap on open connections
minimumIdlesame as maxconnections kept ready
connectionTimeout30000 msmax wait before the exception
idleTimeout600000 msretire unused connections
maxLifetime1800000 msretire any connection, keeps failover working
keepaliveTime0 (off)ping idle connections to detect dead ones
leakDetectionThreshold0 (off)log a stack trace when held too long

The pool name in the message identifies which datasource starved: HikariPool-1 is created first, so a replica or reporting datasource can be the one failing while the primary looks healthy.

A pool of one reproduces it:

java
HikariConfig cfg = new HikariConfig(); cfg.setJdbcUrl("jdbc:postgresql://localhost:5432/app"); cfg.setMaximumPoolSize(1); cfg.setConnectionTimeout(1000); try (HikariDataSource ds = new HikariDataSource(cfg)) { Connection first = ds.getConnection(); // never closed try (Connection second = ds.getConnection()) { // never reached: HikariPool-1 - Connection is not available, request timed out after 1000ms. } first.close(); }

Little's law gives the connections a workload needs: connections ≈ queries per second × average query duration in seconds. Thirty queries per second at 20 ms fits one connection; 200 per second at 50 ms needs ten, and a single two-second query removes one connection from the pool for two seconds.

Key Comparison Table

Message variantCauseFirst check
Connection is not available, request timed out after 30000mspool exhaustedactive vs max, waiting count
same message, low loadone leaked connection per requestleak-detection-threshold
Connection reset / Communications link failureconnection died in the poolkeepaliveTime, maxLifetime
Connection refuseddatabase down or wrong hostpg_isready, firewall
too many connections from the databasepool larger than the server allowsmax_connections × instances
message appears only after idle periodsfirewall or proxy dropped idle socketskeepaliveTime, validationTimeout
SymptomLikely causeFix
active = max, waiting grows with trafficundersized pool or slow queriestune queries, then size the pool
active = max, waiting grows with no trafficleak or long transactionleak detection, thread dump
active fluctuates, timeouts under burstsbursts exceed poolqueue or raise size within DB limits
every instance times out togetherdatabase saturatedcheck server sessions and locks
one endpoint times out, others finethat endpoint holds connectionsinspect its transaction scope
TimeoutWhere it appliesTypical value
connectionTimeoutwaiting for a pooled connection30000 ms
validationTimeoutchecking a connection is alive5000 ms
idleTimeoutretiring idle connections600000 ms
maxLifetimeretiring any connection1800000 ms
statement_timeout (Postgres)a single queryper endpoint

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Read the pool state before resizing

Raising maximumPoolSize without evidence usually moves the failure into the database, where it becomes too many connections. Log the counters on a schedule and correlate them with the error:

java
@Component class PoolMetrics { private final HikariPoolMXBean pool; PoolMetrics(DataSource ds) { this.pool = ((HikariDataSource) ds).getHikariPoolMXBean(); } @Scheduled(fixedRate = 10_000) void log() { log.info("pool active={} idle={} total={} waiting={}", pool.getActiveConnections(), pool.getIdleConnections(), pool.getTotalConnections(), pool.getThreadsAwaitingConnection()); } }

If active stays below max while timeouts occur, the problem is not capacity: it is a connection that is unusable (dead socket, blocked query) or a caller with a shorter timeout than the pool's.

2. Leaks that survive code review

The classic leak is a Connection or EntityManager obtained outside a scope that closes it. In Spring, @Transactional closes the connection when the method returns, so a method that starts a transaction and waits on a remote call holds a connection for the whole call:

java
@Transactional public void importOrders(List<Long> ids) { for (Long id : ids) { Order o = remote.fetch(id); // network call inside the transaction repo.save(o); // connection held the entire time } }

Fetch outside the transaction and save in batches, or use a JdbcTemplate that returns rows quickly. With plain JDBC, try-with-resources on every Connection, PreparedStatement and ResultSet is the only reliable rule:

java
try (Connection c = ds.getConnection(); PreparedStatement ps = c.prepareStatement("select id from orders where state = ?")) { ps.setString(1, "open"); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { ids.add(rs.getLong(1)); } } }

Streaming a large result set without closing it early, or returning a Stream from a repository and consuming it later, keeps a connection open far longer than the query runtime.

3. Size the pool against the database

The pool must fit both the workload and the server. Three replicas with maximumPoolSize: 20 are 60 connections before admin sessions; PostgreSQL's default max_connections is 100.

-- PostgreSQL: who is connected and what they are doing select state, count(*) from pg_stat_activity where datname = 'app' group by state; select pid, now() - query_start as duration, left(query, 80) from pg_stat_activity where state = 'active' order by duration desc limit 10;

If the long-running queries belong to your service, fix them first; a bigger pool mostly multiplies the same slow queries. Consider a pool in front of the database (PgBouncer) when many instances are required.

4. Timeouts that must line up

Three timeouts sit on the same path, and a mismatch produces confusing failures: the HTTP client timeout, connectionTimeout, and the database statement timeout. If the HTTP timeout is 5 seconds and connectionTimeout is 30, clients disconnect long before the pool reports anything, and the logs stay empty.

spring: datasource: hikari: connection-timeout: 3000 # fail fast when the pool is exhausted validation-timeout: 1000 jpa: properties: jakarta.persistence.query.timeout: 5000

A short connectionTimeout turns an exhaustion event into a fast, visible error instead of a 30-second queue that cascades into thread starvation.

5. Spring-specific traps and dead idle connections

  • Multiple DataSource beans mean multiple pools, each sized against the same database.
  • spring.jpa.open-in-view=true (the default) keeps an EntityManager bound to the request, so lazy loading during rendering holds a connection until the response completes.
  • Connection reset inside the pool means infrastructure dropped idle sockets: set max-lifetime below the NAT or load-balancer idle timeout and keepalive-time to a few minutes.

When the failing queries need to be read side by side, the text diff tool compares two slow query logs, and the SQL formatter makes a long statement readable before you decide whether to index or rewrite it.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Raising the pool first. It converts a queue into database saturation and often hits max_connections on the server.
  • Leaving connectionTimeout at 30 seconds. Requests stack up for half a minute before failing, turning a slow query into an outage.
  • Closing the Connection but not the Statement. Close all three in nested try-with-resources.
  • Ignoring the database side. pg_stat_activity, SHOW PROCESSLIST and lock waits explain most exhaustion that looks like a pool bug.
  • Version notes. HikariCP 5 requires Java 11 and is the default pool in Spring Boot 3; HikariCP 6 requires Java 11+ and is used by Boot 3.4+. connectionTimeout has a 250 ms minimum, and values below it are rejected at startup. leakDetectionThreshold adds overhead and should stay above the longest legitimate query.

Official documentation: HikariCP configuration and Spring Boot SQL data access.

Official references

primary documentation

The Java documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.