What is optimistic locking?

Optimistic locking is a concurrency control strategy where:

You assume conflicts are rare, so you don’t lock data upfront.
Instead, you detect conflicts at write time and fail if data was changed by someone else.

Key idea:

  • Read without lock
  • Verify nothing changed
  • Update only if version matches

How optimistic locking works (step by step)

Typical implementation: version column

id | balance | version
---+---------+--------
1  | 1000    | 7

Flow

  1. Read data:
SELECT balance, version FROM account WHERE id = 1;

Client calculates new state (balance - 100)

Update with version check:

UPDATE account
SET balance = 900,
    version = version + 1
WHERE id = 1
  AND version = 7;
  1. Check affected rows:
  • 1 row → success
  • 0 rowsconflict detected

✔ No locks
✔ No blocking
✔ Conflict detected explicitly

Why it’s called optimistic

Because the system is optimistic:

  • Assumes concurrent updates usually won’t collide
  • Pays cost only when conflict happens

Opposite of pessimistic locking.

What happens on conflict?

The application must:

  • Retry
  • Reload data
  • Or return error (409 Conflict in REST)

❗ Database does not retry for you.


Optimistic locking in ORMs (important)

JPA / Hibernate

@Version
private Long version;

Hibernate generates:

UPDATE ... WHERE id = ? AND version = ?

Throws:

  • OptimisticLockException

Optimistic vs pessimistic locking (clear comparison)

AspectOptimisticPessimistic
AssumptionConflicts are rareConflicts are common
LocksNoneExplicit locks
BlockingNoYes
ThroughputHighLower
DeadlocksNoPossible
Conflict handlingDetect & failPrevent
Retry costApplication-levelDB-level wait

When to use optimistic locking

✔ Read-heavy systems
✔ Low contention updates
✔ REST APIs
✔ Microservices
✔ UI-driven edits
✔ Distributed systems

Examples:

  • Editing user profile
  • Updating order metadata
  • Admin panels
  • CMS-like systems

When to use pessimistic locking

✔ High contention
✔ Financial operations
✔ Inventory counters
✔ Sequential workflows
✔ Strong invariants

Examples:

  • Money transfers
  • Stock decrement
  • Seat booking
  • Exactly-once payment logic

Decision rule (interview gold)

If retrying is cheap → optimistic locking
If retrying is dangerous → pessimistic locking


Very senior nuance (bonus)

You often combine them

  1. Optimistic locking for most updates
  2. Pessimistic locking for critical transitions

Example:

  • Order creation → optimistic
  • Payment capture → pessimistic

Typical interview mistakes ❌

  • “Optimistic locking is faster always” → ❌
  • “Pessimistic locking is bad practice” → ❌
  • “Transactions handle everything” → ❌
  • “Just retry automatically” → ❌

Interview-ready answer (say this)

Optimistic locking avoids locking data upfront and detects concurrent modifications using version checks at update time, making it suitable for low-contention, read-heavy systems.
Pessimistic locking locks rows before modification to prevent conflicts and is used when protecting critical invariants like balances or inventory.
The choice depends on contention level and the cost of retries.

This entry was posted in Без рубрики. Bookmark the permalink.