Skip to main content

Multi-Version Concurrency Control (MVCC)

1. Executive Summary​

Multi-Version Concurrency Control (MVCC) is a concurrency control technique that stores multiple versions of each data item rather than overwriting in place. Readers access a consistent snapshot of the database as of a transaction start time (or statement start, depending on isolation), while writers create new versions without blocking readers. At commit time, the system detects write-write conflicts and may abort transactions that would violate isolation guarantees.

MVCC underpins snapshot isolation (SI) in PostgreSQL, Oracle, and many modern databases. SI provides strong read concurrency but is not equivalent to serializability—the classic write skew anomaly remains. PostgreSQL's Serializable Snapshot Isolation (SSI) extends MVCC with dependency tracking to achieve true serializability with optimistic aborts.

This chapter covers MVCC mechanics (tuple versioning, visibility rules, transaction IDs), snapshot isolation semantics, vacuum and garbage collection, write skew and other SI anomalies, comparison with two-phase locking (2PL), production implementations (PostgreSQL, InnoDB, CockroachDB), operational failure modes (bloat, wraparound, long transactions), and principal-level interview framing.

2. Why This Topic Matters​

Principal interviews probe whether candidates understand how databases actually implement isolation, not just SQL level names:

  • Can you explain why readers don't block writers in MVCC?
  • What are xmin/xmax (PostgreSQL) or undo logs (InnoDB) roles?
  • Why does VACUUM exist and what happens if it can't run?
  • Can you articulate snapshot isolation vs serializability with write skew?

Production incidents from MVCC misunderstanding include table bloat exhausting disk, transaction ID wraparound emergencies, replication lag from long snapshots on replicas, and subtle correctness bugs from assuming REPEATABLE READ equals serializable.

Architects who design "read scaling" without understanding snapshot visibility may route analytics queries that see inconsistent cross-table snapshots. Those who ignore vacuum monitoring learn about freeze emergencies at 2 AM.

3. Problems Being Solved​

ProblemWith in-place locking only (2PL)With MVCC
Reader-writer blockingReaders hold shared locks; block writersReaders use snapshots; no read locks on rows
Throughput on read-heavy OLTPLock contention on popular rowsConcurrent reads at different snapshots
Consistent point-in-time readsComplex lock choreographyNatural snapshot per transaction
Long-running analyticsBlock writers or use dirty readsSnapshot can be old but consistent
Write-write conflictsSerialized by exclusive locksDetected at commit; abort loser

MVCC solves read concurrency and snapshot consistency within a single database. It does not solve distributed versioning across services, cross-shard serializability without coordination, or automatic prevention of all serialization anomalies without SSI or locking.

4. Assumptions and System Model​

Assume a single-node relational database with heap or index-organized row storage:

  • Each row version has metadata identifying creating and deleting transactions (e.g., xmin, xmax in PostgreSQL).
  • Transactions receive monotonic transaction IDs (XID) or commit timestamps.
  • Visibility rule: a row version is visible to transaction T if created by a committed txn before T's snapshot and not deleted by a committed txn visible to T.
  • Garbage collection reclaims dead tuple versions no longer visible to any active snapshot.
  • Failures: Crash recovery replays WAL; in-flight transactions abort.

Not assumed: Perfect global clocks (Spanner uses TrueTime—a different model). That all REPEATABLE READ implementations are identical. Unlimited storage for old versions—retention is bounded by vacuum and undo retention policies.

5. Essential Terminology​

TermDefinition
Tuple versionOne physical row version of a logical row.
xminTransaction ID that created this version (PostgreSQL).
xmaxTransaction ID that deleted/updated this version.
SnapshotSet of transactions considered visible at a point in time.
Snapshot isolation (SI)Reads from consistent snapshot; first-committer-wins on write conflicts.
SSISerializable Snapshot Isolation—tracks rw-dependencies, aborts cycles.
Vacuum / GCReclaims dead tuple versions; advances frozen XID horizon.
Write skewTwo txs read overlapping data, write non-overlapping rows, break invariant.
Version chainLinked old versions of same logical row (InnoDB undo chain).
Read viewInnoDB structure defining visible trx ids for a transaction.
Oldest xminOldest active snapshot bound—blocks vacuum progress.
FreezeMark old tuples permanently visible to prevent XID wraparound.

Mnemonic: MVCC = Many Versions, Concurrent reads, Commit-time conflict check.

6. Core Mechanism​

PostgreSQL tuple visibility (simplified)​

A row version is visible to snapshot S if:

  1. xmin is committed and xmin < S's horizon (or in S's active set rules).
  2. xmax is not set, or deleting transaction is not committed for S, or aborted.

Writers always insert new version; old version marked with xmax. Readers never block on row-level read locks for ordinary SELECT.

Figure 1: MVCC snapshot read—reader unaffected by committed writer until reader starts new transaction.

Version chain and vacuum​

Figure 2: Dead versions accumulate until vacuum; long snapshots delay reclamation.

Snapshot isolation vs serializability​

Figure 3: SI allows concurrent disjoint writes after overlapping reads; SSI detects dangerous dependency graphs.

7. Step-by-Step Walkthrough​

Scenario: PostgreSQL REPEATABLE READ—account balance read twice.

StepActionMVCC state
1T1 BEGINSnapshot: all committed xids < T1.xid
2T1 SELECT balance → 100Reads tuple v1 (xmin=50)
3T2 UPDATE balance to 80; COMMITNew v2 (xmin=T2); v1 xmax=T2
4T1 SELECT balance → 100Still v1—within T1 snapshot
5T1 COMMITSnapshot released

Write skew walkthrough (on-call doctors):

StepT1T2
1BEGIN (SI snapshot)BEGIN
2COUNT on_call ≥ 1 → true (1 doctor)COUNT → true
3UPDATE Alice off_callUPDATE Bob off_call
4COMMITCOMMIT
ResultZero on call—not serializable

Under PostgreSQL SERIALIZABLE (SSI), step 3 or 4 triggers 40001 serialization_failure on one transaction.

8. Invariants and Guarantees​

PropertyTypeStatement
Snapshot consistencySafetyAll reads in txn see consistent snapshot (RR+)
No dirty readsSafetyUncommitted versions invisible
First-committer-winsSafetyWrite-write conflict → abort on loser (SI)
Serializability (SSI only)SafetyNo serialization anomalies when using SERIALIZABLE
Version reclamationLivenessVacuum eventually frees dead tuples if xmin advances
Unbounded storageNot guaranteedDead tuples accumulate if vacuum blocked

Write skew: SI guarantees no write-write conflict on same row but not predicate-level conflicts across rows.

9. Failure Scenarios​

Scenario 1: Transaction ID wraparound​

Setup: ~2 billion XIDs consumed; autovacuum freeze lagging due to long transactions.

Effect: Database shutdown to prevent data corruption—catastrophic ops incident.

Mitigation: Monitor age(datfrozenxid), kill long idle transactions, aggressive autovacuum tuning.

Scenario 2: Table bloat​

Setup: Heavy UPDATE workload; vacuum can't keep pace; long-running reporting txn holds snapshot.

Effect: Disk full, query slowdown from heap scans of dead tuples.

Mitigation: VACUUM FULL (locks table), pg_repack, shorten transactions, separate replica for analytics.

Scenario 3: Replication slot lag​

Setup: Logical replication slot; consumer down; WAL retained for slot.

Effect: Disk fill on primary—MVCC-related retention via WAL, not only heap.

Mitigation: Monitor slot lag; drop or fix consumer.

Scenario 4: Assuming SI = serializable​

Setup: REPEATABLE READ on invariant spanning multiple rows.

Effect: Write skew in production under concurrent load.

Mitigation: SERIALIZABLE, explicit locks, or materialized constraint row.

Scenario 5: Hot row update storm​

Setup: Many transactions update same row; MVCC creates version chain per update.

Effect: Contention on row lock; version chain bloat; high abort rate under SSI.

Mitigation: Queue updates, shard counter, reduce transaction scope.

10. Performance Characteristics​

FactorImpact
Read pathNo shared locks—fast concurrent reads
Write pathInsert new version + index updates + row exclusive lock
Index-only scansMay need heap fetch if visibility not in index
Vacuum I/OBackground CPU and I/O; autovacuum tuning critical
SSI overheadTracks rw-conflicts—more CPU, higher abort rate
Version chain lengthHOT updates (PostgreSQL) avoid index updates when same page

HOT (Heap-Only Tuple): PostgreSQL optimization when updated row stays on same page and no indexed column changes—reduces index churn.

Read committed vs repeatable read performance: Under READ COMMITTED, PostgreSQL takes a new snapshot for each statement, so a transaction may see different row versions across statements within the same transaction—cheaper snapshot management for short OLTP statements but surprising behavior for multi-statement reports. REPEATABLE READ holds one snapshot for the transaction lifetime, which can increase conflict detection scope for writes but provides stable reads for analytics-style queries within bounded transaction duration.

Index and visibility interaction: PostgreSQL index-only scans require a visibility map check; if the map bit is not set for a page, the executor must visit the heap tuple to evaluate xmin/xmax—MVCC metadata can defeat index-only optimization on churny tables until vacuum sets all-visible bits.

Comparative latency (qualitative): A point SELECT under MVCC avoids lock acquisition beyond lightweight snapshot setup—typically microseconds of CPU on warm cache. A conflicting UPDATE still waits on row exclusive lock; MVCC does not remove write-write contention. Under SSI, additional CPU tracks predicate locks and rw-edges—benchmark on your workload before assuming SERIALIZABLE is "free" on read-heavy paths.

Capacity planning formula (heuristic): Sustained UPDATE rate × average dead tuple size × (vacuum lag seconds) ≈ bloat growth rate. If long snapshots prevent vacuum from reclaiming, bloat grows linearly with update rate—model this in load tests before black Friday.

11. Scalability Limits​

  • Write hot spots still serialize on row lock—MVCC doesn't eliminate write contention.
  • Snapshot export for very long jobs blocks vacuum—limits sustained UPDATE throughput.
  • SSI abort rate grows with conflicting rw-dependencies—throughput ceiling on contended predicates.
  • Cross-node MVCC (CockroachDB, Spanner) adds clock or timestamp coordination—different scale model.

12. Operational Considerations​

  • Monitor: n_dead_tup, last_autovacuum, age(datfrozenxid), longest transaction duration.
  • Alert: XID age thresholds (e.g., 200M), replication slot lag, table bloat > N GB.
  • Kill policies: idle_in_transaction_session_timeout, statement_timeout.
  • Analytics: Use hot standby with hot_standby_feedback awareness—or separate warehouse.
  • Autovacuum: Scale autovacuum_vacuum_scale_factor down on hot tables.

13. Security Considerations​

  • Stale snapshot reads: Authorized user in long txn sees old secrets after revocation—session length matters.
  • Timing channels: Abort timing on SSI may leak conflict information—niche concern.
  • Logical decoding: MVCC versions exposed via replication—secure replication streams.

MVCC visibility is not a substitute for row-level security policies.

14. Cost Considerations​

  • Storage amplification: Dead tuples until vacuum—plan 20–30% headroom on churny tables (rule of thumb, measure).
  • Vacuum compute: Autovacuum workers compete with OLTP—size instances accordingly.
  • Engineering: Retry logic for SSI; query tuning for bloat.
  • vs 2PL: Lower read-lock contention often wins; write-heavy same-row workloads may not.

15. Production Implementations​

PostgreSQL​

Heap tuples with xmin/xmax; snapshots for isolation; autovacuum; SSI for SERIALIZABLE; FREEZE prevents wraparound. Implementation reference for open-source MVCC behavior.

MySQL InnoDB​

Multi-versioning via undo log chain; clustered index holds current row; Read View for consistency; purge thread reclaims undo. REPEATABLE READ uses next-key locks for phantoms—hybrid MVCC + locking.

Oracle​

Undo segments store old versions; readers don't block writers; ORA-01555 snapshot too old when undo retained insufficiently.

CockroachDB​

Distributed MVCC with hybrid logical clocks; serializable by default; write conflicts cause retry.

FoundationDB​

Multi-version with serializable isolation; optimistic concurrency—different API, same MVCC concepts.

SQL Server Read Committed Snapshot Isolation (RCSI)​

When enabled, READ COMMITTED uses row versioning in tempdb instead of shared locks for reads—readers don't block writers and writers don't block readers for reads. Implementation choice distinct from PostgreSQL defaults; still not full serializable without explicit SNAPSHOT or SERIALIZABLE isolation.

MongoDB WiredTiger​

Document-level MVCC with snapshot reads; multi-document ACID transactions (since 4.0) coordinate across documents with snapshot isolation semantics—cross-document write skew risks similar to relational SI unless explicit concerns addressed in application logic.

Interview note: When comparing engines, ask whether phantom prevention comes from MVCC alone or from next-key/gap locks (InnoDB) or SSI (PostgreSQL SERIALIZABLE)—the mechanism differs even when SQL isolation names match.

16. Alternatives and Tradeoffs​

ApproachStrengthCostUse when
MVCC (SI)Read concurrencyWrite skew, vacuum opsOLTP read-heavy
2PLSerializable via locksReader-writer blockingLegacy, simple correctness
SSISerializable + MVCC readsAborts, tracking overheadPostgres SERIALIZABLE
Lock-free / append-onlyImmutable eventsRead path reconstructionEvent stores
PartitioningReduces per-shard contentionCross-shard complexityScale-out

17. Common Misconceptions​

MisconceptionReality
"MVCC means no locks"Writers take row locks; DDL takes heavy locks.
"Snapshots are free"Dead tuple storage + vacuum cost.
"REPEATABLE READ = serializable"Write skew possible under SI.
"Vacuum is optional maintenance"Required for correctness (freeze) and performance.
"Readers never cause problems"Long readers block vacuum → bloat → wraparound risk.
"MVCC is only PostgreSQL"InnoDB, Oracle, SQL Server RCSI all use variants.

18. Principal Architect Perspective​

  1. Treat vacuum as production-critical—not DBA trivia.
  2. Map invariants to SI vs SSI—write skew is the interview trapdoor.
  3. Separate OLTP snapshots from warehouse ETL—don't run 8-hour txn on primary.
  4. Design retries for SSI and Cockroach-style serializable.
  5. Capacity-plan dead tuple churn on UPDATE-heavy tables.

19. Architecture Review Exercise​

Scenario: SaaS app uses PostgreSQL REPEATABLE READ; background job exports 6-hour report while users update same tables; disk growing 5%/day.

Review prompts:

  1. What blocks vacuum?
  2. Impact on autovacuum freeze?
  3. Move export to replica—does it help primary bloat?
  4. idle_in_transaction_session_timeout value?
  5. Table partitioning for export scope?

Expected findings: Long snapshot holds xmin; replica export with hot_standby_feedback can also block vacuum on primary—use logical replication to warehouse or snapshot exports (pg_export_snapshot with bounded use).

20. Whiteboard Explanation​

90-second version:

"MVCC keeps multiple row versions instead of overwriting. Readers use a snapshot—transaction IDs or timestamps determine visibility—so reads don't block writes. Writers create new versions and lock the row exclusively. Dead versions pile up until vacuum reclaims them. Snapshot isolation gives consistent reads but allows write skew—two transactions read overlapping state and write different rows, breaking an invariant serial execution would prevent. PostgreSQL SERIALIZABLE adds SSI to track read-write dependencies and abort dangerous transactions. Operationally, long transactions are toxic—they block vacuum and can cause XID wraparound emergencies. InnoDB does MVCC with undo logs; behavior differs on phantoms due to gap locks."

21. Interview Questions​

  1. How does MVCC avoid reader-writer blocking?

    • Signals: Snapshots read old versions; no shared read locks on rows.
  2. What are xmin and xmax?

    • Signals: Creating and deleting transaction ids for tuple visibility.
  3. Why is VACUUM necessary?

    • Signals: Reclaim dead tuples; freeze XIDs; prevent wraparound and bloat.
  4. Explain write skew.

    • Signals: Overlapping reads, disjoint writes, invariant violation; SI allows.
  5. SI vs serializability?

    • Signals: SI is not serializable; SSI adds conflict detection.
  6. What causes transaction ID wraparound?

    • Signals: 32-bit XID space; insufficient freezing; long xmin horizon.
  7. How does InnoDB MVCC differ from PostgreSQL?

    • Signals: Undo log chain vs heap tuples; Read View; gap locks.
  8. What is HOT update optimization?

    • Signals: Same-page update without new index entry (PostgreSQL).
  9. ORA-01555 meaning?

    • Signals: Undo overwritten; snapshot too old (Oracle).
  10. How does SSI detect conflicts?

    • Signals: Tracks rw-dependencies; aborts on predicate/out edges forming dangerous structures.
  11. Can MVCC scale write-heavy hot keys?

    • Signals: No—row lock serializes; version chain bloat.
  12. Impact of long-running transaction on vacuum?

    • Signals: Delays dead tuple reclamation; increases bloat and wraparound risk.
  13. READ COMMITTED vs REPEATABLE READ in MVCC?

    • Signals: New snapshot per statement vs one snapshot per transaction.
  14. When choose 2PL over MVCC?

    • Signals: Rare today; simple locking semantics; some embedded systems.

22. Interview Follow-Ups​

  1. Design multi-tenant analytics without hurting OLTP vacuum.

    • Signals: CDC to warehouse, replica, bounded snapshots.
  2. 100% serialization abort rate on promotion day—what now?

    • Signals: Queue, partition inventory, relax to explicit row locks on SKU.
  3. Compare MVCC to event sourcing.

    • Signals: Both versioned; event sourcing reconstructs state from log.
  4. Spanner external consistency vs MVCC snapshot?

    • Signals: TrueTime bounded uncertainty; global serializable transactions.

22A. Production Low-Level Design (Interview + Game Day)​

MVCC snapshot reads + vacuum/GC ops contract. Production LLD and Game Day Standard.

Version chain model​

ColumnPurpose
xmin / xmaxTuple visibility bounds
snapshot_tsTransaction read view
dead_tuplesReclaim via autovacuum

Step-by-step flow:

StepMVCC behaviorPitfall
1Snapshot frozenLong txn blocks vacuum
2–4New version chainWrite skew if RR + predicate
5Repeatable read holdsNot serializable for multi-row

SLO​

Autovacuum lag < 5 min; snapshot too old = 0 in OLTP; analytics on replica/CDC.


22B. Game Day Playbooks​

#DrillInjectDetectMitigateVerify
GD-1Long open txn24h reporting txnBloat / wraparound riskKill or move to replicaVacuum progresses
GD-2Write skew under RRConcurrent schedule insertInvariant breakSERIALIZABLE or locksNo double-book
GD-3Hot update bloat1M updates on rowTable bloat ↑HOT + vacuum tuneQuery latency OK

GD-2 — Write skew (RR not enough)​

23. Strong Answer Example​

Question: "We use PostgreSQL REPEATABLE READ for a scheduling invariant. Good enough?"

Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—usually no for multi-row predicates, and Postgres RR ≠ serializable.

PRACTICE interview answer map for Postgres REPEATABLE READ scheduling

Figure A: PRACTICE map — Problem → Requirements → Assumptions → Capacity → Topology → Invariants → Constraints → Evolution.


Student interview script (PRACTICE)​

P — Problem framing​

"In PostgreSQL, REPEATABLE READ is snapshot isolation (SI)—one consistent snapshot for the whole transaction. That gives stable reads and stops many classic anomalies, but it is not serializability.

Scheduling invariants are usually predicates across rows: 'at least one on-call', 'no double-book of this slot', 'exactly N shifts covered'. Those fail under write skew: two txs each read a snapshot that looks fine, then update different rows, both commit—no write-write conflict on the same tuple, invariant broken.

Short answer: Not good enough for that class of invariant. I'd use SERIALIZABLE (SSI) with retry on 40001, or materialize/lock the constraint—plus short transactions so vacuum stays healthy."

R — Requirements​

Scheduling invariantRR (SI) enough?Why
Report of today's shifts (read-only)Often yesStable snapshot is the point
Update one shift row, no cross-row ruleMaybeFirst-committer-wins on that row
≥1 on-call / coverage countNoClassic write skew
No double-book same slotNo unless exclusion constraint / lockConcurrent inserts on "free" snapshot
Soft preference scoring onlyMaybeIf wrong schedule is recoverable

"I'd ask them to state the invariant as a predicate. If it spans multiple rows or 'absence of a row,' RR alone is a red flag."

A — Assumptions (state aloud)​

AssumptionWhy it matters
Postgres RR ≈ SI (not InnoDB RR)Vendor names aren't portable—InnoDB uses next-key locks
Concurrent schedulers / doctors / opsWrite skew needs concurrency
App retries only on deadlock todaySSI needs explicit 40001 retry
Transactions stay shortLong RR snapshots block vacuum / bloat
Not claiming external consistencyMVCC SI is single-DB snapshot, not Spanner

"I'd say: 'In Postgres, RR means SI—write skew is the interview trap. SERIALIZABLE means SSI.'"

C — Capacity (cost of fixing)​

REPEATABLE READ (SI) → high read concurrency; silent write skew risk
SERIALIZABLE (SSI) → abort+retry under rw-conflicts; measure abort rate
SELECT FOR UPDATE on candidates → predictable serialization; deadlock risk
Materialized constraint row → single-row ww-conflict; simple & hot
Exclusion / unique constraints → DB enforces no double-book; great when expressible

"I'd pay SSI aborts or a locked summary row on the scheduling write path, not blanket SERIALIZABLE on every read-only report."

T — Topology (draw this)​

Write skew on on-call scheduling under REPEATABLE READ

Figure B: Alice and Bob both go off-call from the same SI snapshot—zero on-call; RR allows it because writes hit different rows.

RR vs SERIALIZABLE SSI vs locks for scheduling

Figure C: RR/SI is not enough for predicate invariants; SSI aborts dangerous histories, or lock/materialize the constraint.

FixMechanismWhen I'd pick it
SERIALIZABLE (SSI)Tracks rw-dependencies; abort 40001Complex predicates; want DB to enforce
SELECT FOR UPDATELock rows (or candidates) before decideSmall known row set
Summary / coverage rowOne row on_call_count; updates conflictSimple ≥N invariants
Exclusion / uniqueNo overlapping tstzrange / slotDouble-book expressible in schema
App-level queueSingle writer for schedule mutationsExtreme hot calendar

I — Invariants (safety)​

"I'd write on the whiteboard:

  1. SI / Postgres RR: snapshot reads + first-committer-wins on same row.
  2. Does not prevent write skew on multi-row / predicate invariants.
  3. SERIALIZABLE (SSI) aims for no serialization anomalies—may abort.
  4. Short transactions — long RR snapshots are an ops hazard (bloat, wraparound risk).
  5. Engine portability: don't assume MySQL RR behaves like Postgres RR."

C — Constraints (second C)​

ConstraintDesign response
Hot popular appointment slotExclusion constraint or queue; watch SSI abort storms
Mixed reporting + bookingRC/RR for reports; SERIALIZABLE or locks only on mutators
ORM default isolationSet per-session; don't trust framework defaults
Retry stormsBounded exponential backoff on 40001; idempotent booking keys
Long analytics in same txn as bookSplit—never hold booking snapshot for reports

E — Evolution (prove it)​

Phased delivery:

PhaseDeliverable
M1Write invariant formally; show write-skew counterexample on whiteboard
M2ADR: RR for reads; SERIALIZABLE or locks for schedule mutations
M3App retry on 40001 / deadlock; idempotent booking request id
M4Concurrent integration test: two "last on-call leaves" must not both succeed
M5Monitor SSI abort rate, deadlocks, vacuum lag / bloat

Failure modes:

FailureMitigation
Write skew under RRSSI / locks / materialized constraint
"Repeatable = serializable" mythTeach SI vs SSI
Long txn blocks vacuumTimeouts; split read models
Abort storms on hot slotMaterialize constraint or serialize writers

Observability: 40001 rate, lock wait / deadlock count, autovacuum lag, booking conflict metrics, chaos test for ≥1 on-call.


Closing line (interview)​

"So: PostgreSQL REPEATABLE READ is usually not good enough for a scheduling invariant. It's snapshot isolation—stable reads, but write skew can clear the last on-call doctor or double-book a slot when txs touch different rows. I'd use SERIALIZABLE (SSI) with 40001 retries, or lock / materialize the constraint, keep transactions short, and prove it with a concurrent test in an ADR. I wouldn't confuse Postgres RR with InnoDB RR or with true serializability."

Scoring signals​

StrongWeak / red flag
"No" + names write skew"Yes, repeatable means consistent"
Postgres RR = SI; SERIALIZABLE = SSITreats SQL names as portable
Concrete fix + 40001 retryOnly "use transactions"
Materialize / FOR UPDATE / exclusionNo enforcement story
Short txn / vacuum awarenessIgnores ops side of MVCC
Concurrent invariant testNo proof plan

Compact outline (if time-boxed to 2 minutes)​

"No. Postgres RR is snapshot isolation—write skew breaks multi-row scheduling invariants like ≥1 on-call. Use SERIALIZABLE SSI with 40001 retries, or lock/materialize the constraint. Keep txns short. Prove with a concurrent test. Don't assume MySQL RR is the same."

24. Weak Answer Example​

Question: "We use PostgreSQL REPEATABLE READ for a scheduling invariant. Good enough?"

"Yes, repeatable means reads don't change, so we're consistent."

Why weak / red flags: Confuses stable snapshot reads with serializability; ignores write skew on predicate invariants; no SSI/locks/materialized constraint; no vacuum/short-txn awareness.

25. Hands-On Exercise​

  1. Create doctors(id, on_call) table; insert two on-call rows.
  2. Two psql sessions: BEGIN ISOLATION LEVEL REPEATABLE READ.
  3. Both SELECT count(*) WHERE on_call → 2.
  4. Each sets different doctor off_call; both commit.
  5. Observe count=0.
  6. Repeat with SERIALIZABLE; observe abort.
  7. Query pg_stat_user_tables for n_dead_tup after heavy updates.
  8. Document mitigation for your invariant.

26. Knowledge Check​

  1. MVCC primary benefit for reads? (Non-blocking snapshot reads.)
  2. Write skew allowed under? (Snapshot isolation.)
  3. What does freeze prevent? (XID wraparound corruption.)
  4. SSI implementation in PostgreSQL? (Serializable isolation level.)
  5. InnoDB old versions stored in? (Undo log chain.)

27. Flashcards​

#FrontBack
1MVCCMultiple versions; readers use snapshots.
2Snapshot isolationConsistent read snapshot; commit-time ww-conflict.
3Write skewSI anomaly; overlapping read, disjoint write.
4SSISerializable via dependency tracking + abort.
5xmin / xmaxPostgreSQL tuple create/delete trx ids.
6VACUUMReclaim dead tuples; freeze old xids.
7XID wraparoundEmergency if freeze lags—DB shutdown risk.
8HOT updateSame-page update skips index churn (PG).
9Read ViewInnoDB snapshot visibility structure.
10ORA-01555Snapshot too old—undo purged.
11n_dead_tupBloat indicator in pg_stat_user_tables.
1240001Serialization failure—retry transaction.

28. Cheat Sheet​

MVCC
Read: snapshot visibility (no row read lock)
Write: new version + row exclusive lock
GC: VACUUM / purge undo

SI ≠ SERIALIZABLE
Write skew: classic counterexample
Fix: SSI, locks, materialize invariant

OPS
Monitor age(datfrozenxid), n_dead_tup
Kill idle-in-transaction
Don't run 6hr txn on primary

ENGINES
PG: heap xmin/xmax + SSI
InnoDB: undo + Read View + gap locks

30. References​

Primary sources​

Production and engineering​

  • PostgreSQL Documentation — MVCC, Routine Vacuuming.
  • MySQL InnoDB — Undo Logs.
  • Martin Kleppmann, DDIA — Chapter 7 on snapshots and serializability.

Distinction​

Claim typeSource
SI definitionBerenson et al.; Adya
SSI algorithmPorts & Clements (2012); PostgreSQL docs
Operational wraparoundPostgreSQL admin docs