DEV Community

MVCC: How Databases Let Readers and Writers Coexist

Imagine a report that reads every order from the last year. It takes thirty seconds. Meanwhile, customers keep placing and updating orders.

With simple locking, you get a bad choice: either the report blocks all writes for thirty seconds, or writers block the report, or the report sees a mix of old and new data that never existed at any single moment.

Multi-version concurrency control (MVCC) avoids that choice. PostgreSQL, MySQL's InnoDB, Oracle, SQL Server (with snapshot isolation enabled) and many newer databases use it. This article explains how it works, using PostgreSQL's design as the main example, and what it costs.

The core idea

Instead of overwriting a row in place, the database keeps several versions of it. A writer creates a new version. A reader looks at the version that was current at the moment its snapshot was taken, and ignores newer ones.

The result is the property MVCC is known for: readers do not block writers, and writers do not block readers. Two writers changing the same row still have to wait for each other, but most workloads are dominated by reads.

Snapshots

Every transaction has an ID, assigned in increasing order. When a transaction (or, at Read Committed, each statement) begins, the database takes a snapshot.

Roughly, a snapshot records:

  • which transactions had already committed,
  • which were still running,
  • and that anything that starts later is invisible.

A row version is visible to a snapshot only if the transaction that created it had committed when the snapshot was taken, and the transaction that deleted or replaced it (if any) had not.

Row versions in PostgreSQL

In PostgreSQL, each row version (a tuple) carries two hidden fields:

  • xmin: the ID of the transaction that created this version,
  • xmax: the ID of the transaction that deleted or replaced it, or empty if it is still current.

You can see them:

SELECT xmin, xmax, id, balance FROM accounts WHERE id = 1;

An UPDATE does not change the existing tuple's data. It sets xmax on the old version and inserts a new version with xmin set to the updating transaction. A DELETE only sets xmax.

A worked example

Account 1 has a balance of 100, created long ago by transaction 50.

  • Transaction 200 starts a long report at Repeatable Read. Its snapshot says: everything up to 199 is committed, nothing newer is visible.
  • Transaction 201 runs UPDATE accounts SET balance = 80 WHERE id = 1 and commits. Now there are two versions:
    • version A: balance 100, xmin 50, xmax 201
    • version B: balance 80, xmin 201, xmax empty
  • Transaction 200 reads account 1. Version A was created by 50 (visible) and deleted by 201, which is not in its snapshot, so the deletion does not count: it sees 100. Version B was created by 201: invisible.
  • A new transaction 202 reads account 1. 201 has committed, so version A is deleted and version B is visible: it sees 80.

Transaction 200 never waited, and transaction 201 never waited. Each saw a consistent picture.

What happens when two writers collide

MVCC does not remove write conflicts. If transaction T1 updates a row and T2 tries to update the same row before T1 commits, T2 waits on T1's row lock. What happens next depends on the isolation level:

  • At Read Committed, after T1 commits, PostgreSQL re-checks the row's newest version against T2's WHERE condition and applies T2's update to it.
  • At Repeatable Read and Serializable, if T1 committed, T2 fails with a serialization error ("could not serialize access due to concurrent update"), and the application should retry.

Other designs

Not every engine stores versions the same way.

  • PostgreSQL keeps old and new versions side by side in the table itself.
  • InnoDB and Oracle update the row in place and keep the previous versions in an undo log. A reader that needs an older version follows pointers into the undo log and reconstructs it.

The visible behaviour is similar. The cost shows up in different places: table bloat in PostgreSQL, undo log growth and longer reconstruction in InnoDB when old snapshots stay open.

The cost: garbage

Old versions must eventually go away. A version can be removed when no running transaction could still need to see it.

In PostgreSQL, that cleanup is VACUUM, normally run by the autovacuum background process. It marks dead tuples' space as reusable. It also handles transaction ID wraparound: transaction IDs are 32-bit counters, and vacuum "freezes" old rows so their IDs can be safely reused.

In InnoDB, a purge thread removes undo records and delete-marked rows that no snapshot needs anymore.

This leads to the most common MVCC problem in production: a long-running transaction blocks cleanup for the whole database. A session left open with BEGIN and never committed ("idle in transaction"), a slow analytics query or a forgotten replication slot keeps an old snapshot alive. Dead versions accumulate, tables and indexes grow, and queries slow down.

Practical advice

  • Keep transactions short, and close them. Monitor sessions that stay "idle in transaction"; PostgreSQL has idle_in_transaction_session_timeout for this.
  • Let autovacuum run, and tune it for large, frequently updated tables instead of disabling it.
  • Watch table and index bloat on hot tables.
  • Prefer updates that do not touch indexed columns where you can. In PostgreSQL this allows HOT (heap-only tuple) updates, which avoid adding new index entries.
  • Remember that MVCC is not full isolation. Snapshots prevent dirty and non-repeatable reads, but anomalies like write skew still need Serializable, locks or constraints.

In short

  • MVCC keeps several versions of each row; each transaction reads from a snapshot.
  • Readers never block writers, and writers never block readers. Writers on the same row still conflict.
  • PostgreSQL stores versions in the table with xmin and xmax; InnoDB and Oracle rebuild old versions from undo logs.
  • Old versions must be cleaned up by vacuum or purge, and long transactions stop that cleanup.

Originally published at abdeldjalilchougui.biz.

Top comments (1)

The worked example with transactions 200, 201 and 202 is the part that made this land for me - version A at balance 100 with xmin 50 and xmax 201, version B at 80, and the long report never waiting while still seeing a consistent picture. The bit I would add is the one that bites in practice: the long-running transaction is not just slow, it is the thing that stops VACUUM from cleaning up, so a single forgotten BEGIN can turn a hot table into bloat for the whole database. Your idle_in_transaction_session_timeout advice is the cheapest guard for that. When you have seen this in production, was it usually an idle session, a slow analytics query, or a forgotten replication slot that held cleanup back the longest?

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.