Video in progress

Strong Middle 🌱 Spring

You see "Connection is not available, request timed out after 30000ms". What do you check?

Every connection in the pool is busy, and none was freed within 30 seconds. Most of the time the pool isn't too small; connections are being held too long: a slow query, an external call inside a transaction, an unclosed connection or a deadlock.

📖 Answer

I usually look in this order.

  1. Thread dump. Take one while the error is happening (jstack or /actuator/threaddump) and see where the threads are stuck:
  • JDBC inside SocketInputStream.read: waiting for the database to respond (a slow query or a lock);
  • inside an HTTP client, but with TransactionInterceptor on the stack: waiting for an external API inside a transaction.
  1. The database itself. In PostgreSQL:
select pid, state, now() - xact_start as dur, query
from pg_stat_activity where datname = 'shop' order by dur desc;

Sessions that sit in idle in transaction for a long time mean the application opened a transaction and forgot about it.

  1. A connection leak: calling dataSource.getConnection() by hand and never closing it. To find it:
spring.datasource.hikari.leak-detection-threshold: 20000

Hikari logs a stack trace showing where a connection that was held longer than 20 seconds was acquired.

  1. Nested REQUIRES_NEW: every request needs two connections, and when the pool is full everyone freezes waiting for the second one.

The fix is usually simple: shorten the transaction, move the external call out of it, add an index for the slow query. Lowering connection-timeout from 30 s to 2-5 s is also a good idea: the user won't wait half a minute, and the system fails faster and recovers faster.