Video in progress
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:
- each enters a
@Transactionalmethod and takes one connection, so the pool is empty; - inside each,
auditService.log()is called, and it'sREQUIRES_NEW; - each is waiting for another connection from the pool;
- 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 outerTransactionInterceptoris on their stack too; - Hikari metrics:
hikaricp_connections_pendinghas shot up, andactive= 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.
Sign up to mark studied questions and save your progress.