Interview Prep/Real-World Interview/Data loss and corruption

Postgres stops accepting writes with "ERROR: database is not accepting commands to avoid wraparound data loss in database "app"".

AdvancedTroubleshootingData loss and corruption
Answer

Likely causes → Transaction ID wraparound protection. Postgres uses 32-bit transaction IDs and needs VACUUM to freeze old rows. Autovacuum fell behind (blocked by a long-running transaction, an abandoned replication slot or prepared transaction, or throttled too much on a huge table) until the database was close to the limit.

Diagnose →

SELECT datname, age(datfrozenxid) FROM pg_database ORDER BY 2 DESC;
SELECT relname, age(relfrozenxid) FROM pg_class WHERE relkind='r' ORDER BY 2 DESC LIMIT 10;
SELECT pid, xact_start, state FROM pg_stat_activity WHERE backend_xid IS NOT NULL OR backend_xmin IS NOT NULL ORDER BY xact_start;
SELECT * FROM pg_prepared_xacts;

Fix → Remove whatever holds back the xmin (end old transactions, drop stale slots, roll back orphaned prepared transactions), then run VACUUM (FREEZE, VERBOSE) on the oldest tables. Recent Postgres versions allow this in normal mode; older ones need single-user mode. It can take hours on big tables.

Prevent → Alert when age(datfrozenxid) passes 500 million, tune autovacuum for large tables (autovacuum_vacuum_cost_limit, per-table settings), and kill idle-in-transaction sessions with idle_in_transaction_session_timeout.

All Real-World Interview questions Roadmap: Interview readiness

More on Data loss and corruption