DEV Community

Cover image for One forgotten transaction grew my 5 MB table to 132 MB in 2 minutes
Muhammad Adnan
Muhammad Adnan

Posted on Edited on

One forgotten transaction grew my 5 MB table to 132 MB in 2 minutes

This is the kind of code that ends up in every Node backend sooner or later:

const client = await pool.connect();
await client.query('BEGIN');
await client.query('UPDATE sessions SET touched_at = now() WHERE id = $1', [sessionId]);
await chargeCard(order);            // throws on a declined card
await client.query('COMMIT');
client.release();
Enter fullscreen mode Exit fullscreen mode

When chargeCard throws, nothing rolls back and nothing releases the client. The connection stays checked out of the pool, sitting in an open transaction that will never finish. It holds one row lock on sessions, which looks harmless.

I measured what it does to a different table.

The setup

PostgreSQL 16, default autovacuum settings. An accounts table with 100,000 rows (5.1 MB) gets a steady stream of small updates: pgbench, 8 clients, one UPDATE accounts SET balance = balance + 1 WHERE id = random per transaction, for 2 minutes (about 21,000 to 24,000 updates a second). Scripts and full output are in the measurement folder for this post.

I ran it twice. In run B, one other session did the sessions update above in a transaction and then went idle without committing.

After 2 minutes of updates A: no open transaction B: one idle transaction
accounts table size 6.1 MB 132 MB
Primary key index size 2.2 MB 29 MB
Dead row versions 1,075 2,561,566
SELECT sum(balance) FROM accounts 6.5 ms 52 ms
Index range lookup, 101 rows 0.034 ms, 38 buffers 4.3 ms, 2,428 buffers

The idle transaction never touched accounts.

Why one idle session bloats every table

Every UPDATE in Postgres writes a new version of the row and leaves the old one behind as a dead row. VACUUM (autovacuum, normally) removes dead rows once no running transaction could still need to see them.

The idle session's transaction started before all those updates. As far as Postgres knows, it might still read accounts and need the old versions. So VACUUM keeps every dead row created after it began, in every table of the database. Autovacuum did run in B, twice. It just couldn't remove anything. VACUUM VERBOSE says so directly:

tuples: 0 removed, 2649200 remain, 2549200 are dead but not yet removable
Enter fullscreen mode Exit fullscreen mode

In run A, the same command removed what it found and reported 0 are dead but not yet removable.

Reads slow down because the rows are now spread over 22 times as many pages (16,878 instead of 758). The range lookup has to visit 2,422 heap pages to find 101 live rows, most of the versions it finds there are dead, and the index points at all of them.

Ending the transaction doesn't shrink the table

Once the idle session ended, the next VACUUM removed all 2,549,200 dead rows. But:

After the transaction ended and VACUUM ran
Table size still 132 MB
SELECT sum(balance) 17 ms (was 6.5 ms before the bloat)
Index range lookup 0.125 ms

VACUUM marks the space as free for new rows; it doesn't give it back to the operating system. A full scan still reads all 16,878 pages, mostly empty. Getting the size back needs VACUUM FULL, which locks the table for reads and writes while it rewrites it, or pg_repack, which does it online.

Two minutes at a high update rate did this. An idle transaction left open over a weekend does the same to a slower table.

The fix

1. Always end the transaction and release the client, whatever happens in between:

const client = await pool.connect();
let connError: Error | undefined;
const onError = (err: Error) => { connError = err; }; // see the warning under fix 2
client.on('error', onError);
try {
  await client.query('BEGIN');
  await client.query('UPDATE sessions SET touched_at = now() WHERE id = $1', [sessionId]);
  await chargeCard(order);
  await client.query('COMMIT');
} catch (err) {
  await client.query('ROLLBACK').catch(() => {}); // the connection may already be gone
  throw err;
} finally {
  client.off('error', onError);
  client.release(connError); // an error here destroys the connection instead of reusing it
}
Enter fullscreen mode Exit fullscreen mode

Better still, don't call slow external services (payments, email, HTTP) inside a database transaction at all. Do them before BEGIN or after COMMIT.

2. Put a limit on it at the database, so a bug can't hold a transaction open forever:

ALTER ROLE app SET idle_in_transaction_session_timeout = '30s';
Enter fullscreen mode Exit fullscreen mode

Postgres then ends any session of that role that sits idle inside a transaction for 30 seconds, which rolls the transaction back and frees the dead rows for VACUUM. Pick a value well above your slowest legitimate gap between statements.

Warning for node-postgres users: when Postgres ends a session this way, the client your code has checked out of the pool emits an 'error' event. The pool removes its own error listener while a client is checked out and only puts it back on release(), so pool.on('error') doesn't cover it. With no listener on the client, Node treats the event as an uncaught error and the whole process exits. That's true for the leaked client in the first example, and for the try/finally version too if chargeCard runs longer than the timeout. Attach the client.on('error') handler from fix 1 before you turn the timeout on. (Thanks to Sunnatulla in the comments, who hit this on PostgreSQL 17 with pg 8.23.)

3. Watch for it. This query shows sessions holding a transaction open, oldest first:

SELECT pid, state, now() - xact_start AS xact_age, left(query, 60) AS last_query
FROM pg_stat_activity
WHERE state LIKE 'idle in transaction%'
ORDER BY xact_start;
Enter fullscreen mode Exit fullscreen mode

Anything measured in minutes is worth an alert. In VACUUM logs, a growing "dead but not yet removable" count is the same problem seen from the other side. Long-running queries and a replica with hot_standby_feedback on hold dead rows back in the same way.

Checklist

  • Every BEGIN has a ROLLBACK in a catch and a release() in a finally.
  • Every client checked out of the pool has its own 'error' listener until it's released.
  • No network calls to other services inside a database transaction.
  • idle_in_transaction_session_timeout is set for the application role.
  • An alert fires on transactions older than a few minutes in pg_stat_activity.
  • After an incident, check table sizes: VACUUM won't shrink them back.

Making Claude Code write it this way

The first version reads fine in review and works until the first declined card. The backend PR review skill in my Claude Code skills pack for TypeScript + GraphQL + Postgres backends checks how multi-step writes use transactions; the pack also has skills for safe migrations, slow-query profiling and integration tests against a real Postgres.

Top comments (2)

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

With node-postgres that timeout turns the bloat into a crash. I ran your leaked handler on PG 17 with pg 8.23: the server kills the session, the checked-out client emits 'error' with no listener, and the whole process exits. pool.on('error') doesn't catch it, and the try/finally version dies the same way if chargeCard runs past the timeout. A client.on('error') right after pool.connect() fixed it for me.

Collapse
 
muhammad_adnan_61b78b9816 profile image
Muhammad Adnan •

You're right, thanks for running it. pg-pool removes its error listener when it hands out a client and only puts it back on release(), so a checked-out client that the server terminates has nobody listening and the error takes the process down. I'm updating the post to attach client.on('error', ...) right after pool.connect() and to warn that the timeout needs it. Good catch.