SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Common Database Types
  • SQL vs NoSQL
  • ACID Transactions
  • B-Trees and B+ Trees
  • LSM Trees
  • Transaction Isolation Levels
  • Locking and MVCC
  • Normalization
  • OLTP vs OLAP
  • BASE and PACELC
  • Write-Ahead Log (WAL)
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Basics

Locking and MVCC

Pessimistic and optimistic locking, and how MVCC lets readers and writers work without blocking each other.

โฑ 15 min readAdvancedMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

When many users change the same data, the database needs a rule to keep them from stepping on each other. There are two big families of rules: locking and MVCC.

  • Pessimistic locking assumes a clash will happen: lock the row first, make others wait.
  • Optimistic locking assumes clashes are rare: do the work without a lock, and check at the end that nobody else changed the row. If they did, retry.
  • MVCC (multi-version concurrency control) keeps several versions of each row, so readers do not block writers and writers do not block readers.

02Concept: What is it?

Think of one row, a bank balance of 100. Two users both want to add money. If both read 100 and each write their own total, one update is lost. We need a way to make them take turns, or to notice the clash.

Pessimistic locking

"Lock first, work second." A transaction takes a lock on the row before it reads it for update. Anyone else who wants the same row waits until the lock is released at commit or rollback. A shared lock allows many readers. An exclusive lock allows one writer and blocks everyone else.

Pessimistic: lock the row while you work
BEGIN;
SELECT balance FROM accounts WHERE id = 7 FOR UPDATE;  -- others wait here
UPDATE accounts SET balance = balance + 10 WHERE id = 7;
COMMIT;                                                 -- lock released

Optimistic locking

"Work first, check at the end." Each row has a version number (or a timestamp). You read the row with its version, do your work, then write only if the version is still the same. If another user got there first, zero rows change and you retry.

Optimistic: no lock, check the version when saving
UPDATE accounts
SET balance = 110, version = version + 1
WHERE id = 7 AND version = 1;     -- 0 rows changed? someone beat you, retry

MVCC

Instead of one value per row, the database keeps versions. A write creates a new version rather than overwriting. Each transaction sees a snapshot: the versions committed before it started (or before its statement began, depending on the level). Readers read old versions while writers add new ones, so neither waits for the other.

Locking and MVCC side by side
Locking
โœ๏ธWriterholds lock
๐Ÿ“–Readerโณ waits
๐Ÿ—„๏ธOne value
MVCC
โœ๏ธWriteradds v3
๐Ÿ“–Readerreads v2
v1
v2
v3
With locks, a reader waits for the writer. With MVCC, the reader reads the old version and carries on.
๐Ÿง MVCC does not remove all conflicts
Two writers changing the same row still clash. MVCC removes the reader-versus-writer waiting. Writer-versus-writer conflicts still need locks, or a check that aborts one of them.

03Real-Life Example

๐ŸตThe Shared Recipe Card
A family keeps one recipe card on the fridge. With a pessimistic rule, whoever wants to edit it takes the card and hangs a "busy" sign. Others wait. With an optimistic rule, each person copies the card, edits their copy, and when they put it back they check that nobody changed the original. If someone did, they redo their edit. With MVCC, every edit makes a new card and the old ones stay in a box with dates. Anyone reading just picks the newest card that existed when they started.
Recipe card
Database
The โ€œbusyโ€ sign
A row lock
Waiting for the sign to come down
Lock wait (and a timeout or deadlock if it goes wrong)
Checking the original before putting your copy back
A version check at write time
Redoing your edit
A retry after a conflict
Each edit is a new dated card
A new row version
Picking the newest card from before you started
Reading from a snapshot
Throwing out very old cards
Vacuum or purge of dead versions
The life of one optimistic update
๐Ÿ“–Readvalue + version
โ†’โ†“
๐ŸงฎComputeno lock held
โ†’โ†“
๐Ÿ’พWrite if version same
โ†’โ†“
โœ…1 row changed
๐Ÿ”0 rows: retry

04Why Do We Need It?

๐ŸงฏStop lost updates
Two writers must not silently overwrite each other.
๐ŸšฆKeep readers fast
MVCC lets long reads and busy writes share the same table without waiting.
๐ŸŽฏPick the right tool
Heavy contention suits locks. Rare contention suits version checks.
๐Ÿ“ธStable views
A snapshot gives a report one consistent picture, even while data changes.
๐Ÿง Clear rules
Knowing the mechanism tells you which anomalies you can still see.
๐Ÿ“ˆMore throughput
Less blocking means more transactions per second.
Locks make others wait. Versions let others carry on. Pick the one that matches how often your users clash.

05Where Do We Use It?

๐Ÿ˜PostgreSQL
Built on MVCC. Readers do not block writers, and a cleanup process (vacuum) removes dead versions.
๐ŸฌMySQL (InnoDB)
Uses MVCC for reads and row locks for writes.
๐Ÿ›’Inventory and tickets
SELECT FOR UPDATE on the stock row, so two buyers cannot take the last item.
๐Ÿ“Editing screens
A version column warns a user that someone else saved first. Long forms suit optimistic checks.
๐ŸŒHTTP APIs
ETag and If-Match headers apply the same optimistic idea over HTTP.
๐ŸงฐORMs
Many ORMs have a built-in version column feature for optimistic locking.

06Types / Parts / How It Works

Pessimistic vs optimistic

PessimisticOptimistic
IdeaLock first, so nobody can clashCheck at the end, and retry on a clash
Lock held during the workYesNo
Good whenClashes are common, work is short, correctness is criticalClashes are rare, work is long (like a user filling a form)
Bad whenLocks are held too long, or lock order differs (deadlocks)Clashes are frequent, so retries pile up
CostWaitingWasted work and retries

Kinds of locks

LockWho can share itUsed for
Shared (read) lockMany readers at once, no writerReading data that must not change meanwhile
Exclusive (write) lockOne holder, nobody elseChanging a row
Row lock vs table lockRow locks are fine-grained, table locks block everythingPrefer row locks. Table locks are for maintenance
Range or gap lockProtects a range of keysStopping phantoms in some databases

How MVCC works, in four lines

Versions and snapshots
โœ๏ธWritecreates a new version
โ†’โ†“
๐Ÿ“ธSnapshotwhich versions are visible
โ†’โ†“
๐Ÿ“–Readnewest visible version
โ†’โ†“
๐ŸงนCleanupremove old versions
Writer Reader Housekeeping
Each transaction gets a snapshot. It reads the newest version committed before that snapshot.
โš ๏ธDeadlocks
If transaction 1 locks row A then wants B, while transaction 2 locks B then wants A, both wait forever. Databases detect this and abort one. You avoid it by locking rows in the same order and keeping transactions short.
VisualizerNo control, a lock, or a version check, plus MVCC snapshotsStep through two users adding to the same balance in each mode. Then move the snapshot slider and see which version a reader gets.
How do two users share one row?
User A (+10)
read โ†’ 100
User B (+20)
โ€ฆ
Row in the database: balance = 100
Step 1 of 4
A reads the balance
A reads 100 and plans to add 10.
Lost update: the final balance is 120, but 130 was correct. A's +10 vanished.
MVCC: many versions of one row
VersionValueWritten byCommitted atThis reader
v1100T10t = 12older version, skipped
v2110T20t = 24reads this one
v3130T30t = 36not committed yet, invisible
A reader whose snapshot is at t = 26 sees 110. Writers can keep adding new versions without blocking this reader, and the reader never blocks them. 1 older version is now dead weight until the cleanup job (vacuum or purge) removes them.

A simplified teaching model with made-up times and values. Real databases use transaction ids and visibility rules, and clean up old versions in the background.

07How to Use It / Steps / Implementation

Using locks and versions well

  1. 1
    Prefer an atomic update
    UPDATE accounts SET balance = balance + 10 does the read and write in one step, and needs no explicit lock for simple counters.
  2. 2
    Use SELECT FOR UPDATE for read-then-decide
    When you must read, think, then write, lock the row you read so nobody can change it in between.
  3. 3
    Add a version column for user edits
    Store a version or updated_at. Save with WHERE version = ?. If 0 rows change, tell the user or retry.
  4. 4
    Keep locks short
    Take the lock late and release it early. Do not call other services or wait for a user while holding it.
  5. 5
    Lock in a fixed order
    Always lock rows in the same order (for example by id) so two transactions cannot wait on each other.
  6. 6
    Set timeouts and retry
    Use a lock timeout, and retry deadlock or version-check failures a few times with back-off.
  7. 7
    Watch for old versions
    Long-running transactions keep old row versions alive. Monitor and keep transactions short, so cleanup can do its job.
๐Ÿ’กSame idea over HTTP
An API can return an ETag, and the client can send If-Match when updating. If the version no longer matches, the server answers 412 Precondition Failed. This is optimistic locking across the network.

08Key Terms to Know

TermMeaning in easy words
LockA flag on data that makes others wait or stay out
Shared lockA read lock that many transactions can hold together
Exclusive lockA write lock that only one transaction can hold
Pessimistic lockingLock first, because a clash is expected
Optimistic lockingDo not lock, check for a clash when saving
Version columnA number that goes up on every change, used to detect clashes
MVCCKeeping several versions of each row, so readers and writers do not block each other
SnapshotThe set of row versions a transaction can see
DeadlockTwo transactions each wait for a lock the other holds
Vacuum / purgeBackground cleanup of row versions nobody can see any more
Lock timeoutHow long a transaction waits for a lock before giving up

09Pros, Cons and Trade-offs

โœ… Pros
  • Locks give a simple, strong guarantee
  • Version checks hold no locks, so they scale well
  • MVCC lets readers and writers work together
  • Snapshots give reports a steady view
  • Built into the main databases and ORMs
โš ๏ธ Cons
  • Locks cause waiting and deadlocks
  • Optimistic checks waste work when clashes are frequent
  • MVCC stores extra versions and needs cleanup
  • Write-write conflicts still need handling
  • Behaviour differs between databases

Trade-offs

ChoiceWe gainWe lose
Pessimistic lockNo lost updates, simple to reason aboutWaiting, deadlock risk, lower concurrency
Optimistic checkNo lock held, great for rare clashesRetries and wasted work under heavy contention
MVCC readsReaders never wait for writersExtra storage and cleanup work
Row-level locksFine-grained, many users in parallelMore lock bookkeeping
Table-level locksVery simpleEveryone else waits
Long transactionsBigger all-or-nothing unitsOld versions pile up, locks held long

10Common Problems and Mistakes

Common mistakes

  1. Read, then write, with no guard. This is the classic lost update.
  2. Locking too much. A table lock, or a lock held during a slow API call, stops everyone.
  3. Different lock orders. Two code paths locking the same rows in opposite order deadlock under load.
  4. Optimistic locking with no retry. A failed version check must lead to a retry or a clear message, not a silent loss.
  5. Forgetting the version check on one code path. One writer that skips it breaks the protection for everyone.
  6. Long transactions with MVCC. They keep old versions alive and bloat tables.
  7. Thinking MVCC makes writes safe. It removes read-write blocking only. Two writers still need protection.

Things to watch

๐Ÿ’€Deadlock errors
Log them and retry. Frequent deadlocks point to inconsistent lock order.
โณLock waits
Watch for transactions waiting a long time. Find who holds the lock.
๐ŸงนTable bloat
Dead row versions pile up if cleanup falls behind or transactions never end.
๐Ÿ”Retry storms
Many version-check failures at once can overload the system. Add back-off.

11Real-World Examples

๐Ÿ˜PostgreSQL
Every update writes a new row version, and vacuum cleans up the old ones. Readers use snapshots.
๐ŸŽซTicket sales
Lock or conditionally update the seat row so only one buyer gets the last seat.
๐Ÿ“„Collaborative forms
A version number tells you someone else saved first, and offers to merge or reload.
๐ŸงฐORMs
Many frameworks expose a version attribute for optimistic locking.
๐ŸŒREST APIs
ETag with If-Match lets web clients update safely.
๐Ÿ“ŠLong reports
A report reads a snapshot for minutes while the shop keeps selling.
๐Ÿ“Note
Details such as lock names, default levels and cleanup settings vary by database and version. Use the documentation for your product.
Mini case: two buyers, one last ticket
๐Ÿ‘คBuyer 1
๐Ÿ‘คBuyer 2
โ†’โ†“UPDATE ... WHERE seats > 0
๐Ÿ—„๏ธDatabaseone at a time
โ†’โ†“
โœ…1 row changed: sold
๐Ÿ™0 rows: sold out
A conditional update turns a race into one winner and one clear answer.

12Related Topics to Read Next

ACID Transactionsโ†’

Locks and MVCC are how isolation is delivered.

Transaction Isolation Levelsโ†’

Which problems each level still allows.

Relational Databasesโ†’

The databases that use these mechanisms most.

Write-Ahead Log (WAL)โ†’

How changes survive a crash while versions pile up.

Idempotencyโ†’

Safe retries after a failed version check.

Distributed Locksโ†’

The same idea across many machines, and why it is harder.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Pessimistic: lock first (SELECT FOR UPDATE). Others wait. Watch deadlocks.
  • โœ”Optimistic: version column, UPDATE ... WHERE version = ?. 0 rows means retry.
  • โœ”MVCC: many row versions, snapshot reads, readers and writers do not block each other.
  • โœ”Still needed: writer-versus-writer conflicts need locks or aborts.
  • โœ”Cleanup: old versions need vacuum or purge. Long transactions block it.
  • โœ”Deadlock cure: same lock order, short transactions, timeouts, retry.
  • โœ”Simple counters: use an atomic UPDATE (balance = balance + 10).
  • โœ”One line: "Locks make others wait, versions let them carry on."
โ† Previous
Transaction Isolation Levels
Next โ†’
Normalization