Video in progress

Strong Middle 🌱 Spring

Why does a service that uses REQUIRES_NEW heavily hang under load?

Each REQUIRES_NEW asks the pool for a second connection while holding the outer transaction's connection. If as many threads as the pool size are in outer transactions at the same time, they all wait for a second connection and nobody releases one, which is a deadlock at the pool level.

📖 Answer

The arithmetic is easy to show. HikariCP maximum-pool-size = 10. 10 requests arrive at the same time:

  1. each enters a @Transactional method and takes one connection, so the pool is empty;
  2. inside each, auditService.log() is called, and it's REQUIRES_NEW;
  3. each is waiting for another connection from the pool;
  4. nobody releases the outer connection, because the outer transaction is waiting for the inner one to finish.

After 30 seconds everything fails with SQLTransientConnectionException: Connection is not available. Under a small load the problem isn't visible, which is why it isn't found in the test environment.

How you detect it:

  • in a thread dump, many threads are waiting inside HikariPool.getConnection, and the outer TransactionInterceptor is on their stack too;
  • Hikari metrics: hikaricp_connections_pending has shot up, and active = max.

The solutions:

  • see whether you can give up REQUIRES_NEW: write the audit record after the commit (@TransactionalEventListener(AFTER_COMMIT)) or asynchronously;
  • if you need it, size the pool by the formula "concurrent transactions × connections each one uses", or limit parallel entry with a semaphore;
  • a separate small pool (a separate DataSource) for the inner work: this works for independent writes like audit.

A rule for code review: a REQUIRES_NEW called in a loop or on every request is a red flag.