Requests start timing out with 'Connection is not available' from HikariCP. What's happening and how do you fix it?
BackendSenior
In shortAll pool connections are in use and new requests wait until the timeout. Causes are connections held too long (slow queries, long transactions, remote calls inside transactions), leaks, or more concurrency than the pool and database can serve. Fix the holders first, then size the pool deliberately.
Model answer
A connection pool hands out a fixed number of database connections. When all are borrowed, callers wait up to connectionTimeout (30 s by default in HikariCP) and then fail. So the question is always: who is holding connections, and for how long?
Common causes:
- Slow queries (missing index, N+1 inside a loop) keep connections busy longer under load.
- Long transactions: a
@Transactionalmethod that calls another service over HTTP holds its connection for the whole remote call. A slow dependency then exhausts your database pool. - Leaks: connections not returned (manual JDBC without try-with-resources, streams left open).
- Concurrency spikes: more in-flight requests than the pool can serve, often amplified by retries.
Diagnose: pool metrics (hikaricp.connections.active, pending, usage and acquire times), slow-query logs, traces showing time waiting for a connection, leakDetectionThreshold to log stack traces of connections held too long, and thread dumps showing threads blocked in getConnection.
Fix:
- Keep transactions short: no remote calls inside them; load, decide, write.
- Fix slow queries and N+1s; set statement and transaction timeouts.
- Size the pool for the database, not the request rate: a small pool (often 10–30 per instance) with queueing performs better than hundreds of connections fighting for CPU and locks. Total connections across all instances must fit the database’s limit.
- Bound concurrency upstream (bulkheads, rate limits) and fail fast with clear errors instead of queuing forever.
What they're looking for
Understanding of pool mechanics, the usual root causes, how to diagnose with pool metrics and leak detection, sizing reasoning (database capacity, not request count), and protecting the system with timeouts and bounded concurrency.
Common mistakes
- Raising the pool size to hundreds as the first fix.
- HTTP calls inside @Transactional methods.
- No query timeouts.
More backend questions
- What is the N+1 query problem, and how do you find and fix it?Mid-level
- What does Spring Boot's auto-configuration do, and how do you change what it set up?Mid-level
- How does a Spring backend authenticate requests from a mobile app, and how do you make sure users only see their own data?Mid-level
- Your Spring Boot service in Kubernetes keeps restarting with exit code 137. How do you investigate and fix it?Senior