Databases
MVCC: why readers and writers never wait for each other
A five-minute analytics report and a high-volume checkout flow are running at the same time on the same database. Without special design, one would freeze the other. With MVCC, neither waits — and the trick costs nothing at read time.
What MVCC does in one sentence
MVCC keeps every row’s history so each transaction sees a stable picture of the database without having to lock the rows other people are touching.
Why care. Without it, a five-minute analytics query would freeze every order coming in, and your dashboard would either lie about totals or block the checkout button.
The library metaphor
Imagine a busy library where every book has many copies stamped with the date they were taken off the shelf. When a reader asks for “the catalog as of when I started reading”, the librarian hands them a labeled copy frozen at that moment, even while a librarian behind the counter is binding a new edition. The reader reads their copy in peace. The librarian adds a new edition. Neither has to wait for the other; they are looking at different stamped copies of the same shelf.
Later, a janitor sweeps through and discards copies nobody is reading anymore. That sweep is what Postgres calls VACUUM, and the janitor only throws out a copy when no reader is still holding its date-stamp.
| Without MVCC | With MVCC |
|---|---|
| Reader locks the row; writer waits | Reader sees an old version; writer creates a new one |
| Writer locks the row; reader waits | Writer creates a new version; reader still sees the old |
| Analytics query blocks checkout | Analytics query reads frozen snapshot; checkout proceeds |
Sven and Otto — the concrete scenario
An app server runs a monthly report (Sven). The database receives thousands of orders per second (Otto). Without MVCC, the report either locks the orders table (freezing checkout) or sees half-finished updates. With MVCC, Sven gets a snapshot frozen at the report start; new orders go to fresh versions Sven cannot see. Report finishes, checkout never stalls.
The lost-update gap MVCC does not close
Two browser tabs edit the same profile. Tab A loads, you type. Tab B loads, edits one field, saves. You save Tab A: Tab B’s edit silently disappeared. That is lost update. MVCC alone does not fix it — it still gives both tabs a valid snapshot, but does not serialize their writes. Ask the database with SELECT FOR UPDATE or a stricter isolation level (covered in lesson 03).
Why this works
MVCC was not invented by Postgres. The concept dates to 1978 (Reed’s work at MIT). Oracle shipped it in version 7 (1992); Postgres had a form of it from the very start, and it was one reason Postgres was chosen over competitors in multi-user workloads. MySQL InnoDB added MVCC in 2000.
What does MVCC actually do?
A long-running analytics query and a high-volume checkout flow are running at the same time. With MVCC, what happens?
Put the life of one row's update in order:
- 1 Transaction A starts; gets snapshot tagged with its transaction id
- 2 Transaction A reads the row at version v1 — the version stamped before A started
- 3 Transaction B updates the row, creating version v2 stamped with B's transaction id
- 4 Transaction B commits — v2 is now the latest visible version for new snapshots
- 5 Transaction A still reads v1 because that is what its snapshot allows
- 6 Eventually no snapshot needs v1; VACUUM marks v1's space reusable
Fill in the blank: MVCC is like a library where each reader gets a date-stamped _______ instead of the shelf book itself.
- 01In one sentence: why does a five-minute analytics query in Postgres not block checkout writes?
- 02What is a lost update, and why does MVCC not prevent it?
- 03What does VACUUM do and why is it needed after MVCC updates?
MVCC keeps every row as a chain of versions, each stamped with the transaction that wrote it. When a transaction starts, Postgres gives it a snapshot — a frozen view of which versions are visible. Readers see old versions; writers create new ones; neither ever blocks the other. The storage cost is dead versions accumulating until VACUUM reclaims them. MVCC does not prevent lost updates: two concurrent transactions can still overwrite each other’s work if the application does not use row-level locking or a stricter isolation level.
appears again in147
- Why GraphQL gets N+1junior
- DataLoader mechanics: tick-boundary batchingmiddle
- Batch function contracts: ordering, shapes, errorsmiddle
- Federation and lookahead: batching beyond DataLoadermiddle
- Query complexity defences: depth, cost, persisted queriesmiddle
- Senior GraphQL API: scheduling contract, tenant isolation, observabilitysenior
- Why idempotency: making retries safejunior
- Server-side state machine: four states of an idempotency keymiddle
- Outbox and inbox: effectively-once across the dual-write boundarymiddle
- Concurrency and cache architecture for idempotency at scalesenior
- Observability, production failures, and global-scale designsenior
- The event loop: one thread, three queuesjunior
- Tasks, microtasks, and scheduler.yield()middle
- Microtask starvation, Long Tasks, and LoAFsenior
- Node.js event loop: phases, nextTick, and loop lagsenior
- React, Vue, and INP observability in productionsenior
- The render pipeline: six stages from bytes to pixelsjunior
- Stage costs and the renderer process modelmiddle
- Invalidation, dirty bits, and containmiddle
- Compositor layers: promotion, overlap, and GPU memorymiddle
- DevTools flame strip and the frame lifecyclemiddle
- Layout thrash: forced synchronous layoutsenior
- BeginMainFrame, compositor-driven animations, and GPU memorysenior
- Production observability: LoAF, INP, and the full attack surfacesenior
- What V8 is and why performance varies 100×junior
- V8''''s four-tier JIT pipeline and profile-guided tieringmiddle
- Hidden classes, transition trees, and memory layoutmiddle
- Inline caches, IC states, and deoptimizationmiddle
- Orinoco GC: parallel scavenger, concurrent marking, and write barriersmiddle
- TurboFan''''s speculative engine and the deopt-loop trapsenior
- V8 in production: isolates, pointer compression, and real failuressenior
- Service worker lifecycle and cache strategiesmiddle
- Service worker edge cases: version skew, durability, and navigation trapssenior
- What the reconciler does: render vs commitjunior
- The fiber object and the double-buffer treemiddle
- Render phase purity and commit phase sub-stepsmiddle
- Reconciliation: diffing heuristics and the key trapmiddle
- Priority lanes, time-slicing, and useTransitionmiddle
- Bailout, memoisation, and tearingsenior
- React Profiler, the Compiler, and production observabilitysenior
- Rendering strategies: SSG, SSR, ISR, streaming, and hydrationjunior
- SSG, SSR, ISR, streaming, and RSC — how each worksmiddle
- Hydration cost: selective, progressive, islands, resumabilitymiddle
- Hydration mismatch: causes, detection, and the determinism rulesenior
- RSC, per-route strategy, and production observabilitysenior
- Core Web Vitals: what LCP, INP, and CLS measurejunior
- CLS: why layout shifts happen and how to stop themmiddle
- Metric tradeoffs, RUM attribution, and the CI+field loopsenior
- The full picture: URL to LCP to INP as a relay racejunior
- Eight layers traced: from the service worker to the second navigationmiddle
- Five canonical breaks: where production reliably diessenior
- The three-track method: reading traces and building a monitored systemsenior
- What is a cache stampede and why it makes things worsejunior
- Lock and single-flight: bounding concurrent rebuildsmiddle
- XFetch: coordination-free probabilistic early expirationmiddle
- Stale-while-revalidate and CDN request coalescingmiddle
- Detecting stampedes and designing TTL for productionmiddle
- Metastable failure, fencing tokens, and production postmortemssenior
- Raft roles, terms, and why majority quorums prevent split brainjunior
- How Raft replicates a log entry and decides it is safe to commitmiddle
- Raft leader election: timeouts, voting rules, and the four safety propertiesmiddle
- Raft in the real world: partitions, slow disks, and client routingmiddle
- Raft extensions: pre-vote, learners, snapshots, and linearizable readssenior
- Raft in production: membership changes, Multi-Raft, and observabilitysenior
- Where data fetching happens — and why it decides LCPjunior
- Fetch waterfalls — diagnosis and the Promise.all curemiddle
- React Server Components and Suspense streamingmiddle
- Client-side cache: TanStack Query, SWR, and stale-while-revalidatemiddle
- LCP, prefetch, and race conditions in interactive fetchingmiddle
- Senior internals: RSC payload, caching layers, and production failure modessenior
- The three-way handshakejunior
- Sequence numbers and connection statemiddle
- DNS: what it does and why it existsjunior
- The resolver walk: referrals, record types, and gluemiddle
- TTL, caching, and DNS propagationmiddle
- The 1-RTT handshake: key shares and ECDHEmiddle
- Session resumption and 0-RTTmiddle
- HTTP: the request-response language of the webjunior
- HTTP/2: streams, frames, and HPACKmiddle
- HTTP/3 and QUIC: stream-level loss isolationmiddle
- HTTP/3 in production: QUIC internals, fallback, and observabilitysenior
- HTTP design: priorities, WebTransport, and semantic correctnesssenior
- WebSocket: the HTTP upgrade handshakejunior
- WebSocket frame format: opcodes, masking, fragmentationmiddle
- WebSocket backpressure: when clients can''''t keep upmiddle
- Reconnection: jittered backoff, thundering herd, message resumptionsenior
- WebSocket at scale: HTTP/2 multiplexing, permessage-deflate, C10Msenior
- WebSocket in production: proxies, security, and distributed architecturesenior
- What reverse proxies dojunior
- Health checks, connection draining, and slow startmiddle
- Session affinity, consistent hashing, and the right fixmiddle
- Retry storms, circuit breakers, and load sheddingsenior
- Resilient LB architecture: anycast, zone-aware routing, and observabilitysenior
- Why QUIC and not TCP+TLSjunior
- QUIC streams and head-of-line blockingjunior
- Connection IDs and network migrationmiddle
- 0-RTT resumption and packet encryptionsenior
- DDoS: what it is and why it worksjunior
- Amplification attacks and state exhaustionmiddle
- Rate limiting: algorithms and architecturemiddle
- WAFs, firewalls, mTLS, and HSTSmiddle
- DNS cache poisoning and BGP hijackingsenior
- Defense-in-depth architecture and attack economicssenior
- DNS, TCP, TLS in sequence: where the milliseconds gomiddle
- Critical render path and Core Web Vitalsmiddle
- Proxy intercepts and security gates: rate limiters, WAF, mTLSmiddle
- Alternate paths: QUIC 0-RTT, WebSocket upgrade, connection migrationmiddle
- Observability: distributed traces, USE/RED, and samplingsenior
- Resilience: cascading retries, circuit breakers, and error budgetssenior
- What the three signals are: logs, metrics, and tracesjunior
- Why structured logs exist: the diary vs the spreadsheetjunior
- The production log schema: fields every line must carrymiddle
- PII redaction and log injectionsenior
- OTel Logs Data Model and audit logs as a subsystemsenior
- SLI, SLO, and the error budget: reliability by the numbersjunior
- Error budget policy, latency SLOs, and composite journeysmiddle
- Production SLO failures, self-observability, security, and the big picturesenior
- The incident loop: from pager to postmortem to preventionmiddle
- Cache lines, struct layout, and false sharingmiddle
- SIMD, SoA vs AoS, and memory bandwidthmiddle
- Cache-oblivious algorithms, PGO, and production failuressenior
- GC in production: observability, security, edge cases, and fleet governancesenior
- Batching: amortize fixed cost per operationjunior
- The batching window: size and wait timemiddle
- Batching in Kafka and Postgresmiddle
- io_uring and observability of batchingmiddle
- From Nagle to io_uring: evolution of batchingmiddle
- Backpressure, failure isolation, and batch security in productionsenior
- CI enforcement and RUM: making budgets stickmiddle
- V8 JIT pipeline, HTTP priorities, and bundle securitysenior
- The performance loop: discipline, not a projectjunior
- Classify and fix: matching bottleneck families to remediesmiddle
- Observability stack and CI gates: catching regressions before they shipmiddle
- Incident to enforcement: SLO burn to verified fix in 35 minutesmiddle
- Culture, economics, and org-scale performancesenior
- At-most-once, at-least-once, exactly-once: the three delivery contractsjunior
- The three failure legs — where duplicates and losses actually happenmiddle
- Consumer-side dedup: the cheapest path to exactly-once processingmiddle
- Kafka exactly-once semantics: idempotent producer and transactionsmiddle
- SQS visibility timeout, DLQ, and the outbox patternmiddle
- Exactly-once in production: impossibility proof, hybrid patterns, and real incidentssenior
- What OAuth is and why passwords are not the answerjunior
- Authorization code flow with PKCEmiddle
- ID token validation and JWKS cache managementmiddle
- Refresh token rotation and scope-based least privilegemiddle
- Sender-constrained tokens: DPoP and mTLSsenior
- OAuth in production: audience attacks, observability, and real failuressenior