Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 3

How MVCC Gives Each Transaction Its Own Snapshot

See an UPDATE create a new row version, watch two transactions hold different snapshots of the same row, and learn why long-lived transactions cost everyone storage.

Contentsand lesson path

What you will learn

  • Reproduce non-repeatable reads, phantoms, lost updates and write skew, and state which PostgreSQL isolation level prevents each one.

Prerequisites: SQL Fundamentals

01. Why it matters

A production database serves hundreds of connections at once: one running a month-end report over millions of rows, others inserting orders, updating stock, deleting carts. If reading locked the rows being read, the report would freeze the shop for minutes. If writers overwrote rows in place, a reader mid-report would see an order total change under its feet.

PostgreSQL avoids both with multi-version concurrency control, or MVCC: every transaction works on its own private view of the data, called a snapshot. A plain SELECT never blocks a row write and a row write never blocks a plain SELECT. What still waits is two transactions writing the same row, explicit row locks such as SELECT ... FOR UPDATE, and schema changes, which take table locks. This lesson shows MVCC happening on a real table, because isolation levels, the anomalies in the next lesson, and even table bloat all fall out of this one mechanism.

02. An UPDATE writes a new version

PostgreSQL never overwrites a row in place. An UPDATE leaves the old version where it is, marks it superseded, and writes a new version of the row elsewhere on disk. You can see both facts in the hidden columns every row carries: ctid is the row's physical slot, xmin the id of the transaction that created this version, xmax the transaction that superseded it (zero while the version is live).

Python · two updates inside one transaction
with psycopg.connect(DSN) as w:
    ver = "SELECT ctid, xmin, xmax, balance FROM accounts WHERE id = 1"
    print("before:          ", w.execute(ver).fetchone())
    w.execute("UPDATE accounts SET balance = balance - 40 WHERE id = 1")
    print("after update #1: ", w.execute(ver).fetchone())
    w.execute("UPDATE accounts SET balance = balance - 5 WHERE id = 1")
    print("after update #2: ", w.execute(ver).fetchone())
Illustrative output · transaction and slot ids differ every run
before:           ('(0,1)', '770', '0', 100)
after update #1:  ('(0,3)', '771', '0', 60)
after update #2:  ('(0,4)', '771', '0', 55)

Leaving the with psycopg.connect(...) block committed the transaction (psycopg 3 commits on a clean exit), so the balance is now 55; the next demo starts from there.

Read the output as evidence. The slot moved from (0,1) to (0,3) — a different physical row, not an edit in place (slot (0,2) is the account next door). Both new versions share xmin 771 because one transaction created them both; the version from the insert, xmin 770, is now dead but still on disk. Nothing was deleted. The old versions stay until a maintenance process called VACUUM proves that no snapshot can still need them and reclaims the space — which is why a table grows while it is being updated, a cost the query optimisation skill measures.

03. The snapshot: what a transaction may see

A snapshot is a note of "which transactions had committed when I started". A row version is visible to you if its creator committed before your snapshot was taken — and invisible if its creator was still running, or had rolled back. No locks are taken to decide this; it is arithmetic on transaction ids recorded in each row.

When the snapshot is taken depends on the isolation level. At READ COMMITTED, PostgreSQL's default, every statement gets a fresh snapshot: two SELECTs in one transaction can legitimately see different data if someone committed in between. At REPEATABLE READ, the first statement fixes one snapshot for the whole transaction. Watch the difference with two connections. The reader asks psycopg for the level through isolation_level, so the driver itself sends BEGIN ISOLATION LEVEL REPEATABLE READ before the first query (typing BEGIN ... yourself on a default connection makes psycopg open a transaction first, and the server answers with a warning, or an error if a query already ran):

Python · reader in REPEATABLE READ, writer committing underneath
reader = psycopg.connect(DSN)
reader.isolation_level = psycopg.IsolationLevel.REPEATABLE_READ
writer = psycopg.connect(DSN)
print("reader sees:", reader.execute(
    "SELECT balance FROM accounts WHERE id = 1").fetchone()[0])
with writer.transaction():
    writer.execute("UPDATE accounts SET balance = balance - 25"
                   " WHERE id = 1")
print("writer committed -25, without waiting for the reader")
print("reader sees:", reader.execute(
    "SELECT balance FROM accounts WHERE id = 1").fetchone()[0])
reader.commit()
Expected output
reader sees: 55
writer committed -25, without waiting for the reader
reader sees: 55

The reader saw 55 before and 55 after a committed change to the very row it was reading. It is not a cache and nothing was blocked: the reader's snapshot simply does not include the writer's transaction, so the old version — the one with balance = 55 — is the newest version visible to it. The moment the reader commits and starts a new transaction, its new snapshot includes the writer's work and it reads 30. Stale reads are bounded by the transaction: end it, and you are current again.

Behind the curtain, a snapshot is just a note of which transaction ids were still running when yours started. A row version is visible if its creating transaction had committed by then, and its superseding transaction — the xmax — had not. That is the whole trick: no conversation between transactions, no global pause, only ids compared against a note taken once. It is also why two connections at different isolation levels can work side by side — the visibility rule belongs to each snapshot, not to the server as a whole.

04. What snapshots cost

MVCC trades disk and bookkeeping for concurrency, and the bill arrives in two forms.

First, dead versions accumulate. Every update and delete leaves a corpse, and VACUUM can only clear versions that no live snapshot can see. A report that holds a transaction open for an hour pins an hour's worth of dead rows — the table and its indexes bloat, and every query on them scans more pages. Long transactions are not just slow for the person running them; they tax everyone. If a connection must sit idle, end its transaction first.

Second, a snapshot is a photograph, not a lock. REPEATABLE READ promises your view does not shift under you; it does not promise your view still matches reality when you write. Two transactions can each read a consistent picture, act on it, and commit a combined result that contradicts every order the transactions could have run in — a write skew. PostgreSQL has a third level, SERIALIZABLE, which detects exactly that and aborts one of the offenders. Reproducing these anomalies — and choosing the level that stops each one — is the whole of the next lesson.

05. Check your understanding

Practice check · 3 questions

Versions and snapshots

Three questions about what MVCC really stores and promises.

Q1. The reader in the demo commits and immediately starts a new transaction at REPEATABLE READ. What balance does it see now?
Q2. Who eventually removes the dead row versions that updates leave behind?
Q3. A nightly job holds one transaction open for two hours while other services keep updating the tables it read. What is the main cost to everyone else?
Practice only: not graded, not saved, not evidence.

06. Apply it

On the lab container from this skill:

  1. Run the version demo against a books table and explain each column of the output to yourself in writing.
  2. Open a REPEATABLE READ transaction that reads one row, then from another connection update that row 50 times. While the reader is still open, run VACUUM (VERBOSE) books from a third connection: its tuples: line reports about 50 row versions that "are dead but not yet removable" — those are the versions your reader pins. Commit the reader, run VACUUM (VERBOSE) again and watch them move to "removed". (n_dead_tup in pg_stat_user_tables will not show this: it counts dead versions until a vacuum removes them, whether or not a snapshot still pins them.)
  3. Time a plain SELECT count(*) before and after VACUUM on that table, and note that correctness never depended on the vacuum: only speed did.

07. Review prompt

Without looking back: what physically happens on an UPDATE, and which hidden columns prove it? When is a snapshot taken at READ COMMITTED, and at REPEATABLE READ? Why does a long-running transaction make the database bigger for everybody? Finally, name the one thing MVCC snapshots do not protect you from when two transactions write.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check