Transactions from the inside: WAL, MVCC and the undo log
Replaying all four isolation levels on MySQL 8.4 and PostgreSQL 16, how a write travels through the redo log, InnoDB's MVCC (undo log, read view, purge, and history list length measured in numbers) versus PostgreSQL's (xmin/xmax, dead tuples, VACUUM).
On this page
This post goes below isolation levels: what the database does to keep a transaction's promises, and why one transaction left open too long slows down the whole system. Afterwards you can explain redo, undo and MVCC, and measure the cost of an old snapshot. Read the post on transactions, isolation levels and locking first.
1. The problem
A reporting job opens a transaction, reads one row, then waits 40 minutes on an external API. Meanwhile table hot takes 20,000 UPDATEs. A primary-key read goes from 0.43 ms to 26.8 ms, and the history list length from 46 to 20,001, though nobody changed a query.
2. Key idea
The table is the document's current page; the undo log is its edit history. While someone is still reading an old version, nobody may delete that history.
WAL (write-ahead logging): a commit only needs a sequential append to the redo log plus an fsync; 16 KB data pages reach disk later. After a crash: replay the redo, then use undo to roll back uncommitted transactions.
In REPEATABLE READ the read view is created at the first read; in READ COMMITTED, at each statement. FOR UPDATE, UPDATE and DELETE are current reads: they skip the read view and read the latest committed version, with a lock.
Anything you will write back must come from a current read, or the condition must live inside the UPDATE itself.
2.1 Where does reality differ from theory?
| Difference | MySQL 8.4 (InnoDB) | PostgreSQL 16 |
|---|---|---|
| Lost update at RR | not prevented: +50 lost | error could not serialize access |
| SERIALIZABLE | reads become locks, prone to deadlock | SSI: one side is aborted (40001) |
Both require retrying the whole transaction. Correct money comes from atomic UPDATEs, row locks or versions, not from isolation levels.
2.2 Undo log or versions in the table?
| InnoDB (undo log) | PostgreSQL (tuples in the table) | |
|---|---|---|
| Table | only the latest version | table and indexes bloat, need VACUUM |
| Large rollback | very expensive: killing a 1-hour transaction can take about as long | nearly instant |
3. In Java
Find the long-open transactions that block purge and VACUUM across every table:
// MySQL: HLL and the oldest transaction
String hll = """
SELECT count FROM information_schema.innodb_metrics
WHERE name = 'trx_rseg_history_len'"""; // 20001 while A is open, 0 after commit
String oldestMy = """
SELECT trx_id, trx_started, TIMESTAMPDIFF(SECOND, trx_started, NOW()) AS age_s
FROM information_schema.innodb_trx ORDER BY trx_started LIMIT 1""";
// PostgreSQL: who holds an old snapshot
String oldestPg = """
SELECT pid, state, now() - xact_start AS xact_age, backend_xmin
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL AND pid <> pg_backend_pid()
ORDER BY xact_start LIMIT 1""";
// VACUUM VERBOSE at that moment: "5000 are dead but not yet removable"In Spring: no HTTP calls inside @Transactional; long reading jobs use short per-batch transactions.
Inside InnoDB: hidden columns, checkpoints, doublewrite
- Each row has hidden columns
DB_TRX_ID(the last modifying transaction) andDB_ROLL_PTR(pointing at an undo record). An undo record is a recipe for going back to the previous version, like Ctrl+Z, not a full row. - A read view sees a version if its
DB_TRX_IDcommitted before the read view was created; otherwise it walks to an older one. Purge removes undo records once no read view needs them. - Checkpoints flush dirty pages gradually; after a crash InnoDB replays redo from the last checkpoint. The doublewrite buffer guards against torn pages from power loss mid-write; PostgreSQL uses
full_page_writes. - Group commit: many transactions committing together share one fsync.
4. Working with AI
Give the AI: a script driving two interleaved connections to reproduce anomalies, a dashboard for HLL and transaction age.
Check in AI-written code:
- No "read, compute in the app, write back" relying on RR to prevent lost updates.
- SERIALIZABLE code retries the whole transaction on deadlocks or
40001. - Values written back are read with
FOR UPDATEor sit in theUPDATE'sWHERE.
5. Exercises
Exercise 1: Two reads, two values
In an RR transaction on MySQL, the AI writes: SELECT balance (100), a 2-second exchange-rate API call, SELECT balance FOR UPDATE (150), then UPDATE ... SET balance = 100 + 10. The AI says "RR guarantees repeatable reads, so it's fine". What's wrong?
Solution to Exercise 1
The plain SELECT reads through the read view (the version at the first read); FOR UPDATE is a current read and sees the latest committed version (150, after another transaction added 50). The code computes from 100 and overwrites with 110: +50 lost, exactly the lost update InnoDB's RR doesn't prevent.
Fix: read with FOR UPDATE from the start, or UPDATE ... SET balance = balance + 10. Call the exchange-rate API before opening the transaction so no lock is held for 2 seconds.
Exercise 2: Alerting on HLL
When should you alert on history list length, and which alert fires first?
Solution to Exercise 2
Collect trx_rseg_history_len every 15 seconds (mysqld_exporter has it). Two alerts:
- HLL several times above its normal baseline for 10 minutes straight.
- The oldest transaction in
innodb_trxolder than a threshold (e.g. 5 minutes).
Alert 2 usually fires first and points straight at the culprit. Alert 1 also catches many medium-length transactions piling up.
Summary
- The redo log handles durability; the undo log handles atomicity and old versions for MVCC.
- In RR the read view starts at the first read;
FOR UPDATEreads the latest version. - InnoDB's RR doesn't stop lost updates; PostgreSQL raises an error to retry.
- InnoDB keeps old versions in the undo log, PostgreSQL in the table (needs VACUUM).
- A long-open transaction, even read-only, slows the whole database.
Read more: Harmful transactions and how to find them.
Practice interview questions on this topic
- How does MVCC work in InnoDB and PostgreSQL, and when is a read view created?
- What is ACID? How does a database guarantee atomicity and durability?
- What are lost updates and write skew? Which isolation level prevents them, and how should apps retry?
- Why are long transactions harmful? How do "idle in transaction" and autocommit relate?
Comments
Community rules