Overview
Pessimistic locking assumes conflicts are likely: acquire a lock on the row, do the work, release — others wait. It is safe but reduces concurrency and risks deadlocks. Optimistic locking assumes conflicts are rare: read a version/timestamp, do the work, and on write verify the version is unchanged; if it changed, retry. It maximizes concurrency but you must handle retries.
Optimistic locking vs Pessimistic locking: key differences
| Optimistic locking | Pessimistic locking | |
|---|---|---|
| Assumes | Conflicts rare | Conflicts likely |
| Mechanism | Version/timestamp check on write | Acquire lock, others wait |
| Concurrency | High | Lower |
| Cost on conflict | Retry | Blocking / deadlock risk |
| Best for | Low-contention, web apps | High-contention, short critical sections |
When to use Optimistic locking
Low-contention data and web-scale reads/writes where blocking would hurt throughput — accept occasional retries.
When to use Pessimistic locking
High-contention hotspots or operations that must not be retried, where blocking is cheaper than repeated conflict.
Verdict
Default to optimistic locking for web workloads (a version column + retry) — it scales better. Use pessimistic locks for genuinely high-contention rows or critical sections that cannot tolerate retries.
Common questions
What is the difference between optimistic and pessimistic locking?
Optimistic lets transactions proceed and checks for conflicts at commit (via a version), retrying on clash. Pessimistic locks the data upfront so others wait. Optimistic scales better under low contention.
When is pessimistic locking better?
Under high contention, where optimistic locking would cause many retries — a short pessimistic lock can be cheaper and more predictable.