Skip to the page

PostgreSQL and MySQL inside · mid

MVCC: how PostgreSQL lets readers and writers work together

PostgreSQL never changes a row in place. An UPDATE writes a new row version, and each query uses a snapshot to decide which versions it can see, so readers and writers do not block each other.

The notes

What you must know

  • Each row version stores the id of the transaction that created it (xmin) and the id of the one that deleted or replaced it (xmax).
  • A snapshot decides which versions a query can see. A version is visible when its creator is committed and its deleter is not visible to the snapshot.
  • UPDATE writes a new version and marks the old one. DELETE only marks the row. The old versions stay on disk until VACUUM removes them.
  • Readers do not block writers, and writers do not block readers. Two writers on the same row still wait for each other.
  • HOT update: if no indexed column changes and the page has free room, the new version stays on the same page and no index needs a new entry. A lower fillfactor leaves that room.
  • A very long transaction holds back cleanup for every table, because its snapshot might still need the old versions. Dead rows pile up and queries slow down.
  • InnoDB works differently: it updates the row in place and keeps old versions in the undo log for readers. A purge thread cleans the log, and long transactions make it grow.

The red pen

Common traps: mistake → fix

  • Mistake: PostgreSQL updates a row in place

    Fix: it writes a new version and leaves the old one until VACUUM.

  • Mistake: MVCC means no waiting at all

    Fix: only reads are free of blocking; two writers on one row still wait.

  • Mistake: VACUUM only gives disk space back

    Fix: its first job is to make dead versions reusable and to keep transaction ids safe.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does MVCC mean, in one sentence?
  2. What happens on disk when you run UPDATE on one row in PostgreSQL?
  3. What are xmin and xmax?
  4. Why can one forgotten open transaction slow down a whole database?
  5. How does InnoDB keep old row versions, and how is that different from PostgreSQL?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview