Skip to the workspace
Pebellslearn by building
High Level Database Concepts  ›  Lesson

MVCC

MVCC 15 minMVCC writes a new row version on every change and lets each snapshot see the versions alive when it began, so readers and writers do not block each other.

postgresql dba / MVCC

Explore each scene at your own pace.

01 · The rule

The rule

MVCC

At 9 a.m. an analyst starts a slow report over all of Pedal's rentals, while riders keep ending rides. In many older databases one side would have to wait for the other. In PostgreSQL neither waits, and the report still sees a consistent picture. The mechanism is called multi-version concurrency control.

The rule

Never overwrite a row: write a new version, and let each snapshot choose.

When you UPDATE a row, PostgreSQL does not change it in place. It writes a new version of the row and marks the old one as ended. Every version 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 (empty while it is current).

Each statement (or, in REPEATABLE READ and SERIALIZABLE, the whole transaction) works from a snapshot: a note of which transactions had committed when it started. A version is visible if its creator had committed by then and its remover had not.

SELECT xmin, xmax, bike_id, available FROM bikes WHERE bike_id = 7;

What follows from this:

  • Readers never block writers, and writers never block readers. The report reads old versions while updates add new ones.
  • Two writers on the same row still queue: the second waits for the first to commit or roll back.
  • DELETE only sets xmax; the row stays on disk.
  • Old versions that no snapshot can see any more are dead tuples. They waste space until VACUUM marks it reusable. The autovacuum background workers do this for you, and also refresh planner statistics.
  • Transaction ids are 32-bit and wrap around, so VACUUM also freezes old rows. If autovacuum is blocked for too long, PostgreSQL will eventually refuse new writes to protect data.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.