Video in progress

Why can PostgreSQL slow down when a transaction uses many `SAVEPOINT`s (subtransactions)?

Each savepoint gets a subtransaction ID. If one backend has more than 64 open subtransactions, the snapshot can't hold them and other sessions have to check visibility through pg_subtrans. On replicas and with long transactions, this leads to a sharp slowdown.

📖 Answer

Savepoints are often invisible: every EXCEPTION block in PL/pgSQL, Propagation.NESTED in Spring, autosave=always in PgJDBC all open a savepoint under the hood.

For example, in import code:

for (Row r : rows) {             // 10,000 rows, one transaction
    Savepoint sp = con.setSavepoint();
    try {
        insert(r);
    } catch (SQLException e) {
        con.rollback(sp);
    }
}

Where the problem comes from:

  • each backend keeps its subtransactions in a cache of 64 slots in process memory;
  • when it overflows, that's an "overflow". Now other sessions go to the pg_subtrans SLRU to determine the visibility of this transaction's rows;
  • the SLRU is small and protected by locks: under load the SubtransSLRU/SubtransBuffer wait events pile up and the CPU burns.

On a replica it's even worse: even if there's no long transaction there, an overflow on the primary can slow down all the readers.

What I do:

  • put the savepoint around a batch, not around each row, or get rid of the error itself with ON CONFLICT DO NOTHING;
  • I don't turn on autosave=always;
  • if I see Subtrans in wait_event in pg_stat_activity, I look for savepoints first. PG17 added the ability to tune the SLRU cache sizes, but that's not a cure.