Long-Running Open Transactions

A long-open transaction is a problem for more than locks. To be able to roll back or show the data as of the moment that transaction started, the database cannot remove old row versions. In Oracle, undo keeps growing; in PostgreSQL, dead tuples; in SQL Server, the version store and the transaction log. The result is a full disk, bloated tables, or errors such as snapshot too old.

The search order is the same everywhere: find the oldest transaction, see what that session is doing, then ask for a commit or kill it. Killing it triggers a rollback of the same amount of work.

Oracle

Required privileges: SELECT on V$TRANSACTION, V$SESSION, and DBA_UNDO_EXTENTS (SELECT_CATALOG_ROLE).

Old transactions and undo usage

SELECT s.sid, s.serial#, s.username, s.status, s.program, s.sql_id, s.prev_sql_id,
       t.start_date, ROUND((SYSDATE - t.start_date) * 86400) AS age_sec,
       t.used_ublk, t.used_urec, t.xidusn AS undo_seg
FROM v$transaction t
JOIN v$session s ON s.taddr = t.addr
ORDER BY t.start_date;
  • used_ublk is the number of undo blocks in use and used_urec is the number of undo records. During a rollback, both values decrease.
  • A session with status = 'INACTIVE' and a large age is idle without committing. Find its last statement through prev_sql_id.

Undo tablespace state

SELECT tablespace_name, status, ROUND(SUM(bytes) / 1024 / 1024) AS mb
FROM dba_undo_extents
GROUP BY tablespace_name, status
ORDER BY tablespace_name, status;
  • ACTIVE: in use by an open transaction, so it cannot be reused.
  • UNEXPIRED: finished, but kept because it is within undo_retention. It can be reused if space runs short (unless RETENTION GUARANTEE is set).
  • EXPIRED: can be reused at any time.

Long queries and ORA-01555

SELECT begin_time, end_time, undoblks, maxquerylen, maxqueryid,
       tuned_undoretention, ssolderrcnt, nospaceerrcnt
FROM v$undostat
ORDER BY begin_time DESC
FETCH FIRST 24 ROWS ONLY;
  • Records are in 10-minute intervals. maxquerylen (seconds) is the longest-running query in that interval, and maxqueryid is its SQL_ID.
  • ssolderrcnt is the number of ORA-01555: snapshot too old errors and nospaceerrcnt is the number of undo space shortages. If tuned_undoretention is shorter than maxquerylen, undo is insufficient.
  • Not only transactions: a long-running SELECT also needs undo for consistent reads.

Rollback progress

After killing a session, follow the rollback by how fast V$TRANSACTION.used_ublk decreases. Rollback performed by SMON after an instance restart is checked separately.

SELECT usn, state, undoblocksdone, undoblockstotal,
       ROUND(undoblocksdone / NULLIF(undoblockstotal, 0) * 100, 1) AS pct
FROM v$fast_start_transactions;

PostgreSQL

Required privileges: pg_read_all_stats to see other users' query text.

Old transactions

SELECT pid, usename, application_name, state,
       now() - xact_start AS xact_age,
       backend_xid, backend_xmin, age(backend_xmin) AS xmin_age,
       left(query, 80) AS last_query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY xact_start
LIMIT 20;
  • backend_xmin is the oldest transaction number this session may still need to see. VACUUM cannot remove dead tuples newer than it.
  • A long transaction that only runs SELECT, with no writes, also holds backend_xmin (for the whole transaction under REPEATABLE READ, for the duration of a statement under READ COMMITTED).

Finding what holds the xmin horizon

It is not only sessions. Replication slots, prepared transactions (2PC), and a standby's hot_standby_feedback also hold the horizon.

SELECT 'session' AS source, pid::text AS id, age(backend_xmin) AS xmin_age
FROM pg_stat_activity WHERE backend_xmin IS NOT NULL
UNION ALL
SELECT 'replication slot', slot_name, GREATEST(age(xmin), age(catalog_xmin))
FROM pg_replication_slots WHERE xmin IS NOT NULL OR catalog_xmin IS NOT NULL
UNION ALL
SELECT 'prepared xact', gid, age(transaction)
FROM pg_prepared_xacts
UNION ALL
SELECT 'standby feedback', application_name, age(backend_xmin)
FROM pg_stat_replication WHERE backend_xmin IS NOT NULL
ORDER BY xmin_age DESC NULLS LAST;
  • An unused replication slot (pg_replication_slots.active = false) also accumulates WAL. If it is not needed, drop it with pg_drop_replication_slot('name').
  • A prepared transaction remains even without a session. End it with COMMIT PREPARED 'gid' or ROLLBACK PREPARED 'gid'.

WARNING If you drop a replication slot, the replica or CDC consumer that used it must be resynchronized from scratch. Rolling back a prepared transaction can leave its outcome inconsistent with the other side of the distributed transaction.

Checking whether VACUUM cannot clean up

SELECT relname, n_live_tup, n_dead_tup, last_autovacuum, last_vacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 20;

Running VACUUM (VERBOSE) table; prints the number of dead tuples that cannot be removed yet and the xmin cutoff (wording varies by version). If autovacuum has run but n_dead_tup does not drop, suspect an old xmin.

Transaction ID exhaustion risk

SELECT datname, age(datfrozenxid) AS xid_age,
       current_setting('autovacuum_freeze_max_age')::bigint AS freeze_max_age
FROM pg_database
ORDER BY xid_age DESC;

When xid_age exceeds autovacuum_freeze_max_age (default 200 million), a forced (anti-wraparound) VACUUM runs. As it nears about 2 billion, writes are blocked. While the horizon is held, freezing does not advance either.

Setting time limits

ALTER SYSTEM SET idle_in_transaction_session_timeout = '10min';
ALTER SYSTEM SET transaction_timeout = '1h';          -- PostgreSQL 17+
SELECT pg_reload_conf();

WARNING A session that exceeds the limit is disconnected (idle_in_transaction_session_timeout) or its transaction fails. Rather than applying this server-wide, it is safer to apply it only to application roles, as in ALTER ROLE app SET ....

SQL Server

Required privileges: VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE in 2022+).

Old transactions and log usage

SELECT st.session_id, s.login_name, s.program_name, s.status,
       at.transaction_begin_time,
       DATEDIFF(SECOND, at.transaction_begin_time, SYSDATETIME()) AS age_sec,
       DB_NAME(dt.database_id) AS db,
       dt.database_transaction_log_bytes_used / 1024 / 1024 AS log_mb
FROM sys.dm_tran_active_transactions at
JOIN sys.dm_tran_session_transactions st ON st.transaction_id = at.transaction_id
JOIN sys.dm_exec_sessions s ON s.session_id = st.session_id
LEFT JOIN sys.dm_tran_database_transactions dt ON dt.transaction_id = at.transaction_id
ORDER BY at.transaction_begin_time;

If a transaction touches several databases, one row appears per database. To check just one database quickly, run DBCC OPENTRAN; in that database. It shows the SPID and start time of the oldest active transaction.

Why the log is not reused

SELECT name, recovery_model_desc, log_reuse_wait_desc
FROM sys.databases;

-- Log usage of the current database
SELECT total_log_size_in_bytes / 1024 / 1024 AS log_mb, used_log_space_in_percent
FROM sys.dm_db_log_space_usage;
  • ACTIVE_TRANSACTION: the log cannot be truncated because of an open transaction. Find that transaction with the query above.
  • LOG_BACKUP: the database is in the FULL recovery model but there is no log backup. This is not a transaction problem.
  • Others include REPLICATION, AVAILABILITY_REPLICA (a secondary replica is behind), and ACTIVE_BACKUP_OR_RESTORE.
  • To check all databases at once, use DBCC SQLPERF(LOGSPACE);.

Version store usage

With snapshot isolation (SNAPSHOT, READ_COMMITTED_SNAPSHOT), old row versions accumulate in the tempdb version store and are removed only after the oldest snapshot transaction ends.

-- Version store size per database (2017+, 2016 SP2+)
SELECT DB_NAME(database_id) AS db, reserved_space_kb / 1024 AS version_store_mb
FROM sys.dm_tran_version_store_space_usage
ORDER BY reserved_space_kb DESC;

-- Snapshot transactions holding versions
SELECT session_id, transaction_id, elapsed_time_seconds, is_snapshot
FROM sys.dm_tran_active_snapshot_database_transactions
ORDER BY elapsed_time_seconds DESC;
  • Rows with is_snapshot = 0 are READ_COMMITTED_SNAPSHOT statements. They are released when the statement ends.
  • A database with Accelerated Database Recovery (ADR, 2019+) enabled keeps versions not in tempdb but in a persistent version store (PVS) inside that database. Check its size with sys.dm_tran_persistent_version_store_stats.

Ending a transaction

An open transaction ends only when the session is killed (KILL; see Viewing and Killing Sessions). Check rollback progress with KILL 57 WITH STATUSONLY;.

WARNING A long-running transaction also takes a long time to roll back, and its locks and log remain meanwhile. In a database with ADR enabled, rollback finishes almost instantly.