Skip to main content
Web DevDatabases & CachingDiagramIntermediate

Optimistic Locking

KO: 낙관적 락 vs 비관적 락·EN: Optimistic Locking·JA: 楽観ロック(Optimistic Locking)·Optimistic Concurrency Control (OCC)

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

Pessimistic Locking vs Optimistic Locking Comparison
PessimisticPessimistic Locking

Assume conflicts · Lock on read

  • MechanismBlocks other transactions until commit
  • Trade-offDeadlock risk & lock contention
  • Best FitFlash-sale stock, seat booking
OptimisticOptimistic Locking

Assume rare conflicts · Check on write

  • MechanismUPDATE ... WHERE id=? AND version=v
  • On Conflict0 rows affected → 409 / retry
  • Best FitDocs, profiles, general SaaS edits
Quick Answer

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 Conflict so the UI can prompt the user to refresh or merge.
  • Expose optimistic concurrency over HTTP: Use ETag on GET responses and require If-Match on PUT/PATCH mutations, returning 412 Precondition Failed on 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 UPDATE or atomic conditional decrements (WHERE stock >= qty) instead.

Notable Examples

  • JPA @Version & DynamoDB ConditionExpression: 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.