Sub topic 9
How databases implement isolation: locks and MVCC
Earlier chapters described what each isolation level promises. This chapter covers how a database keeps those promises. There are two mechanisms: locks and multiversion concurrency control (MVCC). Most engines combine them. This chapter assumes you know the anomalies (dirty read, non-repeatable read, phantom, lost update), basic BEGIN/COMMIT/ROLLBACK, and the idea of a primary key.
Two ways to keep transactions apart
A database can protect a row from interference in two ways:
- Make other transactions wait until the row is safe to touch. This is locking.
- Keep several versions of the row, and give each transaction the version it is allowed to see. This is MVCC.
Locking trades waiting for consistency. MVCC trades storage and cleanup work for less waiting. Neither is free, and the cost shows up in different places.
Lock-based isolation
Shared and exclusive locks
A lock-based engine uses two basic lock modes:
- A shared lock (S) is taken to read. Many transactions can hold S on the same row at once.
- An exclusive lock (X) is taken to write. Only one transaction can hold it, and it conflicts with every other lock on that row.
| Held by another transaction | I request S | I request X |
|---|---|---|
| Nothing | granted | granted |
| S | granted | wait |
| X | wait | wait |
Two-phase locking
Taking locks is not enough on its own. If a transaction releases a lock right after using it, another transaction can change the row before the first one finishes, and anomalies come back. Two-phase locking (2PL) prevents this with a rule. A transaction has a growing phase, where it only acquires locks, and a shrinking phase, where it only releases them. In the common variant, strict 2PL, a transaction holds all its write locks until COMMIT or ROLLBACK. That one rule is what rules out dirty reads. Nobody can read a row another transaction has changed and not yet committed, because the writer still holds X.
The isolation levels map onto how long read locks are held:
| Level | Write locks | Read locks |
|---|---|---|
| READ UNCOMMITTED | held to end of transaction | none |
| READ COMMITTED | held to end of transaction | released right after each read |
| REPEATABLE READ | held to end of transaction | held to end of transaction |
| SERIALIZABLE | held to end of transaction | held to end of transaction, plus locks on ranges |
Holding read locks to the end prevents non-repeatable reads, because nobody can write a row you have read. It does not stop phantoms. A phantom is a new row that matches your WHERE clause, and you hold no lock on a row that does not exist yet. To stop phantoms, SERIALIZABLE needs predicate locks or range locks. These cover the set of rows a condition describes, such as age BETWEEN 20 AND 30, and not only the rows that exist now. InnoDB's gap locks and next-key locks are range locks of this kind. SQL Server uses key-range locks at SERIALIZABLE.
What locking costs
Locking has two main costs.
- Blocking. A reader waits for a writer, and a writer waits for readers. Under strict 2PL at higher levels, one slow transaction can stall many others.
- Deadlocks. Transaction A holds a lock on row 1 and wants row 2, while transaction B holds row 2 and wants row 1. Neither can proceed. The engine detects the cycle and aborts one transaction as the victim. A later chapter covers retrying after that.
MVCC: readers do not block writers
With MVCC, an UPDATE does not overwrite a row in place from the readers' point of view. It creates a new version of the row and marks the old one as replaced. Each transaction reads the versions that were current at a certain moment, so a reader never needs a lock to avoid seeing half-finished work.
Snapshots and visibility
Every transaction gets a snapshot, which is a description of which other transactions count as committed from its point of view. A row version is visible if the transaction that created it is committed in the snapshot, and the transaction that replaced or deleted it (if any) is not.
The isolation level decides when the snapshot is taken:
- At READ COMMITTED, a new snapshot is taken for each statement. Each query sees the latest committed data, so two queries in one transaction can disagree.
- At REPEATABLE READ (snapshot isolation in PostgreSQL), one snapshot is taken for the whole transaction, so every query sees the same data.
This is why the READ COMMITTED example earlier showed 100 and then 50, and the REPEATABLE READ one showed 100 twice.
Seeing versions in PostgreSQL
PostgreSQL stores every version as a separate row ("tuple") in the table itself. Two hidden columns record who created and who replaced it: xmin (the creating transaction ID) and xmax (the transaction that deleted or locked it, or 0). You can query them directly.
CREATE TABLE accounts (id int PRIMARY KEY, balance int);
INSERT INTO accounts VALUES (1, 100);
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT xmin, xmax, balance FROM accounts WHERE id = 1;
-- Session B
BEGIN;
SELECT pg_current_xact_id();
UPDATE accounts SET balance = 50 WHERE id = 1;
SELECT xmin, xmax, balance FROM accounts WHERE id = 1;
COMMIT;
-- Session A, still in its transaction
SELECT xmin, xmax, balance FROM accounts WHERE id = 1;
COMMIT;Session B's own query returns balance 50 with a new xmin equal to its transaction ID. Session A's second query still returns balance 100 with the original xmin. The old version is still in the table, and A's snapshot says it is the visible one. Exact ID numbers will differ on your system.
InnoDB (MySQL) does it differently. It updates the row in place and writes the previous contents to an undo log. When a consistent read needs an older version, InnoDB rebuilds it by following the undo records back from the current row. The visible result is the same, but the cost lands in a different place: PostgreSQL keeps old versions in the table, and InnoDB keeps them in undo storage.
What MVCC costs
- Cleanup. Old versions that no transaction can see any more must be removed. PostgreSQL does this with
VACUUM(and autovacuum). InnoDB purges undo records in a background thread. - Bloat from long transactions. An old snapshot keeps old versions alive. A transaction left open for hours, even an idle one, stops cleanup from reclaiming anything newer than its snapshot. Tables and indexes grow, and queries slow down.
- Writers still conflict. MVCC removes reader-writer blocking. Two transactions that update the same row still cannot both succeed.
Writers under MVCC
When transaction B tries to update a row that transaction A has changed but not yet committed, B waits for A. This is a row-level write lock, and MVCC engines still use it. What happens when A commits depends on the level:
- At READ COMMITTED, B re-reads the newest committed version of the row and carries on with it.
- At REPEATABLE READ in PostgreSQL, B's snapshot is older than A's change. B fails with
ERROR: could not serialize access due to concurrent update(SQLSTATE 40001). The application must retry the transaction.
Locking reads let you take these row locks explicitly when you need them:
BEGIN;
-- Exclusive row lock: others cannot update, delete, or lock this row until we finish
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
COMMIT;FOR SHARE takes a weaker lock that blocks writers but allows other FOR SHARE readers. In PostgreSQL, a plain SELECT never takes row locks. This is the main practical difference from lock-based read levels.
Putting the two together
| Row | Lock-based | MVCC |
|---|---|---|
| Reader blocks writer | yes, while the read lock is held | no |
| Writer blocks reader | yes | no |
| Writer blocks writer | yes | yes |
| Extra storage | none | old row versions or undo log |
| Background work | none | `VACUUM` or purge |
| Typical failure | blocking and deadlocks | serialization failures, bloat |
| Read sees | latest data, after waiting | a snapshot, possibly stale |
Common mistakes
- Assuming reads never wait under MVCC. Plain reads do not wait on row writers, but they can wait on a table-level lock such as the one
ALTER TABLEtakes. - Leaving transactions open. An application that runs
BEGINand then waits for user input holds its snapshot, and its locks, the whole time. In PostgreSQL, look for sessions in theidle in transactionstate inpg_stat_activity. - Expecting REPEATABLE READ to mean the same thing everywhere. The name is used for snapshot isolation in PostgreSQL and for a hybrid of snapshots and range locks in InnoDB. The engine differences chapter covers this.
- Locking in inconsistent order. If two code paths lock the same rows in different orders, deadlocks follow. Always lock rows in one agreed order, such as ascending primary key.
Exercise
Session A runs BEGIN ISOLATION LEVEL REPEATABLE READ and reads a row in PostgreSQL. Session B then updates that row and commits. Session A now runs UPDATE on the same row. What happens, and why does a plain SELECT in Session A not behave the same way?
Show answer
Session A's UPDATE fails with "could not serialize access due to concurrent update" (SQLSTATE 40001), and A must roll back and retry the whole transaction. A's snapshot is older than B's committed change, so A cannot safely overwrite a version it has never seen. A plain SELECT only reads the version visible to A's snapshot and takes no row lock, so it keeps returning the old value without conflict.
Exercise
Why does holding read locks until the end of a transaction prevent non-repeatable reads but not phantoms, and what extra mechanism does a lock-based engine need at SERIALIZABLE?
Show answer
A read lock only protects rows that exist, so no one can change or delete a row you have read. A phantom is a new row that matches your condition, and you hold no lock on a row that did not exist yet. To stop phantoms, the engine needs predicate locks or range locks (such as InnoDB next-key locks or SQL Server key-range locks) that cover the whole set of rows a condition describes, including future ones.