Optimistic vs Pessimistic Locking in Databases
Lock and wait, or run freely and retry on conflict. Costs of each, the same update written both ways with a version column, and when to choose which.
In this chapter
Concurrency control: wait for a lock, or retry on conflict
Optimistic vs pessimistic locking: common questions
When should I use optimistic locking?
When conflicts are rare. Read with a version number, then UPDATE … WHERE version = ?; if no row changed, someone else won and you retry.
More on Transactions: locks and production
Keep learning
Overview
chapters · transactions, isolation and locks Concurrency control: wait for a lock, or retry on conflict Two writers hit one row: the engine either makes one wait, or lets both run and rejects one at commit. The promise you get. → isolation levels Locks, validation, timestamps, versions.
1. The map
🔒 Pessimistic Expects conflict. Locks first. Others wait. 🚀 Optimistic family tree of concurrency control concurrency control node bad prevent conflicts node ok detect conflicts locks (2PL) validate at commit timestamp order either style MVCC: layered on top of any MVCC answers Which version does a reader see? Locks / validation / timestamps answer What happens when two writers collide?
2. Pessimistic or optimistic depends on collisions
Slide from rare to frequent conflicts. Which style wastes less work? 🔒 Pessimistic: lock, then work Hot rows, inventory, balances, retries that are costly or have side effects. 🚀 Optimistic: work, then check Read-heavy, rare conflicts, long think time (form open for minutes). What each style costs Pessimistic (locks) Optimistic (check at commit) Under conflict Second tx waits One tx fails, rerun Read/write sets or versions, checked once Failure modes Long waits, timeouts, deadlocks Wasted work, retry storms on hot rows Your code must Keep tx short, lock in one order Catch error, retry whole unit Common blend Hot row kills optimistic Everyone retries at once. → hotspot updates NoSQL leans optimistic Compare-and-set: write rejected if version moved. PostgreSQL SERIALIZABLE Optimistic: detects conflict, fails one tx. MySQL / SQL Server SERIALIZABLE Built from locks. Relational writes Lean pessimistic.
3. What each style looks like from your code
Same read-change-write on stock row 7, both ways. Session A Session B Pessimistic: B waits for A's lock SELECT qty … WHERE id=7 FOR UPDATE locks row 7 lock released Optimistic SERIALIZABLE: B fails and loops SELECT qty WHERE id=7 no lock UPDATE … SQLSTATE 40001 reads 4 now Retry is not optional Innocent tx get rejected: "might succeed if retried". → write anomalies · serializability
4. Optimistic control in three phases
optimistic phases 1. read + work node ok 2. validate 3. write fail here → restart T1 changes some items. Pick what T2 read: does T2 pass or restart? Private copies Abort throws away only private state. Else two tx both validate, then both write.
5. Timestamp ordering: decide the order up front
Tx starts gets timestamp n Order fixed as if run by n Item keeps RTS (youngest reader) · WTS (youngest writer) Out-of-order op refused → abort Step through a schedule. Which late op is refused? What does the Thomas rule change? The two rules Allowed if Tn reads X n ≥ WTS(X) Abort: value it should see is gone Tn writes X n ≥ RTS(X) and n ≥ WTS(X) Abort (Thomas rule: skip blind write) No locks, no deadlocks But many aborts on hot overlapping data. Reads write metadata Each read updates RTS. Distributed (Spanner-style)
6. Versions on top
MVCC keeps old row versions so readers see a snapshot and never wait for writers. 🐘 PostgreSQL 🐬 InnoDB / Oracle Real engines are combinations Writer vs writer InnoDB (read views) Snapshot (MVCC) PostgreSQL (tuples) Multiversion timestamp ordering Version at its timestamp Timestamp rules Optimistic stores / many KV Version or snapshot Version check at commit Storage + cleanup. Long reader Holds back all cleanup. → tx mistakes → MVCC · undo log
Remember
More collisions Retry loop Required for optimistic/serializable. FOR UPDATE waits instead. Per layer Locks in DB, version columns in app.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.