Skip to content

    System Design

    MVCC: Multi-Version Concurrency Control in PostgreSQL

    Learn how PostgreSQL keeps old row versions so readers never block writers, read xmin and xmax on real rows, and see what VACUUM frees, with a PGlite lab.

    By Published 13 min read

    Share

    Standard lessonadvancedPostgreSQL labBackend System Design

    Before this: ACID Transactions and Isolation Levels

    What you'll learn: By the end of this lesson you will be able to explain why PostgreSQL stores several versions of a row instead of overwriting it, read xmin, xmax and ctid on real rows, say which version a given snapshot sees, describe what an update, a rollback and a row lock do to the stored versions, and explain why dead versions pile up until VACUUM reclaims them, using a lab that opens a real heap page and shows each step.

    Picture a shared whiteboard. If everyone edits in place, a reader copying a table must hope nobody rubs out a number halfway through, so you either lock the room while people read or accept half-edited copies. Change the rule: nobody erases anything. An edit adds a new line stamped with the author and the time, and strikes through the old line with the same stamp. A reader notes the time they walked in and reads only lines that were live then. Nobody waits. The price is a board full of struck-through lines and a cleaner who must know which ones nobody will ever need again.

    That is multi-version concurrency control. Databases: Basics introduces transactions. The lesson backend-acid-and-isolation-levels names the guarantees, and this lesson shows the storage mechanism PostgreSQL uses to give them. Storage engines covers the surrounding page and index structures.

    Verified with the PostgreSQL 18 documentation, and with PGlite 0.6.1 (PostgreSQL compiled to WebAssembly, which reports itself as PostgreSQL 19.0), on 2026-12-01.

    The core idea

    MVCC lets each statement or transaction read a consistent snapshot of the data while others write, by keeping every committed change as a new row version and recording on each version which transaction created it and which one deleted it. The PostgreSQL manual puts the benefit in one sentence: locks acquired for reading do not conflict with locks acquired for writing, so reading never blocks writing and writing never blocks reading.

    Three labelled illustrations run through it: the minimal example (two rows, one update, a look at the page), the realistic example (ShopStream's inventory table in a flash sale) and the failure example (a rolled-back update that leaves a non-zero xmax on a live row, and a table that grows without VACUUM).

    A row is a set of versions

    In PostgreSQL an UPDATE does not change a row in place. The manual's definition of the system columns says it directly: xmin is "the identity (transaction ID) of the inserting transaction for this row version", and each update of a row creates a new row version for the same logical row. xmax is "the identity of the deleting transaction, or zero for an undeleted row version", and ctid is the physical location of the version within its table.

    Column Meaning Where you see it
    xmin The transaction that created this version Any select, as a hidden column
    xmax The transaction that deleted or locked this version, or zero Any select; can be non-zero on a visible row
    ctid The version's page and slot, for example (0,3) Any select; changes when the row is updated
    One heap page holding two versions of the same rowYour query to Index on id (look up id 1); Index on id to Slot 1, old (index points here); Slot 1, old to Slot 3, new (t_ctid chain)HEAP PAGE 0 OF TABLE ACCTYour query: id = 1Your queryid = 1Index on id: points to slot 1Index on idpoints to slot 1Slot 1, old: xmin T1, xmax T2Slot 1, oldxmin T1, xmax T2Slot 3, new: xmin T2, no xmaxSlot 3, newxmin T2, no xmaxlook up id 1index points heret_ctid chain

    Figure 1. The two versions of row 1 after an update. How to read this: the index still points at the old slot, the old version names the new one through its t_ctid, and the new version has no deleter. The numbers match the lab's step 2.

    Snapshots decide what you see

    A snapshot is the set of transactions whose effects a statement is allowed to see. The manual says each SQL statement sees a snapshot of the data "as it was some time ago, regardless of the current state of the underlying data", which is what keeps a reader from seeing half of a concurrent update. When the snapshot is taken depends on the isolation level, covered in backend-acid-and-isolation-levels:

    • Read Committed (PostgreSQL's default): "a SELECT query sees a snapshot of the database as of the instant the query begins to run", so two queries in one transaction can see different data.
    • Repeatable Read: a query "sees a snapshot as of the start of the first non-transaction-control statement in the transaction", so every query in the transaction agrees.

    For one row version, the check is a question about xmin and xmax. This is a simplified teaching version of the real rules, which also handle subtransactions and in-progress transactions:

    flowchart TD accTitle: Simplified visibility check for one row version accDescr: A decision flow. If the creating transaction is not visible to the snapshot, the version is invisible. Otherwise, if there is no deleting transaction, or the deleter is aborted, in progress or invisible to the snapshot, the version is visible. If the deleter is visible, the version is invisible. start["Row version with xmin and xmax"] --> creator{"Is the xmin transaction committed and visible to my snapshot?"} creator -- "No" --> hidden1["Invisible: not created yet, or its creator aborted"] creator -- "Yes" --> deleter0{"Is xmax zero?"} deleter0 -- "Yes" --> seen1["Visible"] deleter0 -- "No" --> deleter{"Is the xmax transaction committed and visible to my snapshot?"} deleter -- "Yes" --> hidden2["Invisible: already deleted for me"] deleter -- "No" --> seen2["Visible: deleter aborted, still running, or only a lock"]

    Figure 2. Visibility as two questions. How to read this: a version is shown only if its creator counts for you and its deleter, if any, does not. The bottom-right box is why a visible row can carry a non-zero xmax.

    The next sequence is a conceptual illustration, not captured output; the lab shows the same effect inside one connection.

    sequenceDiagram accTitle: A reader keeps its snapshot while a writer commits an update accDescr: A reader starts a repeatable read transaction and reads balance 100. A writer updates the row to 90 and commits. The reader reads again and still sees 100, because its snapshot predates the writer's commit. A new transaction afterwards sees 90. participant R as Reader (Repeatable Read) participant W as Writer participant D as Database R->>D: begin, then select bal (snapshot taken) D-->>R: 100 W->>D: update bal = 90, then commit Note over D: old version kept, new version added R->>D: select bal again D-->>R: 100 (old version, same snapshot) R->>D: commit W->>D: new transaction: select bal D-->>W: 90

    Figure 3. A snapshot outlives a concurrent commit. How to read this: neither side waits for the other; they simply see different versions.

    What an update, a rollback and a lock leave behind

    Each write leaves a footprint on the page, and the footprints explain the odd things you meet in xmax.

    stateDiagram-v2 accTitle: The life of a row version accDescr: A version is created by an insert or update. It is live until another transaction deletes or replaces it and commits. It is then dead once no snapshot can see it, and VACUUM turns its space into free space. A version created by a transaction that rolls back is never visible and goes straight to dead. [*] --> InProgress: insert or update by a transaction InProgress --> Live: that transaction commits InProgress --> Dead: that transaction rolls back Live --> Replaced: another transaction updates or deletes it and commits Replaced --> Dead: no snapshot can still see it Dead --> Reusable: VACUUM frees the slot Reusable --> [*]

    Figure 4. From insert to reusable space. How to read this: only the last step needs VACUUM; everything before it happens as transactions run.

    • Update: writes the new version, sets xmax on the old one to the updating transaction, and links old to new through t_ctid. Nothing is overwritten.
    • Delete: sets xmax on the existing version and writes nothing new.
    • Rollback: nothing has to be undone. The new version simply belongs to a transaction that aborted, so no snapshot ever sees it, and the old version's xmax names a transaction that aborted, so it is ignored.
    • Row lock: select ... for update also stores the locker in xmax, which the manual hints at when it says locking a row "might cause a disk write". A flag on the version distinguishes a lock from a delete.

    The manual's own wording for the odd case: it is possible for xmax to be nonzero in a visible row version, which "usually indicates that the deleting transaction hasn't committed yet, or that an attempted deletion was rolled back".

    Dead versions, HOT and VACUUM

    Old versions cannot be thrown away at commit, because some snapshot may still need them. The manual says an update or delete does not immediately remove the old version, and that the space "must then be reclaimed for reuse by new rows, to avoid unbounded growth of disk space requirements. This is done by running VACUUM."

    • HOT updates. When an update changes no indexed column and the page has room, PostgreSQL writes the new version on the same page without adding index entries (a heap-only tuple). For such rows, versions other than the oldest and newest "can be completely removed during normal operation, including SELECTs". The lab's step 2 shows the flags: HOT-UPDATED on the old version, ONLY-TUPLE on the new one.
    • Plain VACUUM. It removes dead versions in tables and indexes and marks the space available for reuse, but does not return it to the operating system except when pages at the very end of a table become entirely free.
    • VACUUM FULL. It writes a complete new copy of the table with no dead space, needs extra disk for the copy and takes an ACCESS EXCLUSIVE lock, so it cannot run alongside other use of the table.

    Vacuum also updates planner statistics, maintains the visibility map (pages whose versions are all visible to everyone, which speeds index-only scans and lets vacuum skip them) and guards against transaction ID wraparound: IDs are 32 bits, so every table must be vacuumed at least once every two billion transactions, and VACUUM marks old rows frozen, visible to every current and future transaction. Autovacuum automates this, and the manual calls it "highly recommended".

    What MVCC does not do

    • It does not remove write-write conflicts. Two transactions updating the same row still serialize: the second waits for the first to finish. That wait is the topic of backend-locking-optimistic-pessimistic-and-deadlocks.
    • It does not remove isolation-level effects. Under Repeatable Read, updating a row another transaction changed after your snapshot fails with could not serialize access due to concurrent update, and the manual says to retry the transaction. Under Read Committed the second updater re-evaluates its WHERE clause on the newer version and proceeds.

    Build it: look inside a heap page

    This is the minimal example, run on a real PostgreSQL engine. Goal: see the versions behind a table with xmin, xmax and the page contents, and watch VACUUM act on them.

    Setup. The lab runs on PGlite, PostgreSQL compiled to WebAssembly, in one in-process connection: no server, no Docker. From the repository:

    cd examples/postgres-labs
    npm install
    node labs/mvcc-row-versions/run.mjs
    node --test labs/mvcc-row-versions/test.mjs

    The second command prints the report excerpted below; the third runs 9 tests, one of which checks that two runs print identical text. The code is examples/postgres-labs/labs/mvcc-row-versions/run.mjs. A helper, versions(), reads page 0 with the pageinspect extension, whose heap_page_items "shows all line pointers on a heap page", visible or not. Transaction ids print as T1, T2, and so on, counted from the lab's first transaction, because the raw ids depend on the database's history.

    What it cannot show. PGlite has one connection, so the lab cannot show a long transaction holding back VACUUM, a second updater waiting for a first, or a serialization failure; this lesson describes those in words. Autovacuum is not part of it either (the lab tables have it disabled so that VACUUM runs exactly when the report says).

    Steps 1 and 2: insert, then update. The insert stamps both rows with T1. The update leaves slot 1 in place with xmax set to T2 and adds slot 3.

    Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0, 2026-12-01):

    PostgreSQL version: PostgreSQL 19.0 (PGlite 0.6.1)
    Transaction ids are printed as T1, T2, ... counted from the first transaction below (the raw ids are not stable).
    
    == 1. An insert stamps each row with the transaction that created it
    > insert into acct values (1, 100), (2, 200)
    > select ctid, xmin, xmax, id, bal from acct order by id
      ctid   xmin  xmax  id  bal
      -----  ----  ----  --  ---
      (0,1)  T1    -     1   100
      (0,2)  T1    -     2   200
    
    == 2. An update writes a new version and marks the old one
    > update acct set bal = bal - 10 where id = 1
    > select ctid, xmin, xmax, id, bal from acct order by id
      ctid   xmin  xmax  id  bal
      -----  ----  ----  --  ---
      (0,3)  T2    -     1   90
      (0,2)  T1    -     2   200
    Every version on the page, visible or not:
    > select * from versions('acct')
      lp  state   to_lp  t_xmin  t_xmax  t_ctid  flags
      --  ------  -----  ------  ------  ------  -----------
      1   normal         T1      T2      (0,3)   HOT-UPDATED
      2   normal         T1      -       (0,2)
      3   normal         T2      -       (0,3)   ONLY-TUPLE

    Slot 1 is the old version: created by T1, deleted by T2, with t_ctid pointing to (0,3). A plain select shows slots 3 and 2, so row 1's ctid changed, which is why the manual says not to use ctid as a row identifier.

    Step 3: a snapshot keeps the old version. One connection cannot play two sessions, but a cursor shows the same mechanism: the manual says all PostgreSQL cursors are insensitive, so changes made later in the same transaction are not visible through one.

    Expected output, captured from a real run (the same run):

    == 3. A snapshot keeps seeing the old version (one connection, snapshots per statement)
    A cursor takes its snapshot when it is declared; a later statement of the same transaction does not change what it sees.
    > begin
    > declare c cursor for select id, bal from acct order by id
    > update acct set bal = bal - 10 where id = 1
    > select id, bal from acct order by id
      id  bal
      --  ---
      1   80
      2   200
    > fetch all from c
      id  bal
      --  ---
      1   90
      2   200
    > commit

    The update made bal 80, yet fetch still returns 90, because the version holding 90 is still on the page.

    Steps 4 and 5: rollback and a row lock. After a rolled-back update, row 2 is still current, yet its xmax is non-zero, and the version the update wrote sits on the page, owned by an aborted transaction. A select ... for update sets xmax with no deletion, flagged XMAX-LOCK-ONLY.

    Expected output, captured from a real run (the same run):

    == 4. A rollback needs no undo: the new version is simply never visible
    > begin
    > update acct set bal = 0 where id = 2
    > rollback
    > select ctid, xmin, xmax, id, bal from acct order by id
      ctid   xmin  xmax  id  bal
      -----  ----  ----  --  ---
      (0,4)  T3    -     1   80
      (0,2)  T1    T4    2   200
    Row 2 has a non-zero xmax, yet it is still the current version: the transaction named in xmax aborted.
    > select * from versions('acct')
      lp  state   to_lp  t_xmin  t_xmax  t_ctid  flags
      --  ------  -----  ------  ------  ------  ----------------------
      1   normal         T1      T2      (0,3)   HOT-UPDATED
      2   normal         T1      T4      (0,5)   HOT-UPDATED
      3   normal         T2      T3      (0,4)   HOT-UPDATED ONLY-TUPLE
      4   normal         T3      -       (0,4)   ONLY-TUPLE
      5   normal         T4      -       (0,5)   ONLY-TUPLE

    Expected output, captured from a real run (the same run):

    == 5. xmax also records a row lock, with no deletion
    > begin
    > select id from acct where id = 2 for update
    > select ctid, xmin, xmax, id, bal from acct where id = 2
      ctid   xmin  xmax  id  bal
      -----  ----  ----  --  ---
      (0,2)  T1    T5    2   200
    > select * from versions('acct') where flags like '%XMAX-LOCK-ONLY%'
      lp  state   to_lp  t_xmin  t_xmax  t_ctid  flags
      --  ------  -----  ------  ------  ------  --------------
      2   normal         T1      T5      (0,2)   XMAX-LOCK-ONLY
    > commit

    Steps 6 and 7: what VACUUM does. Two more updates leave seven versions for two live rows. After VACUUM, four dead versions are unused (free for new versions) and slot 1 became a redirect to the live version, so the index entry that points at slot 1 still reaches the current row. The visibility map now says the page is all-visible, and VACUUM (FREEZE) flags the survivors as frozen.

    Expected output, captured from a real run (the same run):

    == 6. VACUUM turns dead versions into reusable space
    > update acct set bal = bal + 1 where id = 1
    > update acct set bal = bal + 1 where id = 1
    Live rows: 2. Versions on the page before VACUUM:
    > select * from versions('acct')
      lp  state   to_lp  t_xmin  t_xmax  t_ctid  flags
      --  ------  -----  ------  ------  ------  ----------------------
      1   normal         T1      T2      (0,3)   HOT-UPDATED
      2   normal         T1      T5      (0,2)   XMAX-LOCK-ONLY
      3   normal         T2      T3      (0,4)   HOT-UPDATED ONLY-TUPLE
      4   normal         T3      T6      (0,6)   HOT-UPDATED ONLY-TUPLE
      5   normal         T4      -       (0,5)   ONLY-TUPLE
      6   normal         T6      T7      (0,7)   HOT-UPDATED ONLY-TUPLE
      7   normal         T7      -       (0,7)   ONLY-TUPLE
    > vacuum acct
    After VACUUM ('unused' slots are free for new versions; 'redirect' keeps the old address pointing at the current version):
    > select * from versions('acct')
      lp  state     to_lp  t_xmin  t_xmax  t_ctid  flags
      --  --------  -----  ------  ------  ------  --------------
      1   redirect  7      -       -
      2   normal           T1      T5      (0,2)   XMAX-LOCK-ONLY
      3   unused           -       -
      4   unused           -       -
      5   unused           -       -
      6   unused           -       -
      7   normal           T7      -       (0,7)   ONLY-TUPLE
    > select * from pg_visibility_map('acct')
      blkno  all_visible  all_frozen
      -----  -----------  ----------
      0      true         false

    Expected output, captured from a real run (the same run):

    == 7. VACUUM (FREEZE) marks old versions as visible to every transaction
    > vacuum (freeze) acct
    > select * from versions('acct')
      lp  state     to_lp  t_xmin  t_xmax  t_ctid  flags
      --  --------  -----  ------  ------  ------  ----------------------
      1   redirect  7      -       -
      2   normal           T1      -       (0,2)   XMIN-FROZEN
      3   unused           -       -
      4   unused           -       -
      5   unused           -       -
      6   unused           -       -
      7   normal           T7      -       (0,7)   ONLY-TUPLE XMIN-FROZEN
    > select * from pg_visibility_map('acct')
      blkno  all_visible  all_frozen
      -----  -----------  ----------
      0      true         true

    Step 8: growth. Two tables of 1,000 illustrative rows each get six updates of every row; one is vacuumed after each step, the other is not.

    Expected output, captured from a real run (the same run):

    == 8. Dead versions take space until VACUUM runs (illustrative data: 1,000 rows, each with a 100-character pad)
    block_size = 8192 bytes. Each step updates every row of both tables; only with_vacuum is vacuumed after each step.
      step          no_vacuum_pages  with_vacuum_pages
      ------------  ---------------  -----------------
      after insert  18               18
      update 1      35               35
      update 2      52               35
      update 3      69               35
      update 4      85               35
      update 5      101              35
      update 6      117              35
    > vacuum no_vacuum
    no_vacuum pages after a plain VACUUM: 117
    > vacuum full no_vacuum
    no_vacuum pages after VACUUM FULL: 18

    Without VACUUM the table grows by about 17 pages per update, from 18 to 117. With it, the table settles at 35: while an update runs every old version is still needed, so the new versions need fresh pages, and VACUUM then frees the old ones for the next update. A plain VACUUM of the grown table made space reusable, not smaller; only VACUUM FULL rewrote it to 18 pages. These sizes belong to this lab's rows and page size.

    Break it. In run.mjs, delete the vacuum with_vacuum line inside the loop of step 8: the test "without VACUUM the table grows ... levels off" fails. Restore the line and re-run.

    Stretch. Update an indexed column and compare the flags with step 2. Left out: concurrent sessions, autovacuum, index entries, TOAST and server settings.

    Choosing: the trade-offs

    Design Gain Cost Wrong when
    MVCC with versions in the table (PostgreSQL) Readers and writers do not block each other Dead versions, vacuum, bigger tables Rows are rewritten constantly and nobody owns vacuum
    Read-write locking Simple model, no dead versions Readers and writers wait for each other A long report must run beside live traffic
    Append events, aggregate later No update churn on hot rows More storage, a read-side cost You need the current value in one lookup

    In practice: ShopStream's inventory table during a flash sale

    This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. Every number is illustrative.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream runs a one-hour flash sale on a few products. Each order decrements an inventory row, so a few thousand rows take most of the writes, while a finance report runs a long read on the same table. The table's file keeps growing although its row count is stable.

    Starting architecture

    ShopStream inventory under a flash saleCheckout to Inventory table (update stock); Finance report to Inventory table (read old snapshot); Autovacuum to Inventory table (clean up when safe)Checkout: decrement stockCheckoutdecrement stockFinance report: long readFinance reportlong readInventory table: hot rowsInventorytablehot rowsAutovacuum: cleanupAutovacuumcleanupupdate stockread old snapshotclean up when safe

    Figure 5. Writers, a long reader and the cleaner on one table. How to read this: checkout writes new versions and the report reads old ones. Cleanup can only free a version that no snapshot, including the report's, can still see.

    Options considered

    Option What it does Risk
    A. Leave it Rely on autovacuum Dead versions accumulate while the report holds its snapshot
    B. Shorten or move the report Run it in slices or on a replica Report logic changes; replica lag must be understood
    C. Tune the table Run autovacuum sooner and leave room on pages for HOT updates Needs measurement; settings are per release

    The decision

    Option B first, because the manual says a version must not be deleted while it is still potentially visible to other transactions: the long report is why cleanup cannot catch up. Option C follows, using the levers the manual names: fillfactor to leave space on a page for HOT updates, and pg_stat_all_tables to monitor HOT and non-HOT updates.

    Rollout and verification

    A rollout would run the new report path for one night beside the old one and compare totals. Verification is measured: the table's size under the same sale, the share of updates that were HOT, and the age of the oldest open transaction during the report.

    The 2 a.m. failure

    The page reads: inventory queries slowed after last night's sale and disk is climbing. The report held its snapshot for hours, so the sale's dead versions could not be reclaimed until it finished (the left column of step 8). The checks: the age of the oldest open transaction, the table's size against its live row count, and what autovacuum could remove. The mitigation is to end or move the long transaction and let vacuum run; VACUUM FULL is a last resort because of its exclusive lock. The lasting fix is a rule that reports do not run against the primary's hot tables, plus an alert on the oldest transaction's age.

    Architect's notes

    • Name the isolation level with its snapshot rule. "Read Committed, a new snapshot per statement" and "Repeatable Read, one snapshot per transaction" are different promises.
    • Treat vacuum as part of the design. A write-heavy table needs an owner for its cleanup.
    • Keep transactions short. A long transaction pins old versions for everyone.

    Common mistakes

    • Reading a non-zero xmax as "deleted". It can be a lock, or a transaction that rolled back.
    • Expecting VACUUM to shrink the file. Plain VACUUM makes space reusable; only VACUUM FULL compacts, with an exclusive lock.
    • Disabling autovacuum to save I/O. The manual calls that unwise unless the workload is extremely predictable.
    • Treating MVCC as "no locks". Writers to one row still queue.

    Key takeaways

    • Each update creates a new row version; xmin names its creator, xmax its deleter or locker, ctid its address.
    • A snapshot sees a version if its creator is visible to it and its deleter is not.
    • Reading never blocks writing and writing never blocks reading; two writers on one row still queue.
    • A rollback leaves an invisible version behind and needs no undo.
    • Dead versions need VACUUM; plain VACUUM reuses space, VACUUM FULL compacts under an exclusive lock.

    Practice exercises

    Exercise 1 (20 min). For the lab's step 4, explain which version of row 2 a new snapshot sees and why its xmax is non-zero.

    Exercise 2 (45 min). Run the lab. In step 6, list the seven versions before VACUUM, say which five became unused or a redirect, and why slot 1 became a redirect.

    Exercise 3 (1 hour). Run "Break it". Then make step 8 update an indexed column and predict the page counts before you run it.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments