Optimistic Locking
A concurrency control strategy that avoids holding DB locks by checking a version or timestamp column on update, preventing lost updates with high throughput
Table of Contents
Structure Diagram
Assume conflicts · Lock on read
- MechanismBlocks other transactions until commit
- Trade-offDeadlock risk & lock contention
- Best FitFlash-sale stock, seat booking
Assume rare conflicts · Check on write
- MechanismUPDATE ... WHERE id=? AND version=v
- On Conflict0 rows affected → 409 / retry
- Best FitDocs, profiles, general SaaS edits
What is Optimistic Locking?
A concurrency control strategy that avoids holding DB locks by checking a version or timestamp column on update, preventing lost updates with high throughput. It is a core concept in Databases & Caching within Web Dev.
Core Principles
When two users load the same record and save edits concurrently, the second write can silently overwrite the first—a bug known as a Lost Update.
Optimistic Locking assumes conflicts are rare and avoids holding expensive database locks during reads. Tables include a version integer (or timestamp); updates run conditionally (UPDATE items SET price = 500, version = version + 1 WHERE id = 1 AND version = 3). If another transaction already bumped the version to 4, zero rows match and the conflict is caught cleanly.
Practical Takeaways
- Define conflict recovery upfront: For automated backend jobs, reload fresh state and retry 2–3 times with jitter; for human-edited forms, return
409 Conflictso the UI can prompt the user to refresh or merge. - Expose optimistic concurrency over HTTP: Use
ETagonGETresponses and requireIf-MatchonPUT/PATCHmutations, returning412 Precondition Failedon mismatch. - Know when to switch to Pessimistic Locking: Under extreme contention on a single hot row (e.g., flash-sale inventory), optimistic retries thrash the DB—use
SELECT ... FOR UPDATEor atomic conditional decrements (WHERE stock >= qty) instead.
Notable Examples
- JPA
@Version& DynamoDBConditionExpression: First-class optimistic concurrency built into enterprise ORMs and NoSQL stores. - CMS, wikis, and issue trackers: Preventing concurrent editors from silently clobbering each other's updates.