Part 12 of 12 · Databases

Why does one long-running transaction slow down the whole database?

Databases keep old row versions for as long as any open transaction might need them. One idle transaction on an unrelated table made PostgreSQL's busiest table 200× bigger and its writes 3× slower; in MySQL it made the old transaction's own reads 250× slower. Measured, with the settings that…

A city traffic jam with lanes of cars stuck behind each other

The culprit, as we’ll prove: both PostgreSQL and MySQL keep old versions of changed rows, so every open transaction can keep reading the data as it was when it started (this is MVCC, multi-version concurrency control). An old version can only be thrown away once no open transaction might still need it. So one transaction left open, even an idle one that only touched an unrelated table, stops the cleanup for the whole database.

  • In PostgreSQL the old versions pile up in the tables, so every query and every write on busy tables gets slower, and the tables stay bigger even after the transaction ends.
  • In MySQL (InnoDB) they pile up in the undo log. Other sessions barely notice, but the old transaction itself gets slower and slower, and so does purge.

The fix is the same in both: don’t hold transactions open, and set timeouts so the database ends the ones that are.

The case opens with a familiar symptom: the busiest table is suddenly slow, writes have dropped off, nothing in the slow-query log explains it, and no query touching that table looks guilty. I love this mystery because the answer shows how databases work underneath. MVCC is what lets readers and writers stop blocking each other, and the price of that trick is a promise to keep the past around for anyone who might still be looking at it.

I measured this on PostgreSQL 17 and MySQL 8.4. The code is in database-tradeoffs-lab, and make longtx reruns it.

Case file

The case The busiest table is suddenly slow and no query looks guilty
Suspects Queries touching that table, the slow-query log
Culprit One idle transaction left open on an unrelated table
The fix Short transactions, plus timeouts that end the ones left open
Evidence database-tradeoffs-lab on PostgreSQL 17 and MySQL 8.4 (make longtx)

Reconstructing the crime #

Let’s recreate the scene: what happens when one session forgets to commit.

  • 8 writers update 100 “hot” rows (balances, counters, job states) as fast as they can, for 20 seconds.
  • In PostgreSQL, VACUUM runs every second, far more often than autovacuum would.
  • Meanwhile, one other session runs BEGIN, reads one row from an unrelated reports table, and does nothing else. It stands in for a report, a SQL client with autocommit off, or a request that forgot to commit.
Flowchart: Idle transaction on reports, keeps an old snapshot, Cleanup horizon stuck, 8 writers update hot rows, Dead row versions, VACUUM removes nothing, Table grows, reads and writes slow down, idle_in_transaction_session_timeoutFlowchart: Idle transaction on reports, keeps an old snapshot, Cleanup horizon stuck, 8 writers update hot rows, Dead row versions, VACUUM removes nothing, Table grows, reads and writes slow down, idle_in_transaction_session_timeout
Diagram source
flowchart LR
  T["Idle transaction on reports"] -->|"keeps an old snapshot"| H["Cleanup horizon stuck"]
  W["8 writers update hot rows"] --> D["Dead row versions"]
  H --> V["VACUUM removes nothing"]
  D --> V
  V --> B["Table grows, reads and writes slow down"]
  TO["idle_in_transaction_session_timeout"] -.->|ends the session| T

Two witnesses, two stories #

Two databases, the same idea, and two very different places to keep the history.

PostgreSQL 17 MySQL 8.4 (InnoDB)
Where old versions live In the table, next to the live rows In the undo log; the table holds the newest version
Who removes them VACUUM (and autovacuum) Purge threads, in the background
What an old transaction holds back VACUUM, in every table of the database Purge, for the whole instance
Who pays while it’s open Everyone using the busy tables: bigger tables, slower writes and scans Mostly the old transaction itself, which rebuilds old versions from undo, plus a growing undo log
After it ends Dead rows removable, but the table stays big until rewritten Purge catches up; undo space is reused
Built-in guard idle_in_transaction_session_timeout, transaction_timeout (17+), statement_timeout max_execution_time for SELECTs; idle transactions must be found and killed
Where to look pg_stat_activity (xact_start, backend_xmin), pgstattuple information_schema.innodb_trx, “History list length” in SHOW ENGINE INNODB STATUS

The evidence from PostgreSQL #

Updates in 20 s Dead row versions VACUUM couldn’t remove Table size Point read p50 Read all 100 rows
No long transaction 590K-682K 0 32-48 kB 0.07-0.09 ms 0.12 ms
One transaction left open on another table 233K-257K every one (233K-257K) 9.9-10.9 MB 0.30-0.38 ms 3.7-4.1 ms
The same, with idle_in_transaction_session_timeout = 2s 543K-553K 0 1.6-1.7 MB 0.10 ms 0.14-0.20 ms
Chart: PostgreSQL: read all 100 rows, ms (slowest of three runs)Chart: PostgreSQL: read all 100 rows, ms (slowest of three runs)
Diagram source
xychart-beta
  title "PostgreSQL: read all 100 rows, ms (slowest of three runs)"
  x-axis ["No long transaction", "One left open", "With 2s idle timeout"]
  y-axis "ms"
  bar [0.12 , 4.1 , 0.20]

(Ranges across three runs; full results.)

What the evidence shows:

  • VACUUM ran every second and removed nothing. Every update leaves the previous version behind as a dead row. VACUUM may only remove a dead row once it’s older than every open transaction’s snapshot. The idle transaction’s snapshot was older than all of them, so all ~250,000 dead versions stayed. It never touched the accounts table; it only existed. That’s the striking part: a session doing nothing at all can still hold the whole database’s history hostage.
  • The 100-row table grew 200×, to about 10 MB, because there was nowhere to reuse. Reading all 100 rows meant reading 10 MB of mostly dead versions: about 30× slower. Single-row reads by primary key were 4× slower.
  • Writes slowed to a third. Each update had to put its new version on a new page and update the index, instead of reusing space on the same page.
  • Ending the transaction didn’t shrink the table, a false comfort many people fall for. After a final VACUUM, the dead rows were gone, but the file was still ~10 MB: plain VACUUM marks the space for reuse and only gives back empty pages at the end of the file. Reading all rows was still 3× slower than before. Only a rewrite (VACUUM FULL, which locks the table, or pg_repack) returns the space.
  • A 2-second idle timeout limited the damage to 2 seconds’ worth (1.6 MB). PostgreSQL ended the session; VACUUM caught up and reused the space.

The evidence from MySQL #

Updates in 20 s History list length Point read p50: new session / old transaction Read all 100 rows: new session / old transaction
No long transaction 84K-89K 226-356 0.11 ms / - 0.14-0.16 ms / -
A consistent-snapshot transaction left open 58K-71K 58K-71K (every update) 0.11 ms / 0.52-0.60 ms 0.14 ms / 34-43 ms

Here the case takes a twist. InnoDB makes a different choice. It updates the row in place and writes the previous version to the undo log, so:

  • New sessions didn’t notice. They read the newest version, which sits in the table.
  • The old transaction paid. To show each row as it was when it started, it walked back through every later version in the undo log. Reading all 100 rows took 34-43 ms instead of 0.14 ms, and it gets worse with every update. A long-running report is exactly that old transaction: it slows itself down by staying open.
  • Purge couldn’t run. The history list (undo records waiting for purge) grew by one per update, to about 70,000. On a busy production server, that’s millions, and the undo log grows on disk. Writes in this run also dropped by about 20-30%.

The difference is where the cost lands, and I find it a lovely illustration of how one design decision shapes everything downstream. PostgreSQL makes everyone pay, and keeps paying until the table is rewritten. MySQL makes the long transaction pay, plus disk and purge work that catch up afterwards.

Case 1: the report on the primary #

Situation: finance runs a 40-minute report against the production primary every morning, in one transaction.

In PostgreSQL, that’s 40 minutes in which VACUUM can’t clean up anything changed in that database: queue tables, sessions, counters. On busy tables, 40 minutes of dead rows is a lot of bloat.

What I’d do:

  • Run reports on a read replica (see the replicas post). On the replica, a long query can still be cancelled by replay conflicts; hot_standby_feedback = on avoids that, but sends the replica’s horizon back to the primary, which brings the problem back.
  • Or run them on a separate analytics copy.
  • If they must run on the primary, set statement_timeout and split them into shorter queries.

Case 2: the forgotten transaction #

Situation:

  • an application path that starts a transaction and returns early on an error without rolling back;
  • an ORM session left open in a long-lived worker;
  • an engineer’s SQL client with autocommit off, left open over lunch.

pg_stat_activity shows these as idle in transaction.

What I’d do: set a timeout so the database ends them, on the application’s role:

ALTER ROLE app SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE app SET statement_timeout = '15s';       -- interactive traffic
ALTER ROLE app SET transaction_timeout = '60s';     -- PostgreSQL 17+: the whole transaction

Find the oldest transactions, and what they’re doing:

SELECT pid, usename, state, now() - xact_start AS open_for, age(backend_xmin) AS xmin_age, left(query, 60)
FROM pg_stat_activity WHERE xact_start IS NOT NULL ORDER BY xact_start LIMIT 5;

In MySQL, there’s no idle-in-transaction timeout (wait_timeout closes any idle connection, but defaults to 8 hours), so find and alert on old transactions instead:

SELECT trx_mysql_thread_id, trx_started, now() - trx_started AS open_for, trx_query
FROM information_schema.innodb_trx ORDER BY trx_started LIMIT 5;

Case 3: the batch job in one transaction #

Situation: a nightly job updates every row of a big table in a single transaction “so it’s all or nothing”.

In PostgreSQL, that one transaction creates a full table’s worth of dead versions, and holds back cleanup everywhere until it commits. It also holds its row locks the whole time (the lag-debugging post measured what that does to the pages waiting on them).

What I’d do: batches of a few thousand rows, each its own transaction. Make the job restartable: record progress, and make each batch idempotent. “All or nothing” is rarely worth an hour-long transaction.

Case 4: accomplices that act like an open transaction #

Not every horizon-holder shows up as a session; some suspects never appear in the line-up at all:

  • A replica with hot_standby_feedback = on holds back VACUUM on the primary as if its queries ran there.
  • A prepared transaction (PREPARE TRANSACTION, used by some distributed-transaction tools) left uncommitted holds it too (pg_prepared_xacts).
  • An abandoned replication slot retains WAL until the disk fills, and can hold VACUUM back too: a logical slot through its catalog_xmin, a physical slot through the xmin it kept from hot_standby_feedback (pg_replication_slots).

Check all of these when VACUUM isn’t keeping up and no session looks guilty.

Remember this

  • An idle open transaction holds back cleanup for the whole database.
  • PostgreSQL makes everyone pay, and the table stays big after it ends.
  • Set idle_in_transaction_session_timeout and alert on the oldest transaction’s age.

Case closed: what I’d do by default #

  1. Set timeouts on application roles: idle_in_transaction_session_timeout (30 s-5 min), statement_timeout for interactive traffic, and transaction_timeout on PostgreSQL 17+. In MySQL, max_execution_time for SELECTs, and an alert on innodb_trx.
  2. Alert on the age of the oldest transaction, not only slow queries. A transaction that’s idle doesn’t show up as slow.
  3. Keep reports off the primary, and batch jobs in short transactions.
  4. When a PostgreSQL table has already bloated, fix the cause first. Then reclaim the space with pg_repack (online) or VACUUM FULL (locks the table) in a quiet window.
  5. Watch dead tuples and table size on your busiest tables. Queue tables, sessions and counters bloat first, and quickly.

Once you see the old row versions piling up, the mystery of the slow database becomes almost touching: the database is faithfully keeping its promise to one forgotten session. Close that session, and the promise lets everyone else go.

Checked on PostgreSQL 17.11 and MySQL 8.4.13 (Nov 2026), one laptop, everything in Docker, with commits not waiting for the disk so the writers weren’t limited by fsync (this doesn’t change how versions are kept). Dead rows counted with pgstattuple. Code and full results: database-tradeoffs-lab/07-long-transactions.

Like (sign in first) 0 likes 💬 0

Written by

Vishal Kumar

Associate Director at CapGrid, running product and engineering in a CPTO capacity. 10+ years building distributed, multi-tenant SaaS and AI platforms. AWS Certified Solutions Architect - Professional. Based in Gurugram.

Comments

No comments yet.

Sign in to comment. We'll email you a link; no password needed.