PostgreSQL SubtransSLRU Cliffs from Nested Savepoints
Everything looks calm at 25% CPU until one batch worker opens 65+ savepoints alongside a long transaction and freezes every reader on SubtransSLRU. Here is the exact PGPROC mechanism, how to spot it in pg_stat_activity, and how to fix the application loop.
One of the nastiest outages on Amazon RDS for PostgreSQL or Aurora PostgreSQL starts without a slow query deploy or a traffic spike. Average CPU sits at 25% all week, then jumps to 98% in thirty seconds while thousands of fast primary-key and index lookups stall on LWLock:SubtransSLRU (or SubtransControlLock on older versions).
Killing the slowest SELECT queries does nothing, because those SELECT queries are victims.
Why 65 savepoints change how every reader checks MVCC visibility
Every SAVEPOINT (and every BEGIN ... EXCEPTION WHEN ... END block in PL/pgSQL) allocates a child transaction ID (subxid) when it modifies state. To keep MVCC snapshot checks fast, PostgreSQL stores up to 64 subtransaction XIDs directly inside each backend’s PGPROC structure in shared memory (PGPROC_MAX_CACHED_SUBXIDS).
As long as every active session stays at or below 64 subtransactions, XidInMVCCSnapshot() scans those small in-memory arrays without touching pg_subtrans pages.
The cliff arrives when two conditions overlap:
- At least one backend overflows 64 subtransactions inside a single parent transaction (setting
subxids.overflowed = trueinProcArray). - A long-running transaction or hot-standby feedback pin holds the global
xminhorizon back (for example, an analytics export, anidle in transactionsession, orhot_standby_feedback = onwith a slow replica query).
Once ProcArray contains an overflowed snapshot and TransactionIdPrecedes(xid, TransactionXmin) is false for newly written tuples, every concurrent reader inspecting those tuples has to look up their top-level parent XID in pg_subtrans SLRU buffers. Under 200 concurrent connections, cache lines bounce across cores and SLRU page replacements serialize readers behind SubtransSLRU.
Catching both halves of the incident in SQL
During a live stall on PostgreSQL or AWS RDS, run one read-only diagnostic query against pg_stat_activity to separate the wait victims from the horizon pin and savepoint writer:
/* culprit */
SELECT pid,
usename,
application_name,
state,
wait_event_type,
wait_event,
age(backend_xmin) AS xmin_age_xids,
now() - xact_start AS xact_age,
left(query, 120) AS current_sql
FROM pg_stat_activity
WHERE pid <> pg_backend_pid()
AND (xact_start IS NOT NULL OR wait_event IS NOT NULL)
ORDER BY coalesce(age(backend_xmin), age(backend_xid), 0) DESC,
xact_start ASC NULLS LAST
LIMIT 25;
Look at two distinct rows in that output:
- The horizon holder sits at the top with a large
xact_ageorxmin_age_xids(oftenstate = 'idle in transaction'or a 20-minute reportingSELECT). - The victim herd sits stacked on
wait_event_type = 'LWLock'andwait_event IN ('SubtransSLRU', 'SubtransBuffer', 'SubtransControlLock', 'MultiXactOffsetSLRU').
Here is what that degradation looks like in EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) on public.payment_attempts before and after removing the savepoint loop and clearing the pinned horizon:
Click into the Index Only Scan node above: the plan shape looks identical at first glance, yet Before executes 38,400 Heap Fetches (38,400 buffer reads, 384.8 ms), while After completes in 1.84 ms with Heap Fetches: 0 and 8 shared buffer hits.
Three code patterns that silently mint thousands of savepoints
Developers almost never write raw SAVEPOINT sp_42 in application code. Savepoint storms come from ORM helpers nested inside loops:
- Django
with transaction.atomic():inside aforloop when an outer request or Celery task already openedatomic(). The outer block startsBEGIN; every inner iteration emitsSAVEPOINTandRELEASE SAVEPOINT. - ActiveRecord
Model.transaction(requires_new: true)or Sequeldb.transaction(savepoint: true)called per imported CSV row to catchRecordNotUnique. - PL/pgSQL
BEGIN ... EXCEPTION WHEN unique_violation THEN ... END;inside aFORloop over thousands of items. Every entry into anEXCEPTIONblock allocates a subtransaction.
Fixing the writer and capping the blast radius
Replace exception-driven savepoint loops with single-statement conflict handling:
-- Zero savepoints, zero subxids, one round-trip for 1,000 rows:
INSERT INTO public.payment_attempts (merchant_id, idempotency_key, amount_cents, state)
SELECT * FROM unnest($1::bigint[], $2::text[], $3::bigint[], $4::text[])
ON CONFLICT (merchant_id, idempotency_key)
DO UPDATE SET state = EXCLUDED.state,
updated_at = now()
WHERE public.payment_attempts.state <> 'settled';
Then enforce two server-level guardrails (via RDS Parameter Group or ALTER DATABASE) so one forgotten transaction cannot pin the MVCC horizon for twenty minutes:
ALTER DATABASE payments SET idle_in_transaction_session_timeout = '30s';
ALTER DATABASE payments SET statement_timeout = '60s'; -- override per reporting role if needed
In Culprit SQL Studio and Culprit Fleet, SubtransSLRU wait spikes, idle in transaction horizon pins, and Index Only Scan heap-fetch regressions correlate into one finding rather than paging on generic CPU. Pair this with lock-safe PostgreSQL migration gates in CI so DDL locks never start a second queue on the same hot table.
Frequently asked questions
Why is 64 subtransactions the magic cliff in PostgreSQL?
Each backend's PGPROC shared-memory struct caches up to 64 subtransaction XIDs inline (PGPROC_MAX_CACHED_SUBXIDS = 64). Once any active transaction exceeds 64 open or committed subtransactions, its PGPROC entry is marked overflowed, forcing concurrent backends checking MVCC tuple visibility to resolve parent XIDs through the shared pg_subtrans SLRU pages and SubtransControlLock.
Do ordinary SELECT queries generate subtransactions?
No, plain SELECT statements do not allocate XIDs or subtransactions. However, SELECT queries pay the penalty: whenever an Index Scan or Seq Scan visits a recently modified heap tuple whose xmin belongs to an overflowed backend within the active snapshot horizon, the reader must walk pg_subtrans under lightweight locks to check visibility.
A metadata-only ALTER TABLE takes 12 milliseconds on staging and still takes down production when it queues behind one 8-second query. Here is how PostgreSQL lock queues form and how to block unsafe DDL in GitHub Actions.