FULL AI ANALYSIS

Autovacuum stalls and partition bloat due to lingering prepared transactions holding old snapshots in PostgreSQL 13

Generated Oct 24, 2026, 9:21:01 AM

Analysis summary

Prepared transactions (two-phase commit) retain the transaction snapshot until COMMIT PREPARED or ROLLBACK PREPARED is executed. Abandoned prepared transactions hold back the oldestxmin so autovacuum cannot remove tuples created before that snapshot, causing bloat. Restarting the server does not remove prepared transactions; they persist across restarts. Fixes include identifying and explicitly rolling back abandoned prepared transactions, modifying application behavior to avoid leaving prepared transactions open, and adding server-side timeouts or monitoring.

Possible causes

Application leaves PREPARE TRANSACTION requests uncommitted (crash or bug), leaving persistent prepared transactions that block VACUUM

90%

Misconfigured or missing failover cleanup that should ROLLBACK PREPARED on aborted participants

40%

Logical replication or long-running replica slots referencing old snapshots (less likely than prepared txns)

30%

Suggested fixes

1

Diagnostic step 1

List prepared transactions: SELECT * FROM pg_prepared_xacts; note gid, prepared timestamp and owner.

2

Diagnostic step 2

If you can verify a prepared transaction is abandoned, run ROLLBACK PREPARED 'gid' on the primary to remove it; do this for one transaction at a time and monitor relfrozenxid/pg_stat_all_tables.

3

Diagnostic step 3

If multiple abandoned prepared txns exist, coordinate with application owners before ROLLBACK PREPARED. For emergency cleanup, ROLLBACK PREPARED is safe for abandoned work but will lose prepared updates.

4

Diagnostic step 4

Prevent recurrence: add application safeguards (ensure COMMIT/ROLLBACK PREPARED on failures), consider enabling idle_in_transaction_session_timeout for normal txns, and add monitoring/alerting for pg_prepared_xacts count.

5

Diagnostic step 5

Longer-term: avoid two-phase commits unless necessary; use idempotent design or outbox patterns for cross-service transactions.