Video in progress
How do long-open transactions hurt the database in a Hibernate service, and how do you find them?
A long transaction holds a connection, keeps the locks it took, and on PostgreSQL stops VACUUM from cleaning up old row versions, so tables and indexes bloat. To find them I watch xact_start and the idle in transaction state in pg_stat_activity, Hikari's leak detection, and transaction times in the APM.
📖 Answer
Hibernate itself does not make a transaction longer; the code does. Typical causes: an external HTTP call inside a @Transactional method, processing a large file, a session kept open until the whole view is rendered because of open-in-view, or a manually managed transaction that was left without a commit.
The damage shows up on several levels:
- connection pool: if 5 of 20 connections sit in "thinking" transactions, the remaining requests queue up;
- locks: row locks taken by
select for updateor a plain UPDATE stay until commit, others wait, and the chance of a deadlock goes up; - MVCC: PostgreSQL cannot clean up dead rows newer than the snapshot of an open transaction. A one-hour transaction means one hour of "garbage" across the whole database. As a result queries slow down and disk usage grows.
How to find them:
select pid, now() - xact_start as dur, state, left(query, 80)
from pg_stat_activity
where xact_start is not null
order by dur desc limit 10;
Sessions in the idle in transaction state are the most suspicious: the application opened a transaction and is doing nothing.
spring.datasource.hikari.leak-detection-threshold: 20000 # a connection held longer than 20 s gets a stack trace in the log
As protection I set idle_in_transaction_session_timeout and statement_timeout in the database, and @Transactional(timeout = ...) in the application. The main cure is architectural: do only database work inside the transaction, make external calls before or after it (via an outbox), and split big jobs into small batches, committing each one separately.
Sign up to mark studied questions and save your progress.