Sub topic 12
MVCC: readers that do not block writers
This chapter assumes you know the basic transaction commands (BEGIN, COMMIT, ROLLBACK), the idea of isolation levels, and the anomalies they prevent. It uses PostgreSQL for concrete behavior. Other engines differ in details, and the chapter says so where it matters.
The problem MVCC solves
A simple lock-based database makes readers and writers take turns. A reader takes a shared lock on a row, and a writer needs an exclusive lock on the same row. While a long report reads a table, updates to that table wait. While an update is in progress, reads wait. Throughput drops as concurrency rises.
Multiversion concurrency control (MVCC) removes most of this waiting. The database keeps more than one version of a row. A reader looks at an older, committed version while a writer builds a new one. The reader does not need a lock on the row, and the writer does not wait for the reader.
The rule to remember is: readers do not block writers, and writers do not block readers. Writers still block other writers that touch the same row.
How versions work
Each time a row is updated, the database does not overwrite it. It creates a new version of the row and marks the old one as replaced. Each version records which transaction created it and which transaction, if any, removed or replaced it.
PostgreSQL stores these as two hidden system columns, xmin and xmax. You can select them:
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric(12,2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, balance) VALUES (1, 100.00);
SELECT xmin, xmax, id, balance FROM accounts WHERE id = 1;
-- xmin = the transaction that created this version
-- xmax = 0 while no transaction has deleted or replaced it
UPDATE accounts SET balance = 70.00 WHERE id = 1;
SELECT xmin, xmax, id, balance FROM accounts WHERE id = 1;
-- xmin now shows the updating transaction's IDAfter the update, the table physically holds two versions of row 1. The old one has xmax set to the updating transaction. The new one has that transaction as its xmin. Only one of them is visible to any given reader.
Snapshots and visibility
A reader decides which version to see by using a snapshot. A snapshot records which transactions had committed at a particular moment. A row version is visible to a snapshot when both conditions hold:
- The transaction that created it (
xmin) had committed before the snapshot was taken, or is the reader's own transaction. - The version has not been removed or replaced by a transaction that committed before the snapshot (
xmaxis unset, belongs to an aborted transaction, or belongs to a transaction that was still running or had not started when the snapshot was taken).
Changes from transactions that were in progress, or that committed later, are invisible. This is why a reader never sees uncommitted data, and why it needs no lock to avoid dirty reads.
The isolation level controls when the snapshot is taken:
| Isolation level | Snapshot taken | Effect |
|---|---|---|
| READ COMMITTED | At the start of each statement | Each statement sees the latest committed data. Two identical queries in one transaction can differ. |
| REPEATABLE READ | At the first statement of the transaction | Every query sees the same data for the whole transaction. |
| SERIALIZABLE | Same as REPEATABLE READ, plus conflict tracking | Same stable view, and the database aborts transactions whose combined effect could not occur in any serial order. |
This is the mechanism behind the earlier example in which Session A reads 70.00, Session B updates the row and commits, and Session A then reads again. Under READ COMMITTED the second statement takes a new snapshot and sees 0.00. Under REPEATABLE READ it keeps the old snapshot and still sees 70.00.
What MVCC does not remove
MVCC removes read-write blocking. It does not remove write-write conflicts. If two transactions update the same row, the second one must wait for the first to finish. The outcome depends on the isolation level.
- Under READ COMMITTED, if the first transaction commits, the second one re-reads the newest version of the row, re-checks its
WHEREcondition, and applies its update on top. - Under REPEATABLE READ and SERIALIZABLE, if the first transaction commits, the second one fails with SQLSTATE
40001(serialization_failure). Its snapshot is older than the committed change, so applying the update would overwrite a change it never saw. The application must retry. - If the first transaction rolls back, the second one proceeds in every case.
This is how REPEATABLE READ in PostgreSQL prevents lost updates, while READ COMMITTED does not for read-then-write patterns done in application code.
Snapshot isolation also allows write skew, because two transactions that update different rows never conflict on a row. The on-call doctors example earlier showed this. Only SERIALIZABLE, which tracks read-write dependencies between transactions, catches it.
Explicit row locks still exist alongside MVCC. SELECT ... FOR UPDATE reads the latest committed version and locks it, so it is the tool for a read-then-write sequence at READ COMMITTED.
The cost: dead versions and vacuum
Keeping old versions has a price. After the update above, the table contains a version nobody will ever need once all older snapshots have finished. These are called dead tuples. They take disk space and slow scans.
PostgreSQL reclaims them with VACUUM, which autovacuum runs in the background. A dead version can be removed only when no running transaction could still see it. You can check dead-row counts:
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'accounts';This leads to the most common MVCC operational problem: a long-running transaction holds back cleanup. While it is open, its snapshot may still need old versions, so vacuum cannot remove anything newer than the oldest snapshot. Tables bloat, even when the long transaction only reads. A forgotten BEGIN in an interactive session, or an application that leaves connections "idle in transaction", has the same effect. You can find them:
SELECT pid, state, xact_start, now() - xact_start AS age, query
FROM pg_stat_activity
WHERE state <> 'idle' AND xact_start IS NOT NULL
ORDER BY xact_start
LIMIT 5;Differences between engines
MVCC is a family of designs, not one implementation.
| Aspect | PostgreSQL | MySQL InnoDB and Oracle |
|---|---|---|
| Where old versions live | In the table itself, next to current rows | In a separate undo log or undo segment |
| Cleanup | VACUUM removes dead tuples | Old undo records are purged when no snapshot needs them |
| Updates | Always write a new row version | Update in place and write an undo record |
| Long readers | Cause table bloat | Cause a growing undo area, and in Oracle can raise "snapshot too old" |
The visible behavior (readers do not block writers) is the same. The operational costs differ. Also, InnoDB's default level is REPEATABLE READ, and its plain SELECT reads from a snapshot while SELECT ... FOR UPDATE reads the latest committed data. Check your engine's documentation before assuming PostgreSQL's isolation guarantees.
Common errors
- Assuming a snapshot read is the current value. A value read at REPEATABLE READ may be out of date by the time you act on it. If a decision depends on it staying true, lock the row or use SERIALIZABLE.
- Not retrying
40001. At REPEATABLE READ and SERIALIZABLE, serialization failures are normal. Wrap the whole transaction in a retry loop. - Long transactions. Open transactions, even read-only ones, delay vacuum. Keep them short and close them promptly.
- Treating
count(*)as free. Because visibility is per snapshot, the database must check each row version, so exact counts require scanning.
Summary of the working model
- Every update creates a new row version and leaves the old one in place.
- A snapshot decides which versions a statement or transaction can see.
- Readers use snapshots, so they never wait for writers.
- Writers to the same row still queue, and may fail with a serialization error at stricter levels.
- Old versions accumulate until vacuum or purge removes them, which a long transaction can delay.
Exercise
Session A runs BEGIN ISOLATION LEVEL REPEATABLE READ and reads row 1 (balance 70.00). Session B then updates row 1 to 0.00 and commits. Session A, still in its transaction, runs UPDATE accounts SET balance = balance - 20 WHERE id = 1. What happens in PostgreSQL, and why? What would happen if Session A were at READ COMMITTED instead?
Show answer
At REPEATABLE READ, the UPDATE fails with SQLSTATE 40001 (serialization_failure), because row 1 was changed by a transaction that committed after Session A's snapshot was taken. Session A must roll back and retry the whole transaction. At READ COMMITTED, the UPDATE re-reads the newest committed version (0.00), re-checks the WHERE clause, and applies the subtraction. That makes the balance -20, which the CHECK constraint rejects, so the statement fails with a constraint violation instead.
Exercise
A table's dead-tuple count keeps growing even though autovacuum is running. A monitoring query shows one session has been "idle in transaction" for six hours. Explain the connection.
Show answer
That session holds a snapshot (or at least an open transaction ID) from six hours ago. Vacuum can only remove a dead row version when no running transaction could still need it, so versions replaced after that snapshot cannot be reclaimed. The fix is to end the transaction (commit or roll back), and to prevent recurrence with application changes or a setting such as idleintransactionsessiontimeout.