Multiversion concurrency control (MVCC) is a concurrency control method in which a write creates a new version of a row instead of overwriting it, and each transaction reads the versions that were current as of its snapshot. Because the old version remains in place after it is replaced, a reader can continue to read the version that was current when it started. In the PostgreSQL docs’ phrasing, “reading never blocks writing and writing never blocks reading.”

Most of the behavior of MVCC systems follows from this design. Readers obtain a consistent view without taking locks, while writers still conflict with one another. The default isolation level, snapshot isolation or a weaker one, still permits anomalies that a lock-based serializable system would not. Old versions must eventually be removed, which is possible only once no open transaction can still read them.

PostgreSQL serves as the running example because its versions are visible from SQL. The theory that MVCC implements (anomalies, serializability, the isolation ladder) is in Transactions, Serializability, and Isolation Levels. The claims about PostgreSQL’s behavior were replayed on a PostgreSQL 16 server, and the measurements of the cost of SSI and of garbage come from the same server.

Versions, snapshots and visibility

An MVCC design must determine where old versions are stored, how a reader selects the version it should see, and when an old version can be discarded.

Where versions live. Wu et al. (2017) classify implemented systems into three storage schemes (their table 1):

  • Append-only. Every version is a complete row in the main table. PostgreSQL uses this scheme; an UPDATE writes a whole new row and marks the old one as replaced. Hekaton, MemSQL and NuoDB also use append-only storage.
  • Delta (undo) storage. The table holds only the newest version, updated in place, and older versions are rebuilt from undo records when a reader needs them. Oracle, MySQL’s InnoDB and HyPer work this way.
  • Time-travel. The newest version stays in the table and complete old versions move to a separate area (SAP HANA).

Append-only stores also choose a direction for the chain. In PostgreSQL an index entry points at the oldest version still on the page, and each version’s t_ctid field points forward to its replacement (README.HOT). A lookup for the current row therefore starts at the oldest version and follows the chain forward. The chain extends only while updates remain on the same page; an update whose new version is placed on another page gets an index entry of its own, and a lookup then checks one index entry per version. Delta stores reverse the arrangement. The current row is stored in place, and a reader with an old snapshot incurs the cost of reconstructing earlier versions. Whether the cost of old versions falls on new readers or on old ones is measured under One idle snapshot.

How a reader picks a version. Each version is stamped with the transaction that created it and, once it is replaced, the transaction that replaced it. In PostgreSQL these are the hidden columns xmin and xmax, both transaction ids (xids). A transaction gets an xid only when it first writes (txid_current_if_assigned() returns null until then), which reduces the overhead of read-only transactions.

A snapshot records which transactions count as finished. PostgreSQL’s has three parts (pg_current_snapshot):

  • xmin, the lowest xid that was still running. Everything below it has finished.
  • xmax, one past the highest finished xid. Everything at or above it is treated as running, even after it commits.
  • xip, the xids between the two that were still running.

A version is visible to a snapshot when its creator had committed as of the snapshot and its replacer, if it has one, had not. A transaction also sees its own writes. The rest of the implementation (hint bits, the commit log, the in-progress list) exists to answer that question quickly.

When a version can be removed. A replaced version is garbage once every snapshot that could still see it is gone. PostgreSQL tracks the oldest xmin among open snapshots and running transactions, called the removal horizon. A version whose replacer committed below the horizon is invisible to everyone and can be removed. A single old snapshot holds the horizon back for its whole database, which makes long-lived snapshots a common cause of operational problems with MVCC in production.

Step through it

The figure runs short schedules of two or three transactions through a model of PostgreSQL’s rules: versions stamped with xmin and xmax, snapshots taken the way PostgreSQL takes them, waits on row locks, and serializable snapshot isolation as predicate.c implements it. Each scenario was also replayed step by step on a real PostgreSQL 16 server, along with 80 random schedules, and the model matches the server on every step: the values read, which writes waited, which statements failed and with which error, and the final table. The harness is schedule.py, and the comparison runs as part of the figure’s tests.

1 means on call. Alice (T1) and Bob (T2) each check that two doctors are on call, then take themselves off. The rule: at least one stays on.

Press Next to run the first step, or click any step to run up to it.

Row versions, oldest first

alice
  1. 1xmin 100
    xmax –
    current
bob
  1. 1xmin 100
    xmax –
    current

Removal horizon: xid 101. A version replaced by a committed transaction older than this is invisible to every snapshot.

Transactions

T1 has no snapshot yet: it takes one at its first statement.

T1T2

2 transactions are still open. The arrows show the dependencies so far; an arrow T1 → T2 means T1 must come before T2 in any equivalent serial order.

A model of PostgreSQL's MVCC, checked step by step against PostgreSQL 16 on these schedules and 80 random ones. Click a step to run up to it, or pick a step and move it earlier or later to change the interleaving. Click a transaction to see what its snapshot sees and why. Arrows are dependencies: ww and wr point from the earlier writer, rw from a reader to the transaction that replaced what it read. A cycle (red) means no serial order exists.

Scenarios to step through in the figure:

  • On-call doctors at each level. Read committed and repeatable read both commit, and nobody is left on call. Serializable fails one doctor’s commit.
  • Two increments at read committed: the second writer waits for the first, then writes 1 over the 1 that is already there. At repeatable read the waiting writer fails instead.
  • A long reader holds back cleanup. Step through at repeatable read and watch T1’s snapshot keep two dead versions alive until T1 commits.
  • Three transactions in a chain at serializable: T2 fails. Pick T3’s commit, press Later twice, and run it again: all three commit.

Snapshot isolation

Under snapshot isolation (SI), a transaction reads everything from one snapshot, taken at its first statement, and two concurrent transactions may not both change the same row. The Critique of ANSI SQL Isolation Levels defined SI with a first-committer-wins rule: when two concurrent transactions wrote the same item, whichever commits second aborts. PostgreSQL’s REPEATABLE READ is SI, but it enforces the rule at the write rather than at commit, which is often called first-updater-wins. A transaction that tries to update a row that another running transaction has already updated waits for that transaction to finish. If the other one rolls back, the update goes ahead. If it commits, the waiting transaction fails with could not serialize access due to concurrent update.

A fixed snapshot combined with the prohibition of concurrent writes to one row excludes most of the anomalies in the Critique’s classification. Table 4 of the Critique lists dirty writes and dirty reads (P0, P1), fuzzy reads (P2), lost updates (P4) and read skew (A5A) as impossible under SI. It also rules out the strict form of phantoms (A3), though not every predicate-based variant (P3). What remains possible is write skew (A5B).

In the on-call example (Ports and Grittner 2012, section 2.1.1, based on Cahill et al. 2008; also in Kleppmann, chapter 7), a hospital requires at least one doctor on call. Alice and Bob are both on call and both feel unwell. Each runs a transaction that counts the doctors on call, sees two, and takes themselves off. Alice writes Alice’s row and Bob writes Bob’s row, so no row is written twice and SI detects no conflict. Both commit, and nobody is on call. Each transaction is correct in isolation, and the condition each one checked is invalidated by the row the other one changed.

Fekete, O’Neil and O’Neil (2004) identified a subtler case, in which a transaction that only reads can observe a state that fits no serial order, even when the writers by themselves are serializable. Checking account X and savings account Y both start at 0, and a withdrawal that takes X + Y below zero costs a fee of 1. T2 starts a withdrawal of 10 and reads both balances. T1 deposits 20 into savings and commits. T3, a report, prints X = 0 and Y = 20 and commits. Then T2 writes X = −11, charging the fee because its snapshot showed X + Y = 0. The final state says the withdrawal happened before the deposit, while T3’s report says the deposit happened and the withdrawal hadn’t. No serial order of the three explains both. Without T3 the history is fine: it is equivalent to T2 then T1.

Outcomes on PostgreSQL 16

schedule.py replays each interleaving on a real server, one step at a time, with one connection per transaction. These are the figure’s schedules, and the outcomes are in pg_outcomes.json:

InterleavingRead committedRepeatable read (SI)Serializable (SSI)
Two increments of a counter at 0both commit, counter = 1 (lost update)second writer waits, then failssecond writer waits, then fails
On-call doctors, both write, then both commitboth commit, nobody on callboth commit, nobody on callsecond commit fails
On-call doctors, Alice commits before Bob writesboth commit, nobody on callboth commit, nobody on callBob’s write fails
A transfer read halfway by T1T1 adds up 110 (read skew)T1 adds up 100T1 adds up 100
Fekete’s read-only anomalyall commit, anomalyall commit, anomalythe withdrawal’s write fails
rw chain T1 → T2 → T3, T3 commits firstall commitall commitT2’s commit fails
The same chain, commits in orderall commitall commitall commit

The last two rows are the same three transactions with a different commit order. The first of them is in fact serializable (running T1, T2, T3 in that order reads the same values), and PostgreSQL nevertheless aborts T2. The abort is a false positive of the conservative test described under Making snapshot isolation serializable.

Read committed in an MVCC engine

Read committed takes a new snapshot for every statement instead of one per transaction. That prevents dirty reads, but a transaction can see a transfer halfway through and add up 110, as in the table. Updates are handled differently. When an UPDATE finds that the row it wants is being changed by another transaction, it waits. If the other transaction commits, PostgreSQL re-reads the newest version of the row, checks that it still matches the WHERE clause, and updates that version (docs). Consequently UPDATE t SET v = v + 1 is safe under read committed, whereas a read followed by a write of a value computed in the application is not; the second writer overwrites the first with the same value, and one increment is lost. The remedies are an atomic UPDATE, SELECT ... FOR UPDATE, or a higher isolation level.

Making snapshot isolation serializable

Fekete et al. (2005) proved the result on which SSI is built. In the dependency graph of a history, an edge T → U means that T must precede U in any equivalent serial order. The edges are ww (U overwrote T’s write), wr (U read T’s write) and rw (T read a version that U then replaced). Under SI, every cycle in that graph contains two rw edges in a row, T1 → T2 → T3, where each adjacent pair ran concurrently (T1 and T3 may be the same transaction). The middle transaction read something that a concurrent transaction overwrote and wrote something that a concurrent transaction had read. It is called the pivot.

Write skew is the two-transaction case. Alice → Bob because Alice read Bob’s row before Bob changed it, and Bob → Alice the same way. That is the red cycle in the figure.

Cahill, Röhm and Fekete (2008) derived from the theorem an algorithm, serializable snapshot isolation (SSI). Every transaction runs under SI. SIREAD locks record what each transaction reads; they block no one and are retained after commit until every overlapping transaction has finished. An rw-conflict is flagged whenever a write lands on something a concurrent transaction read, or a read skips a version written by a concurrent transaction. A transaction is aborted when it has both an incoming and an outgoing rw-conflict. The test is conservative. It never admits a cycle, but two consecutive rw edges do not always close a cycle, so it also aborts some transactions whose history would have been serializable.

PostgreSQL has used SSI for SERIALIZABLE since 9.1 (Ports and Grittner 2012). It refines the test in two main ways:

  • Commit order. A dangerous structure T1 → T2 → T3 can only produce an anomaly if T3 commits first (section 3.3.1). The two chain rows in the table show both sides of this rule.
  • Read-only transactions. A read-only transaction can take part in an anomaly only if T3 committed before its snapshot was taken. A SERIALIZABLE READ ONLY DEFERRABLE transaction waits for a snapshot on which no anomaly is possible, then runs with no SSI overhead at all. It is the one case where SERIALIZABLE blocks and REPEATABLE READ doesn’t (docs).

The application has to retry any transaction that fails with SQLSTATE 40001. Ports and Grittner report a cost of less than 7% against SI on their benchmarks: a 5% slowdown on an in-memory DBT-2 variant, and 10 to 20% more CPU on the SIBENCH microbenchmark.

Measured cost of SSI

pgbench.sh runs pgbench’s built-in TPC-B-like workload for 30 seconds with 8 clients at each level, with pgbench retrying a transaction that fails with a serialization error up to 10 times. Each transaction updates one account, one teller and one branch row, and at this scale there are only 10 branches, so concurrent transactions often update the same branch. The tables were rebuilt before every run. Mean ± standard deviation over 3 runs (pgbench.txt):

Transactions per secondRetried at least onceFailed after 10 tries
Read committed7,857 ± 1110%0%
Repeatable read (SI)5,849 ± 16439.1%0.10%
Serializable (SSI)1,364 ± 4186.5%43.2%
Serializable, sequential scans off5,614 ± 3639.2%0.09%

Repeatable read reduces throughput by a quarter relative to read committed, and none of that reduction is due to SSI. It results from first-updater-wins: two transactions that update the same branch row cannot both commit, so 39% of transactions had to run again, whereas read committed updated the newest version.

With default settings, serializable throughput fell to 1,364 transactions per second, because of one step in the query plan. pgbench_branches is so small that the planner updates it with a sequential scan, and a sequential scan takes a predicate lock on the whole table. Every transaction then “read” every branch, so any two that overlapped had rw-conflicts in both directions whichever branches they touched. Turning sequential scans off lets each transaction lock only the branch row it reads, and SSI then reduced throughput 4% below SI, with the same retry rate, within the range Ports and Grittner report. In a first pass that reused the tables from run to run (pgbench_first_pass.txt), serializable runs alternated between the two outcomes, which is why the runs above start from fresh tables.

An in-memory design: HyPer

PostgreSQL’s design dates from disk-based systems. Neumann, Mühlbauer and Kemper (2015) describe an MVCC design built for main memory:

  • Delta storage, newest to oldest. The table holds the newest version in place, and each transaction keeps an undo buffer of before-images. A row’s version chain runs from the current value back through those undo entries.
  • Timestamps instead of snapshots. Start and commit times come from one counter. An uncommitted undo entry carries its writer’s transaction id, and those ids start at 2^63, so the entry looks newer than every reader’s start time and stays invisible to other transactions. Committing restamps the entries with the commit time.
  • No overhead for rows not recently changed. A reader walks a chain only if the row has a version newer than its start time.
  • Optimistic validation instead of SSI. “In contrast to SSI” (section 5.2), HyPer doesn’t track dependencies. Each transaction logs the predicates it read, and at commit it checks them against the before- and after-images of the transactions that committed while it ran, a form of precision locking. If any of those writes would have changed what a predicate matched, the transaction aborts.
write(T, row, value):
    if row has an uncommitted version, or one committed after T.start: abort T
    append (row, current value) to T.undo, stamped T.id     # T.id >= 2^63
    link that entry at the head of row's chain; write value in place
 
read(T, row):
    v = value in place; e = head of row's chain
    while e and e.stamp > T.start and e is not T's own:
        v = e.before_image; e = e.next                     # walk back in time
    return v
 
commit(T):
    check T's read predicates against the undo buffers of the
        transactions that committed after T.start; abort T on a hit
    T.commit = next counter value; restamp T's undo entries with it

On TPC-C, full serializability reduces throughput by around 20% relative to the same engine with single-version concurrency control, to a rate still above 100,000 transactions per second, while two-phase locking gives about a fifth of the throughput (section 4.3). The abstract concludes that with this design “there is little need to prefer SI over full serializability any longer.”

Wu et al. compared these design choices inside one in-memory engine. They found that the version storage scheme matters more for scaling than the concurrency control protocol, contrary to the emphasis of earlier work on the protocol, and that collecting garbage per transaction rather than per row gave the best performance with the smallest memory footprint (section 8).

The cost: garbage

One idle snapshot

bloat.py runs three writer threads that update random rows of a 10,000-row table at 1,500 updates per second, for 210 seconds. In one condition nothing else happens. In the other, a REPEATABLE READ transaction reads one row at the start and then sits idle for 150 seconds before committing, which reproduces the behavior of a forgotten BEGIN in a psql window or of a stalled job. Every 5 seconds a sampler records the table’s size and point-read cost. Mean ± standard deviation over 3 runs of each, read at 145 seconds, just before the idle transaction ends (bloat.txt):

No idle snapshotOne idle snapshot
Table (heap) size1.3 MB29.1 MB
Index size0.23 MB1.74 MB
Dead versions441 ± 24217,072 ± 630
Updates that were HOT99.8%0.9%
Buffers touched by one point read, new session3.024.6 ± 0.3
Server time of that read (median)11 ± 3 µs30 ± 4 µs
Buffers touched by the same read in the idle transaction24.9 ± 0.2
count(*) over the table1.2 ± 0.3 ms9.3 ± 1.9 ms

The idle transaction never touched more than one row, yet the whole table grew about 22 times, by roughly 2 MB every 10 seconds. Without it, each update found the page holding its row, pruned the dead versions there and wrote the new version into the freed space as a heap-only tuple. With the horizon pinned nothing on the page could be pruned, so the new version went to another page, which also needed a new index entry.

The point reads show which readers incur the cost. After 145 seconds each row had about 22 dead versions (217,072 over 10,000 rows), each with its own index entry, and a lookup checks every entry for its key: about 22 heap pages, plus the index pages, comes to the 24.6 buffers measured. A new session incurs that cost although it reads only the newest version, and so does the idle transaction, which reads the oldest. Autovacuum ran during the held runs too but could remove almost nothing.

After the idle transaction committed, read cost recovered within 15 seconds: autovacuum had run and a point read was back to 3 buffers. By the end of the run the dead count was 14,178 ± 645. The space was not returned to the operating system. The table stayed at 30.1 MB and count(*) still took 7.0 ± 1.7 ms against 0.9 ms, because VACUUM marks space as free for reuse inside the table rather than returning it. Shrinking it takes VACUUM FULL or another full rewrite, which locks the table while it runs.

Which snapshots count

horizon.py determines which open transactions hold back the horizon. It updates every row of a 10,000-row table five times, making 50,000 dead versions, and then runs VACUUM (VERBOSE) while one other session sits in an open transaction that never touches the table (horizon.json):

The other sessionRemoved by VACUUMDead but not removable
none10,0150
REPEATABLE READ, same database, has run a query050,000
REPEATABLE READ, another database on the same server10,0150
READ COMMITTED, same database, idle between queries10,0150
READ COMMITTED, same database, has a transaction id050,000

With no other session open, the updates must have already pruned about 40,000 of the dead versions themselves, and VACUUM removed the rest. What pins the horizon is a snapshot that stays open, which READ COMMITTED doesn’t keep between statements, or a transaction id, which any transaction gets once it writes. So an idle BEGIN that has run one UPDATE holds back cleanup for its whole database whatever its isolation level, while a session in another database doesn’t, because the horizon for ordinary tables is computed per database (procarray.c, ComputeXidHorizons). The shared system catalogs are the exception and use a horizon across all databases. Other things that hold the horizon, not tested here, include prepared transactions that were never finished and replication slots. pg_stat_activity.backend_xmin and backend_xid show which sessions are holding it, and idle_in_transaction_session_timeout ends sessions that sit idle inside a transaction.

Cleaning up in PostgreSQL

PostgreSQL removes dead versions in two ways. Reading or updating a page can prune it: dead versions in a chain of heap-only tuples (HOT) are cut out and their space reused without touching any index. An update is HOT when it changes no indexed column and the new version fits on the same page. VACUUM removes dead versions everywhere, index entries included, and records the free space for reuse. Autovacuum runs it on a table once roughly 20% of its rows are dead (autovacuum_vacuum_scale_factor 0.2 plus 50 rows, by default). Neither can remove a version that some open snapshot can still see.

MVCC compared with locking

  • Reads. MVCC readers take no locks and never wait, so a long report can run against a snapshot while writes continue. Under two-phase locking, a long reader blocks every writer that touches what it read.
  • Writes. Writers still conflict with writers. PostgreSQL makes the second writer wait for the first and then, above read committed, fail if the first one committed. Some of the cost moves from waiting to retrying.
  • Serializability. Locking gets it by blocking. MVCC gets it by detecting dangerous structures and aborting (SSI), or by validating at commit (HyPer), and the application has to retry.
  • Storage. A single-version engine updates in place and leaves no old versions. MVCC leaves dead versions behind, and something has to find and remove them: VACUUM in PostgreSQL, purge in InnoDB, per-transaction garbage collection in in-memory engines.
  • Long transactions. The removal rule makes a database wait for its oldest snapshot. One session left idle in transaction, or a day-long analytics query, prevents the removal of every dead version in its database, whichever tables it touched.
  • The readers that incur the cost of an old snapshot may depend on the storage scheme. In the bloat runs, PostgreSQL’s new and old readers touched the same 25 buffers per lookup, because every version had its own index entry. A delta store such as InnoDB keeps one index entry per row and rebuilds old versions from undo, so the same idle snapshot might cost new readers almost nothing there while the old reader walks the undo chain. Running bloat.py’s workload against MySQL would check this.
  • How many SSI aborts are false positives. The two chain schedules show that PostgreSQL’s commit-order test aborts some histories that were serializable. The figure’s model already has a brute-force serializability check, so it could count what share of the aborts in its 2,000 random serializable runs were unnecessary. That share in a random model says little about a real workload, though.
  • The replay harness as a checker for other engines. Replaying a schedule on a real server, step by step, caught two problems in the harness and one in the model before the two agreed on all 80 random schedules. The same schedules replayed on MySQL’s REPEATABLE READ would show, step by step, where it departs from snapshot isolation.

Sources