Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  Optimistic vs Pessimistic Locking
Engineering~9 min readComparison
Head to Head

Optimistic vs pessimistic locking: assume conflict, or hope there isn’t one?

OptimisticvsPessimistic

Two users edit the same row at the same time. You can guard against that by locking the row up front so the second user waits — or by letting both proceed and catching the collision only if it actually happens. Which is right depends almost entirely on one thing: how often those two users really do collide.

01

The one distinction that decides everything

Pessimistic locking assumes a conflict is likely, so it takes a lock before reading-to-edit — SELECT … FOR UPDATE — and anyone else who wants that row waits until the lock is released. Optimistic locking assumes conflicts are rare, so it takes no lock: it reads the row (noting a version number or timestamp), does its work, and only at write time checks "is the version still what I read?" If yes, it writes and bumps the version; if the row changed underneath it, the write is rejected and the caller retries. One prevents collisions by blocking; the other detects them after the fact.

→ The rule

Pessimistic: lock first, others wait, no wasted work — but blocking and deadlock risk. Optimistic: no lock, full concurrency — but conflicts cause retries, and lots of conflicts means lots of wasted retries. The right choice is set by how contended the data actually is.

02

Head to head

DimensionOptimisticPessimistic
When it locksNever — checks a version on writeBefore editing (up front)
AssumesConflicts are rareConflicts are likely
Under low contentionFast — no lock overheadWasteful — locks nobody contends for
Under high contentionRetry storms — wasted workSerializes cleanly — others just wait
On conflictReject & retryBlock until the lock frees
Deadlock riskNone (no locks held)Real — must order lock acquisition
Implemented withVersion / timestamp column, compare-and-swapSELECT FOR UPDATE, row locks
03

When to use each

Reach for optimistic

  • Low contention — collisions are genuinely rare
  • Reads vastly outnumber writes to the same row
  • Long "think time" between read and write (a user editing a form)
  • You want maximum concurrency and no blocking
  • Distributed systems where holding locks is costly

Reach for pessimistic

  • High contention — many writers hit the same row
  • Retrying is expensive or the work is long
  • A conflict must be prevented, not merely detected
  • Short, sharp transactions that release the lock fast
  • Hot rows (inventory counts, counters) under load
04

Contention is the deciding variable

Both schemes are correct — they prevent the lost update (two writers both reading the old value and one silently overwriting the other). The choice between them is a performance bet on contention. Under low contention, optimistic wins easily: almost every write succeeds first try, and you paid zero locking overhead for the common case. Under high contention, the bet flips: optimistic writes keep colliding and retrying, and a stampede of retries can do more wasted work than simply queueing. There, pessimistic locking serializes access cleanly — everyone waits their short turn instead of racing, failing, and racing again.

→ The cheap default

Default to optimistic (a version column) — most rows aren’t hot, and you avoid locks entirely. Switch a specific hot row to pessimistic (or an atomic operation) once you measure real contention and retry churn on it. Don’t lock the whole database for the few rows that actually fight.

05

Retry storms versus blocking and deadlocks

Each strategy has a failure mode that shows up exactly when you picked the wrong one. Optimistic locking’s is the retry storm: on a hot row, writers keep reading the same version, colliding, and retrying in lockstep — throughput collapses as everyone redoes work that keeps getting invalidated. Worse, the retries can synchronize into waves. Optimistic under high contention doesn’t corrupt data; it just melts down on throughput.

Pessimistic locking’s failure mode is blocking and deadlock: while one transaction holds a lock, others stall, so long-held locks tank concurrency — and if two transactions grab locks in different orders (A then B versus B then A), they can wait on each other forever, a deadlock the database must detect and kill. That’s why pessimistic locks want to be short-lived and acquired in a consistent order. In short: optimistic wastes work on conflict, pessimistic makes others wait and risks deadlock — pick the failure you can better afford.

→ The trade you’re actually making

Optimistic trades guaranteed progress for zero locking overhead — great until contention makes retries dominate. Pessimistic trades concurrency and deadlock-freedom for guaranteed non-collision — great until locks are held too long.

06

A worked scenario: editing a profile vs decrementing flash-sale stock

A user edits their own profile bio. Two people editing the same profile at the same second is vanishingly rare, and there’s long "think time" while they type. This is textbook optimistic: read the row with its version, save with "update … where version = N," and in the one-in-a-thousand case someone else saved first, show "this changed, please reload." No locks, full concurrency, and the rare conflict is cheap to handle.

Now decrement the stock of one hot item during a flash sale — thousands of buyers hitting the exact same row in the same instant. Optimistic here is a disaster: nearly every write collides and retries, a full-blown retry storm. This wants pessimistic locking (or, better still, a single atomic operation like UPDATE … SET stock = stock - 1 WHERE stock > 0) so the contending writers serialize cleanly instead of racing and failing. Same "update a number" operation, opposite locking choice — because the contention is opposite.

→ The pattern generalizes

Rarely-contended, think-time-heavy edits → optimistic. Hot, heavily-contended rows → pessimistic or an atomic update. Measure contention per row; don’t apply one strategy to the whole database.

The picture

The picture: two writers, one row, two strategies

Optimistic: no lock, check the version on write T1 read v=7 write WHERE v=7 1 row, v=8 T2 read v=7 write WHERE v=7 0 rows: retry T2 re-reads v=8 and redoes its work: nobody waits, work is wasted Pessimistic: lock first, others wait T1 SELECT … FOR UPDATE write COMMIT: unlock T2 FOR UPDATE blocks: waiting on T1’s row lock gets lock two transactions waiting on each other in opposite order = deadlock
Both strategies stop the lost update; they differ in who pays. Optimistic lets T2 run at full speed and charges it only when T1 got there first: its conditional UPDATE matches zero rows, and it re-reads and redoes the work. Pessimistic makes T2 wait at the door from the start, so nothing is redone, but T2’s latency is now T1’s whole transaction. Make T1 slow (a user typing, a network call) and the bottom lane gets long; make conflicts frequent and the top lane retries over and over.
Trade-offs

Cost and trade-offs: attempts, waiting and what is held

Here Time is what one write costs in attempts or waiting, and Space is what the database holds while it happens. The optimistic rows use a simple model: each try conflicts with probability p, so a write takes 1 ÷ (1 − p) attempts on average.

CaseTimeSpaceWhy
Optimistic, 1% of tries conflict1 ÷ 0.99 ≈ 1.01 attempts per writeNo lock held; one integer version column per rowThe common case. Almost every write lands first time and nobody ever waits.
Optimistic, 50% conflict2 attempts per writeNo lock, but every retry re-reads and redoes the workThroughput has halved before anything looks broken. This is the point to start measuring.
Optimistic, 90% conflict10 attempts per writeNine of every ten units of work thrown awayThe retry storm. Under real load p rises as retries pile up, so it gets worse than the model says.
Pessimistic, short transactionQueued: 100 writers on one row, 5 ms each, the last waits 99 × 5 = 495 msOne row lock per row touched, until commitNo wasted work, but latency on a hot row grows linearly with queue depth.
Pessimistic across user think timeEvery other writer waits as long as the user typesA row lock, an open transaction and a pooled connection, for minutesWhy form edits are optimistic. In PostgreSQL a long-open transaction also stops VACUUM removing dead rows.
Atomic UPDATE … SET stock = stock − 1 WHERE stock > 0One round trip; the row lock lasts one statementNothing beyond the statementBest for hot counters, but only when the new value can be computed in SQL from the old one.
FOR UPDATE NOWAIT / SKIP LOCKEDFails at once, or skips locked rows, instead of waitingOnly the rows it actually locksSKIP LOCKED lets many workers pull jobs from one table without blocking each other (PostgreSQL 9.5+, MySQL 8.0+).
SERIALIZABLE isolationRuns without row locks for plain reads; a conflicting transaction is aborted at commit or earlierThe database tracks read and write sets for youOptimistic concurrency done by the engine: it reports a serialization failure (SQLSTATE 40001) and your code must retry the whole transaction.
Across services, no shared databaseA lock service (Redis, ZooKeeper, etcd) adds a round trip and a lease to manageA lease that can expire while its holder is pausedPrefer a conditional write where the store has one: DynamoDB condition expressions or an etcd compare on a key’s revision are the version check, with no lock to lose.

The optimistic curve is flat and then a cliff: 1.01 attempts at 1%, 2 at 50%, 5 at 80%, 10 at 90%. That knee is the measured signal to move one row to a lock or an atomic statement. When you do retry, retry the whole read-modify-write, cap the attempts, and add jittered backoff so retries do not arrive in waves. The pessimistic cost is the opposite shape: it never wastes work, but every millisecond a lock is held is added to everyone queued behind it, so keep the locked section to the write itself. To find p without guessing, count the version-checked updates that matched zero rows against all of them, per table or per hot key. That ratio is your conflict rate. A rate near zero means optimistic is free; a rate climbing past a third or so on one key is the row to change.

Watch for

Common mistakes

  • Checking the version in application code

    Reading the row, comparing version == 7 in code, then writing unconditionally leaves a gap: another writer can commit between your check and your write. The check must be part of the write: UPDATE … SET …, version = version + 1 WHERE id = ? AND version = 7, then read the affected-row count. One statement is atomic; a check followed by a write is not. ORMs that support a version column (JPA’s @Version, for example) generate exactly this statement and raise an error on zero rows, which is the error you then have to handle.

  • FOR UPDATE with autocommit on

    In autocommit mode every statement is its own transaction, so the lock taken by SELECT … FOR UPDATE is released the moment that statement ends. Your later UPDATE runs unprotected. The lock only means something inside an explicit BEGIN … COMMIT that contains both the read and the write.

  • Holding a lock across a network call

    Locking the order row, calling a payment provider, then committing means every other writer to that row waits on someone else’s API, including its timeouts. Take the external call out of the transaction: record intent, commit, call out, then update the row with the result, using a version check or an idempotency key. Set a lock wait timeout as well (InnoDB’s innodb_lock_wait_timeout defaults to 50 s), so a stuck holder produces an error instead of a pile-up.

  • Locking in whatever order the code runs

    A transfer from A to B locks A then B; a transfer from B to A locks B then A. Run both at once and each waits on the other. Always lock in a fixed order, such as lowest id first. And still handle the deadlock error: the database picks a victim and aborts it (PostgreSQL checks after deadlock_timeout, 1 s by default), and that transaction must be retried, not reported as a failure.

  • A coarse timestamp as the version

    A last_modified column with one-second resolution cannot tell apart two writes in the same second, so the second write passes a check it should fail. Clock changes and replicas with skewed clocks make it worse. Use an integer that the UPDATE itself increments; it costs a few bytes and never collides.

Your call

Which would you pick?

Three situations. Pick the side you'd actually build — the explanation follows.

A wiki page edited by many users, where two people editing the same page at once is rare.

Two operators decrement the same inventory count hundreds of times a second, and conflicts are constant.

A colleague adds optimistic locking but never handles the version-conflict error, letting the write silently fail.

Frequently asked

Quick answers

What's the difference between optimistic and pessimistic locking?

Pessimistic locking takes a lock before editing a row, so anyone else who wants it waits — it assumes conflicts are likely and prevents them by blocking. Optimistic locking takes no lock: it reads a version number, does its work, and checks at write time whether the version still matches, retrying if the row changed underneath it. One prevents collisions by locking; the other detects them and retries.

Which is better?

It depends on contention. Under low contention, optimistic wins — almost every write succeeds first try with zero locking overhead. Under high contention, pessimistic (or an atomic operation) wins, because optimistic writes keep colliding and retrying. Default to optimistic and switch specific hot rows to pessimistic once you measure real contention.

How is optimistic locking implemented?

Usually with a version or timestamp column. You read the row and its version, and your write is conditional: "update … set …, version = version + 1 where id = ? and version = ?". If another writer already bumped the version, the update affects zero rows, and you know a conflict happened and retry with the fresh value. Compare-and-swap is the same idea at the value level.

What are the failure modes?

Optimistic locking under high contention causes retry storms — writers keep colliding and redoing work, collapsing throughput (though data stays correct). Pessimistic locking causes blocking and, if transactions acquire locks in different orders, deadlocks the database must detect and kill. Keep pessimistic locks short-lived and acquired in a consistent order to limit this.

▶  Watch it explained

Optimistic vs Pessimistic Locking: lock the door, or check the version

Optimistic vs Pessimistic Locking · Vibe Engines · 2026
Finished this one? 0 / 209 Handbooks done
NextThe Redis Handbook Next on the “Data, and where it lives” ladder · rung 7 of 9

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks