Optimistic vs Pessimistic Locking — What's the Difference?

Pessimistic locking prevents conflicts by locking a record before making changes, blocking other transactions from touching it until the lock is released; op...

Published November 23, 2026

Pessimistic locking locks a record while someone edits it so no one else can change it; optimistic locking lets everyone read and edit, then checks at save time whether the record changed and rejects conflicting writes. Optimistic suits low contention, pessimistic suits high contention.

The concept

Pessimistic: SELECT ... FOR UPDATE holds a lock until commit. Safe but can cause waiting and deadlocks.

Optimistic: store a version number or updated_at; UPDATE ... WHERE id = ? AND version = ?. If zero rows update, someone else changed it and the app retries or reports a conflict.

Conflict detection

A reads v1 B reads v1
A saves → version 1→2 ✓
B saves → WHERE version=1 matches 0 rows ✗ conflict

Practical examples

Pessimistic

START TRANSACTION;
SELECT * FROM stock WHERE id = 1 FOR UPDATE;
UPDATE stock SET qty = qty - 1 WHERE id = 1;
COMMIT;

Optimistic

UPDATE docs SET body = ?, version = version + 1 WHERE id = ? AND version = ?;

Handle the conflict

const r = await update(doc)
if (r.affectedRows === 0) throw new Error('Edited by someone else — reload and retry')

Common mistakes

  • Optimistic locking with high contention (constant retries).
  • Holding pessimistic locks during user think time.
  • Not retrying after a conflict.

Key takeaways

  • Pessimistic = lock first, optimistic = check at save.
  • Pick by contention level.
  • Keep locks short.

FAQ

Which is faster?

Optimistic when conflicts are rare.

Where is optimistic used?

ETag/If-Match in HTTP, ORM version columns.

More SQL articles