1.Multi-Version Concurrency Control
MVCC is the mechanism that lets PostgreSQL give every statement a consistent snapshot of the database without locking readers against writers — instead of one shared copy of each row that everyone fights over, PostgreSQL keeps multiple versions of a row around, and each transaction sees exactly the version(s) that existed as of its own snapshot.
Key features
- Each SQL statement sees a snapshot of the database as it existed at some point, regardless of what has changed since
- Locks acquired for reading do not conflict with locks acquired for writing — reading never blocks writing, and writing never blocks reading
- This works because a writer creates a new row version rather than overwriting the old one in place — a concurrent reader can keep using the old version undisturbed
- A transaction snapshot determines which row versions are visible to that transaction for its whole duration (Repeatable Read/Serializable) or per-statement (Read Committed)
- PostgreSQL achieves even its strictest isolation level (Serializable) through MVCC-based mechanisms (Serializable Snapshot Isolation) rather than falling back to heavy locking
MVCC vs a naive single-copy-per-row model
- Row version 1 — existed before the UPDATE
- leads to Reader (old snapshot) (still visible to this snapshot)
- leads to Row version 2 (UPDATE creates a new version, does not overwrite)
- Reader (old snapshot) — keeps seeing version 1
- Row version 2 — created by a concurrent UPDATE
Command
-- MVCC in one sentence, demonstrated:
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1; -- snapshot taken here
-- (a concurrent transaction commits an UPDATE to this row)
SELECT balance FROM accounts WHERE id = 1; -- still sees the OLD version -- no lock, no block
COMMIT;MVCC gives every statement a consistent snapshot without locking readers against writers, by having a writer create a new row version instead of overwriting the old one in place — reading never blocks writing and writing never blocks reading. It does NOT mean writer-vs-writer conflicts on the same row stop existing; those still block as usual.