Video in progress

A session has been sitting in "idle in transaction" for hours. How does that hurt the database?

Such a session holds an open transaction: the locks it took aren't released, and because of its snapshot VACUUM can't clean up dead rows across the whole cluster. As a result other queries wait on locks and tables bloat. You should limit it with idle_in_transaction_session_timeout.

📖 Answer

Usually this is a bug in the application: a transaction was opened, then the code is waiting on an external API, an exception was swallowed, or a connection went back to the pool without commit/rollback.

Finding them:

SELECT pid, usename, application_name, state,
       now() - xact_start AS tx_age,
       left(query, 80) AS last_query
FROM pg_stat_activity
WHERE state LIKE 'idle in transaction%'
ORDER BY xact_start;

The query column shows the last query the session ran, not the current one. That helps you find which place in the code it is.

The harm is threefold:

  • locks: if the transaction did an UPDATE, those rows are locked. Other queries wait, they also occupy connections, and the pool runs out;
  • VACUUM: rows that died after the oldest open snapshot can't be cleaned in any table. One forgotten session creates bloat across the whole database;
  • DDL: if a migration tries to ALTER TABLE, it waits for this session, and all the ordinary queries line up behind it.

Protection:

ALTER DATABASE app SET idle_in_transaction_session_timeout = '60s';

In an emergency you can cut the session off with SELECT pg_terminate_backend(pid). In the long run, in Spring you shouldn't make network calls inside a @Transactional method, and you should set spring.jpa.open-in-view=false.