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
| Problem | With in-place locking only (2PL) | With MVCC |
|---|---|---|
| Reader-writer blocking | Readers hold shared locks; block writers | Readers use snapshots; no read locks on rows |
| Throughput on read-heavy OLTP | Lock contention on popular rows | Concurrent reads at different snapshots |
| Consistent point-in-time reads | Complex lock choreography | Natural snapshot per transaction |
| Long-running analytics | Block writers or use dirty reads | Snapshot can be old but consistent |
| Write-write conflicts | Serialized by exclusive locks | Detected 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,xmaxin 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
| Term | Definition |
|---|---|
| Tuple version | One physical row version of a logical row. |
| xmin | Transaction ID that created this version (PostgreSQL). |
| xmax | Transaction ID that deleted/updated this version. |
| Snapshot | Set of transactions considered visible at a point in time. |
| Snapshot isolation (SI) | Reads from consistent snapshot; first-committer-wins on write conflicts. |
| SSI | Serializable Snapshot Isolation—tracks rw-dependencies, aborts cycles. |
| Vacuum / GC | Reclaims dead tuple versions; advances frozen XID horizon. |
| Write skew | Two txs read overlapping data, write non-overlapping rows, break invariant. |
| Version chain | Linked old versions of same logical row (InnoDB undo chain). |
| Read view | InnoDB structure defining visible trx ids for a transaction. |
| Oldest xmin | Oldest active snapshot bound—blocks vacuum progress. |
| Freeze | Mark 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:
xminis committed andxmin< S's horizon (or in S's active set rules).xmaxis 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.
| Step | Action | MVCC state |
|---|---|---|
| 1 | T1 BEGIN | Snapshot: all committed xids < T1.xid |
| 2 | T1 SELECT balance → 100 | Reads tuple v1 (xmin=50) |
| 3 | T2 UPDATE balance to 80; COMMIT | New v2 (xmin=T2); v1 xmax=T2 |
| 4 | T1 SELECT balance → 100 | Still v1—within T1 snapshot |
| 5 | T1 COMMIT | Snapshot released |
Write skew walkthrough (on-call doctors):
| Step | T1 | T2 |
|---|---|---|
| 1 | BEGIN (SI snapshot) | BEGIN |
| 2 | COUNT on_call ≥ 1 → true (1 doctor) | COUNT → true |
| 3 | UPDATE Alice off_call | UPDATE Bob off_call |
| 4 | COMMIT | COMMIT |
| Result | Zero on call—not serializable |
Under PostgreSQL SERIALIZABLE (SSI), step 3 or 4 triggers 40001 serialization_failure on one transaction.
8. Invariants and Guarantees
| Property | Type | Statement |
|---|---|---|
| Snapshot consistency | Safety | All reads in txn see consistent snapshot (RR+) |
| No dirty reads | Safety | Uncommitted versions invisible |
| First-committer-wins | Safety | Write-write conflict → abort on loser (SI) |
| Serializability (SSI only) | Safety | No serialization anomalies when using SERIALIZABLE |
| Version reclamation | Liveness | Vacuum eventually frees dead tuples if xmin advances |
| Unbounded storage | Not guaranteed | Dead 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
| Factor | Impact |
|---|---|
| Read path | No shared locks—fast concurrent reads |
| Write path | Insert new version + index updates + row exclusive lock |
| Index-only scans | May need heap fetch if visibility not in index |
| Vacuum I/O | Background CPU and I/O; autovacuum tuning critical |
| SSI overhead | Tracks rw-conflicts—more CPU, higher abort rate |
| Version chain length | HOT 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_feedbackawareness—or separate warehouse. - Autovacuum: Scale
autovacuum_vacuum_scale_factordown 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
| Approach | Strength | Cost | Use when |
|---|---|---|---|
| MVCC (SI) | Read concurrency | Write skew, vacuum ops | OLTP read-heavy |
| 2PL | Serializable via locks | Reader-writer blocking | Legacy, simple correctness |
| SSI | Serializable + MVCC reads | Aborts, tracking overhead | Postgres SERIALIZABLE |
| Lock-free / append-only | Immutable events | Read path reconstruction | Event stores |
| Partitioning | Reduces per-shard contention | Cross-shard complexity | Scale-out |
17. Common Misconceptions
| Misconception | Reality |
|---|---|
| "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
- Treat vacuum as production-critical—not DBA trivia.
- Map invariants to SI vs SSI—write skew is the interview trapdoor.
- Separate OLTP snapshots from warehouse ETL—don't run 8-hour txn on primary.
- Design retries for SSI and Cockroach-style serializable.
- 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:
- What blocks vacuum?
- Impact on autovacuum freeze?
- Move export to replica—does it help primary bloat?
idle_in_transaction_session_timeoutvalue?- 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
-
How does MVCC avoid reader-writer blocking?
- Signals: Snapshots read old versions; no shared read locks on rows.
-
What are xmin and xmax?
- Signals: Creating and deleting transaction ids for tuple visibility.
-
Why is VACUUM necessary?
- Signals: Reclaim dead tuples; freeze XIDs; prevent wraparound and bloat.
-
Explain write skew.
- Signals: Overlapping reads, disjoint writes, invariant violation; SI allows.
-
SI vs serializability?
- Signals: SI is not serializable; SSI adds conflict detection.
-
What causes transaction ID wraparound?
- Signals: 32-bit XID space; insufficient freezing; long xmin horizon.
-
How does InnoDB MVCC differ from PostgreSQL?
- Signals: Undo log chain vs heap tuples; Read View; gap locks.
-
What is HOT update optimization?
- Signals: Same-page update without new index entry (PostgreSQL).
-
ORA-01555 meaning?
- Signals: Undo overwritten; snapshot too old (Oracle).
-
How does SSI detect conflicts?
- Signals: Tracks rw-dependencies; aborts on predicate/out edges forming dangerous structures.
-
Can MVCC scale write-heavy hot keys?
- Signals: No—row lock serializes; version chain bloat.
-
Impact of long-running transaction on vacuum?
- Signals: Delays dead tuple reclamation; increases bloat and wraparound risk.
-
READ COMMITTED vs REPEATABLE READ in MVCC?
- Signals: New snapshot per statement vs one snapshot per transaction.
-
When choose 2PL over MVCC?
- Signals: Rare today; simple locking semantics; some embedded systems.
22. Interview Follow-Ups
-
Design multi-tenant analytics without hurting OLTP vacuum.
- Signals: CDC to warehouse, replica, bounded snapshots.
-
100% serialization abort rate on promotion day—what now?
- Signals: Queue, partition inventory, relax to explicit row locks on SKU.
-
Compare MVCC to event sourcing.
- Signals: Both versioned; event sourcing reconstructs state from log.
-
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
| Column | Purpose |
|---|---|
xmin / xmax | Tuple visibility bounds |
snapshot_ts | Transaction read view |
dead_tuples | Reclaim via autovacuum |
Step-by-step flow:
| Step | MVCC behavior | Pitfall |
|---|---|---|
| 1 | Snapshot frozen | Long txn blocks vacuum |
| 2–4 | New version chain | Write skew if RR + predicate |
| 5 | Repeatable read holds | Not serializable for multi-row |
SLO
Autovacuum lag < 5 min; snapshot too old = 0 in OLTP; analytics on replica/CDC.
22B. Game Day Playbooks
| # | Drill | Inject | Detect | Mitigate | Verify |
|---|---|---|---|---|---|
| GD-1 | Long open txn | 24h reporting txn | Bloat / wraparound risk | Kill or move to replica | Vacuum progresses |
| GD-2 | Write skew under RR | Concurrent schedule insert | Invariant break | SERIALIZABLE or locks | No double-book |
| GD-3 | Hot update bloat | 1M updates on row | Table bloat ↑ | HOT + vacuum tune | Query 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.

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 invariant | RR (SI) enough? | Why |
|---|---|---|
| Report of today's shifts (read-only) | Often yes | Stable snapshot is the point |
| Update one shift row, no cross-row rule | Maybe | First-committer-wins on that row |
| ≥1 on-call / coverage count | No | Classic write skew |
| No double-book same slot | No unless exclusion constraint / lock | Concurrent inserts on "free" snapshot |
| Soft preference scoring only | Maybe | If 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)
| Assumption | Why it matters |
|---|---|
| Postgres RR ≈ SI (not InnoDB RR) | Vendor names aren't portable—InnoDB uses next-key locks |
| Concurrent schedulers / doctors / ops | Write skew needs concurrency |
| App retries only on deadlock today | SSI needs explicit 40001 retry |
| Transactions stay short | Long RR snapshots block vacuum / bloat |
| Not claiming external consistency | MVCC 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)

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.

Figure C: RR/SI is not enough for predicate invariants; SSI aborts dangerous histories, or lock/materialize the constraint.
| Fix | Mechanism | When I'd pick it |
|---|---|---|
SERIALIZABLE (SSI) | Tracks rw-dependencies; abort 40001 | Complex predicates; want DB to enforce |
SELECT FOR UPDATE | Lock rows (or candidates) before decide | Small known row set |
| Summary / coverage row | One row on_call_count; updates conflict | Simple ≥N invariants |
| Exclusion / unique | No overlapping tstzrange / slot | Double-book expressible in schema |
| App-level queue | Single writer for schedule mutations | Extreme hot calendar |
I — Invariants (safety)
"I'd write on the whiteboard:
- SI / Postgres RR: snapshot reads + first-committer-wins on same row.
- Does not prevent write skew on multi-row / predicate invariants.
- SERIALIZABLE (SSI) aims for no serialization anomalies—may abort.
- Short transactions — long RR snapshots are an ops hazard (bloat, wraparound risk).
- Engine portability: don't assume MySQL RR behaves like Postgres RR."
C — Constraints (second C)
| Constraint | Design response |
|---|---|
| Hot popular appointment slot | Exclusion constraint or queue; watch SSI abort storms |
| Mixed reporting + booking | RC/RR for reports; SERIALIZABLE or locks only on mutators |
| ORM default isolation | Set per-session; don't trust framework defaults |
| Retry storms | Bounded exponential backoff on 40001; idempotent booking keys |
| Long analytics in same txn as book | Split—never hold booking snapshot for reports |
E — Evolution (prove it)
Phased delivery:
| Phase | Deliverable |
|---|---|
| M1 | Write invariant formally; show write-skew counterexample on whiteboard |
| M2 | ADR: RR for reads; SERIALIZABLE or locks for schedule mutations |
| M3 | App retry on 40001 / deadlock; idempotent booking request id |
| M4 | Concurrent integration test: two "last on-call leaves" must not both succeed |
| M5 | Monitor SSI abort rate, deadlocks, vacuum lag / bloat |
Failure modes:
| Failure | Mitigation |
|---|---|
| Write skew under RR | SSI / locks / materialized constraint |
| "Repeatable = serializable" myth | Teach SI vs SSI |
| Long txn blocks vacuum | Timeouts; split read models |
| Abort storms on hot slot | Materialize 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
40001retries, 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
| Strong | Weak / red flag |
|---|---|
| "No" + names write skew | "Yes, repeatable means consistent" |
| Postgres RR = SI; SERIALIZABLE = SSI | Treats SQL names as portable |
Concrete fix + 40001 retry | Only "use transactions" |
| Materialize / FOR UPDATE / exclusion | No enforcement story |
| Short txn / vacuum awareness | Ignores ops side of MVCC |
| Concurrent invariant test | No 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
- Create
doctors(id, on_call)table; insert two on-call rows. - Two psql sessions:
BEGIN ISOLATION LEVEL REPEATABLE READ. - Both
SELECT count(*) WHERE on_call→ 2. - Each sets different doctor off_call; both commit.
- Observe count=0.
- Repeat with
SERIALIZABLE; observe abort. - Query
pg_stat_user_tablesforn_dead_tupafter heavy updates. - Document mitigation for your invariant.
26. Knowledge Check
- MVCC primary benefit for reads? (Non-blocking snapshot reads.)
- Write skew allowed under? (Snapshot isolation.)
- What does freeze prevent? (XID wraparound corruption.)
- SSI implementation in PostgreSQL? (Serializable isolation level.)
- InnoDB old versions stored in? (Undo log chain.)
27. Flashcards
| # | Front | Back |
|---|---|---|
| 1 | MVCC | Multiple versions; readers use snapshots. |
| 2 | Snapshot isolation | Consistent read snapshot; commit-time ww-conflict. |
| 3 | Write skew | SI anomaly; overlapping read, disjoint write. |
| 4 | SSI | Serializable via dependency tracking + abort. |
| 5 | xmin / xmax | PostgreSQL tuple create/delete trx ids. |
| 6 | VACUUM | Reclaim dead tuples; freeze old xids. |
| 7 | XID wraparound | Emergency if freeze lags—DB shutdown risk. |
| 8 | HOT update | Same-page update skips index churn (PG). |
| 9 | Read View | InnoDB snapshot visibility structure. |
| 10 | ORA-01555 | Snapshot too old—undo purged. |
| 11 | n_dead_tup | Bloat indicator in pg_stat_user_tables. |
| 12 | 40001 | Serialization 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
29. Related Concepts
- ACID and Isolation — isolation levels MVCC implements
- Storage Engines — heap, WAL, undo logs
- Linearizability — different consistency model
- Two-Phase Commit — distributed commits
- Replication — logical slots affect WAL retention
30. References
Primary sources
- Berenson, H., et al. (1995). "A Critique of ANSI SQL Isolation Levels." — snapshot isolation definition.
- Adya, A. (1999). "Weak Consistency." — SI vs serializability formalization.
- Ports, D. R. K., & Clements, A. T. (2012). "Serializable Snapshot Isolation in PostgreSQL." — SSI design.
Production and engineering
- PostgreSQL Documentation — MVCC, Routine Vacuuming.
- MySQL InnoDB — Undo Logs.
- Martin Kleppmann, DDIA — Chapter 7 on snapshots and serializability.
Distinction
| Claim type | Source |
|---|---|
| SI definition | Berenson et al.; Adya |
| SSI algorithm | Ports & Clements (2012); PostgreSQL docs |
| Operational wraparound | PostgreSQL admin docs |