skip to content

Four PostgreSQL import workers each wrap every one of 5,000 order lines in SAVEPOINT and RELEASE SAVEPOINT inside one transaction, and the cluster slows to a crawl; why, and what fixes it?

level: seniorimportance: should knowfreq 42%

answer

  1. each savepoint that writes gets an ID
  2. a small per-backend list in shared memory
  3. release is not rollback
  4. pg_subtrans and SubtransSLRU waits

basics

~20 s

In PostgreSQL each writing savepoint gets its own subtransaction XID, and a backend caches only 64. RELEASE keeps the slot, so past 64 the cache overflows and other sessions' snapshots resolve XIDs through pg_subtrans, contending on SubtransSLRU.

solid answer

~50 s

A `SAVEPOINT` starts a subtransaction, and once it writes it gets its own XID, a **subxid**, with its parent recorded in `pg_subtrans`. Each backend advertises up to 64 subxids in shared memory so other sessions can recognise them while building snapshots. `RELEASE SAVEPOINT` sub-commits the subtransaction but its subxid stays cached until the top-level transaction ends; only `ROLLBACK TO SAVEPOINT` removes one. The 65th writing savepoint marks the backend overflowed, and every other session's snapshot taken while that transaction runs is marked overflowed too, so checking any XID between the snapshot's `xmin` and `xmax` means a `pg_subtrans` lookup. With four workers doing this, every backend queues on that cache, visible as `SubtransSLRU` and `SubtransBuffer` waits. The fix is fewer savepoints: validate in a staging table, use `INSERT ... ON CONFLICT DO NOTHING`, or commit in batches below 64 savepoints.

code

sql · 7 lines
sql
BEGIN;
SAVEPOINT line;
INSERT INTO order_import_line (order_id, line_no, sku, qty)
VALUES (9001, 1, 'A-100', 5);
RELEASE SAVEPOINT line;   -- subxid stays cached until COMMIT
-- ... repeated for lines 2 to 5000 ...
COMMIT;

go deeper

for a junior

Know that a PostgreSQL savepoint starts a subtransaction and is not free, so wrapping every row in one is a pattern to question.

for a middle

Explain subxids, pg_subtrans and the 64-entry per-backend cache, and why RELEASE keeps a slot while ROLLBACK TO frees it.

for a senior

Diagnose the cluster-wide slowdown from SubtransSLRU waits and pg_stat_slru, then remove the per-row savepoints with staging, ON CONFLICT or batched commits.

for a principal

Set team rules for error handling that never needs per-row subtransactions, and review driver and framework settings that add savepoints implicitly.

## What a savepoint costs in PostgreSQL A `SAVEPOINT` starts a **subtransaction**. So does entering a PL/pgSQL block with an `EXCEPTION` clause, and so do client libraries that set a savepoint before every statement to survive errors. A subtransaction that only reads stays cheap. The first time one **writes**, PostgreSQL assigns it its own transaction ID, a **subxid**, and makes sure every parent up to the top-level transaction has an XID too; a parent's XID is always lower than its children's. Each subxid's parent is recorded in the `pg_subtrans` directory. `pg_current_xact_id()` still reports the top-level XID. ## The 64-slot cache To build a snapshot, a backend has to know every XID that is still running, subxids included. Each backend therefore advertises its subxids in shared memory, but only up to **64** of them (`PGPROC_MAX_CACHED_SUBXIDS` in the source). The rules that bite: - Only subtransactions that **wrote** take a slot. - **`RELEASE SAVEPOINT` does not free the slot.** The subtransaction is sub-committed; its XID must still look running to everyone else until the top-level transaction commits, so it stays cached. - **`ROLLBACK TO SAVEPOINT` does free it**, because an aborted subxid no longer needs to look running. - The **65th** subxid sets an *overflowed* flag on the backend, and that flag stays set until the top-level transaction ends. The import's pattern, `SAVEPOINT`, `INSERT`, `RELEASE SAVEPOINT` per line, therefore overflows after its 65th line and stays overflowed for the remaining 4,935. ## What overflow does to everyone else 1. Any other session's snapshot built while an overflowed transaction is running is itself marked **overflowed**: it no longer holds a complete list of running subxids. 2. For every XID that falls between that snapshot's `xmin` and `xmax`, the visibility check must first map it to its top-level parent through `pg_subtrans`, instead of scanning in-memory arrays. 3. `pg_subtrans` is read through a small shared cache, the `subtransaction` row in `pg_stat_slru`. Many backends hammering it queue on its locks, shown as LWLock wait events `SubtransSLRU` and `SubtransBuffer` in `pg_stat_activity`, and its `blks_read` climbs. 4. With four workers, each worker's snapshots see the other three overflowed, so their own unique-index and foreign-key checks against each other's freshly written rows all pay the lookup. Unrelated sessions pay it too. 5. On a hot standby, while such a primary transaction is running, snapshots are marked overflowed as well, so read replicas slow down with the primary. That is why the symptom is cluster-wide, not confined to the import. ## Fixing the import | Fix | How it avoids the problem | |---|---| | Load into a staging table, validate with set-based SQL, then one `INSERT ... SELECT` | Bad lines are filtered by queries, no per-line savepoint at all | | `INSERT ... ON CONFLICT (order_id, line_no) DO NOTHING` | Duplicate-key lines are skipped without raising an error | | Commit in batches of at most 64 savepoints | Each top-level commit empties the cache before it can overflow | | `COPY ... ON_ERROR ignore` (17+) | Skips rows whose values fail type conversion; `REJECT_LIMIT` (18) caps how many. Constraint violations still abort | | Raise `subtransaction_buffers` (17+) | Enlarges the `pg_subtrans` cache; it eases misses but does not remove the overflow | `subtransaction_buffers` defaults to `0`, meaning `shared_buffers`/512, at least 16 and at most 1024 blocks, and changing it needs a restart. It treats the symptom: the durable fix is to stop holding more than 64 writing subtransactions open in one transaction. ## Finding it in production - Look for `SubtransSLRU` or `SubtransBuffer` waits across many sessions at once in `pg_stat_activity`. - Watch `pg_stat_slru` where `name = 'subtransaction'` for a rising `blks_read`. - Search the code for per-row savepoints: retry helpers, `EXCEPTION` blocks inside loops, and driver settings that set a savepoint before every statement. - Check `pg_stat_activity.xact_start` for the import sessions: the overflow lasts exactly as long as their top-level transactions, so a long single-transaction import keeps the whole cluster in the slow path for its full duration. ## Why the limit is not a setting The 64 is a compile-time constant, not a configuration parameter; the source comment itself calls it a guessed-at value. The array is part of each backend's shared-memory slot, and a session building a snapshot copies the cached subxids while holding the process-array lock. A larger array would make snapshots costlier to build for every workload, including those that never use savepoints. PostgreSQL instead keeps the common case cheap and makes the rare case, a transaction with many live subtransactions, pay through `pg_subtrans`. The design expects applications to keep the number of writing subtransactions per transaction small.

  • Does a PostgreSQL PL/pgSQL loop whose body has a BEGIN ... EXCEPTION block hit the same 64-subxid limit?
    Yes. Each entry into a block with an `EXCEPTION` clause starts a subtransaction, and if the block writes it gets a subxid. A normal exit sub-commits it, so the subxid stays cached like a released savepoint. A loop of 1,000 inserts with such a block overflows the cache after 64 iterations; move the error handling outside the loop or validate first. The block syntax itself is a PL/pgSQL topic.
  • Would raising subtransaction_buffers in PostgreSQL 18 alone fix the import?
    It helps but does not fix it. A bigger `pg_subtrans` cache means fewer reads from disk and somewhat less contention, yet snapshots are still marked overflowed and every in-range XID check still goes through `pg_subtrans`. It also needs a restart. Removing the per-line savepoints, or committing before 64 accumulate, removes the cause.

  • RELEASE SAVEPOINT frees the subtransaction's slot, so release-per-line is safe.
  • Only the session that uses many savepoints slows down; others are unaffected.
  • Read-only savepoints also consume one of the 64 cached slots.
  • Raising subtransaction_buffers removes the overflow, so the code can stay as it is.
  • Savepoints are free in PostgreSQL because they only mark a position in the transaction.

Assumes PostgreSQL 18; subtransaction_buffers and transaction_buffers exist since 17 (before that the cache sizes were fixed), COPY ON_ERROR since 17 and REJECT_LIMIT since 18.