Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Optimistic vs pessimistic locking: assume conflict, or hope there isn’t one?
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.
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.
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.
Head to head
| Dimension | Optimistic | Pessimistic |
|---|---|---|
| When it locks | Never — checks a version on write | Before editing (up front) |
| Assumes | Conflicts are rare | Conflicts are likely |
| Under low contention | Fast — no lock overhead | Wasteful — locks nobody contends for |
| Under high contention | Retry storms — wasted work | Serializes cleanly — others just wait |
| On conflict | Reject & retry | Block until the lock frees |
| Deadlock risk | None (no locks held) | Real — must order lock acquisition |
| Implemented with | Version / timestamp column, compare-and-swap | SELECT FOR UPDATE, row locks |
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
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.
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.
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.
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.
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.
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: two writers, one row, two strategies
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.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.
| Case | Time | Space | Why |
|---|---|---|---|
| Optimistic, 1% of tries conflict | 1 ÷ 0.99 ≈ 1.01 attempts per write | No lock held; one integer version column per row | The common case. Almost every write lands first time and nobody ever waits. |
| Optimistic, 50% conflict | 2 attempts per write | No lock, but every retry re-reads and redoes the work | Throughput has halved before anything looks broken. This is the point to start measuring. |
| Optimistic, 90% conflict | 10 attempts per write | Nine of every ten units of work thrown away | The retry storm. Under real load p rises as retries pile up, so it gets worse than the model says. |
| Pessimistic, short transaction | Queued: 100 writers on one row, 5 ms each, the last waits 99 × 5 = 495 ms | One row lock per row touched, until commit | No wasted work, but latency on a hot row grows linearly with queue depth. |
| Pessimistic across user think time | Every other writer waits as long as the user types | A row lock, an open transaction and a pooled connection, for minutes | Why form edits are optimistic. In PostgreSQL a long-open transaction also stops VACUUM removing dead rows. |
Atomic UPDATE … SET stock = stock − 1 WHERE stock > 0 | One round trip; the row lock lasts one statement | Nothing beyond the statement | Best for hot counters, but only when the new value can be computed in SQL from the old one. |
FOR UPDATE NOWAIT / SKIP LOCKED | Fails at once, or skips locked rows, instead of waiting | Only the rows it actually locks | SKIP LOCKED lets many workers pull jobs from one table without blocking each other (PostgreSQL 9.5+, MySQL 8.0+). |
SERIALIZABLE isolation | Runs without row locks for plain reads; a conflicting transaction is aborted at commit or earlier | The database tracks read and write sets for you | Optimistic concurrency done by the engine: it reports a serialization failure (SQLSTATE 40001) and your code must retry the whole transaction. |
| Across services, no shared database | A lock service (Redis, ZooKeeper, etcd) adds a round trip and a lease to manage | A lease that can expire while its holder is paused | Prefer 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.
Common mistakes
- Checking the version in application code
Reading the row, comparing
version == 7in 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 UPDATEis released the moment that statement ends. Your laterUPDATEruns unprotected. The lock only means something inside an explicitBEGIN … COMMITthat 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_timeoutdefaults 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_modifiedcolumn 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 theUPDATEitself increments; it costs a few bytes and never collides.
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.
When conflicts are rare, locking makes every writer pay for a collision that almost never happens — and a held lock blocks readers-turned-writers behind someone who wandered off mid-edit. Optimistic concurrency pays only on the rare conflict, which is exactly the shape of this workload.
Two operators decrement the same inventory count hundreds of times a second, and conflicts are constant.
Optimistic concurrency assumes conflicts are the exception. Under constant contention most writes fail and retry, so you burn work repeatedly and throughput collapses — backoff makes it slower still without making it succeed. A lock serialises the contended row once and gets on with it.
A colleague adds optimistic locking but never handles the version-conflict error, letting the write silently fail.
Optimistic locking does not prevent conflicts; it detects them and hands you the decision of what to do — retry, merge, or ask the user. Skipping that leaves you with detection and no resolution, which is a lost update wearing a version number. Logging records the data loss rather than avoiding it.
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.
Optimistic vs Pessimistic Locking: lock the door, or check the version
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The System Design Fundamentals HandbookThe load-bearing ideas behind every distributed system — the CAP theorem and consistency models, concurrency and locking, partitioning and replication, and consensus and coordination — each tied to a real worked design you can study interactively.Read →
- CAP Theorem & Consistency ModelsWhat a distributed system can promise when the network splits — CP vs AP, why "CA" is a myth, PACELC, and the full spectrum from linearizable to eventual consistency. Part of System Design Fundamentals.Read →
- Partitioning, Sharding & ReplicationHow one dataset becomes many — range vs hash partitioning, consistent hashing and virtual nodes, hot partitions, replication topologies, replication lag, and quorums. Part of System Design Fundamentals.Read →
- Consensus, Transactions & CoordinationHow nodes that can crash still agree on one truth — majority quorums, Raft and Paxos, leader election, two-phase commit vs the saga pattern, and idempotency for exactly-once effects. Part of System Design Fundamentals.Read →
- The Kubernetes HandbookThe one idea under all the YAML — declare desired state, and a control loop makes reality match. Covers the orchestration problem, pods, deployments and replicasets, services and networking, the reconciliation loop and self-healing, the scheduler, config/secrets and health probes, autoscaling, and when you actually need Kubernetes.Read →
- The Observability HandbookSeeing inside production — monitoring vs observability, the three pillars (metrics, logs, traces) and what each answers, structured logging, metric types and the cardinality trap, distributed tracing, the golden signals and SLIs/SLOs/error budgets, alerting on symptoms not causes, and correlating all three during an incident.Read →