Optimistic and pessimistic locking

Two strategies for concurrent updates: lock first, or detect conflicts at the end and retry.

On the roadmap:Intermediate · step 1: Faster queries

Lesson 3 of 23 · 6 min read · quiz · exercise

The problem

Two users load the same record, both change it, both save. Without protection the later save silently overwrites the earlier one (a lost update). Two families of solutions exist.

A railway signal: only one train may hold a stretch of track at a time, just as a lock admits one writerImage: Svetlov Artem · CC0 · Source · Wikimedia Commons: RZD Selizarovo 2016-08 searchlight signal 2

Pessimistic locking: assume conflict

Lock the data before changing it, so others must wait.

BEGIN;
SELECT * FROM seats WHERE id = 7 FOR UPDATE;  -- others block here
UPDATE seats SET taken = true WHERE id = 7;
COMMIT;
  • Safe and simple to reason about.
  • Cost: waiting, reduced throughput, risk of deadlock, and trouble if the lock is held while waiting for a user.

Optimistic locking: assume no conflict, check at the end

Read freely, and when saving check nothing changed.

UPDATE pages SET body = :new, version = version + 1
WHERE id = 5 AND version = :versionIRead;
-- 0 rows updated means someone else saved first
  • No locks held while the user thinks.
  • Cost: on conflict the work is rejected and must be retried or merged. Under heavy contention many attempts fail.

Before: pessimistic: lock first

After: optimistic: check at the end

What changed

  • Pessimistic makes others wait, optimistic lets them all try
  • Optimistic rejects a stale save instead of overwriting it
  • Optimistic wastes work only when a conflict really happens

Optimistic locking in action

Figure SDA-CORE-03-1 · Two writers with a version check · © forcsguy.com

Choosing

OptimisticPessimistic
Conflictsrarefrequent
Lock durationnonewhole transaction
Failure moderetry or mergewaiting, deadlocks
Good forediting, profiles, most web appsinventory, seat booking, money moves

Beyond one database

For resources not in a database (a file, an external job), use a distributed lock or a lease, covered in a later lesson. They need extra care because the lock holder can crash or stall.

Real-world reading

Check your understanding

Question 1 of 3

0 correct so far

How does optimistic locking detect a conflict?

© 2026 forcsguy.com. Original lesson text and diagrams. Books and sites linked above belong to their authors.