Video in progress

Strong Middle 🐻 Hibernate and JPA

How do you limit long-running queries: how do the JPA query timeout, `@Transactional(timeout)` and the database's `statement_timeout` differ?

The jakarta.persistence.query.timeout hint sets a limit in milliseconds on a single query and works through JDBC setQueryTimeout. @Transactional(timeout) passes the time remaining in the whole transaction to each query as its timeout. PostgreSQL's statement_timeout is the last line of defense on the database side: it applies no matter what the application does.

📖 Answer

For a single query:

List<Report> rows = em.createQuery("select r from Report r where ...", Report.class)
    .setHint("jakarta.persistence.query.timeout", 3000)   // ms
    .getResultList();

In Spring Data:

@QueryHints(@QueryHint(name = "jakarta.persistence.query.timeout", value = "3000"))
List<Report> findHeavy(...);

When the time runs out, the driver sends a cancel request to the database and QueryTimeoutException comes back. JDBC setQueryTimeout works in seconds, so milliseconds get rounded.

For a transaction:

@Transactional(timeout = 5)   // seconds
public void monthlyClose() { ... }

JpaTransactionManager sets each query's timeout to the "time left in the transaction". Note: this affects only the SQL. If you wait 10 seconds on an external HTTP call inside the method, the transaction isn't stopped; it fails on the next SQL statement.

At the database level:

alter role app_user set statement_timeout = '30s';
alter role app_user set idle_in_transaction_session_timeout = '60s';

This works regardless of bugs in the application, and it also closes transactions that were left open.

I use all three layers together: a broad general limit in the database (say, 30 s), an explicit hint on heavy report queries, and on HTTP endpoints timeouts matched to the endpoint's SLA. When a timeout happens, the client gets a 503 or a clear message, and retries are only for idempotent reads.