← Back to SQL, page 23

sql-0453 · Medium mid

What is optimistic concurrency control, and how does it compare with locking rows up front?

Optimistic control lets transactions proceed without locks and checks at write time that the row has not changed, typically with a version column in the UPDATE's WHERE clause; zero rows updated means a conflict to retry or report. Pessimistic control locks rows first (SELECT ... FOR UPDATE), making others wait. Optimistic suits low-conflict, user-facing edits; pessimistic suits short, high-conflict updates.

Full answer

Optimistic, with a version column:

text
SELECT id, title, version FROM docs WHERE id = 7;        -- version = 3
UPDATE docs SET title = :t, version = version + 1 WHERE id = 7 AND version = 3;

If another user saved first, version is now 4, the UPDATE affects 0 rows, and the app shows 'this document changed, reload'. No locks are held while the user edits for minutes.

Pessimistic:

text
BEGIN; SELECT ... FROM accounts WHERE id = 7 FOR UPDATE; UPDATE ...; COMMIT;

Others wanting the row wait until commit. Good for short operations with frequent contention, such as decrementing stock, but holding locks across user think-time blocks everyone.

Trade-offs: optimistic control wastes work on conflict (retries), pessimistic control risks waits and deadlocks. Many systems use both: optimistic for forms, atomic updates or short locks for counters and balances.

Key points

  • Optimistic checks a version at write time
  • Zero rows updated signals a conflict
  • Pessimistic locks rows before changing them
  • Optimistic suits long user edits
  • Pessimistic suits short contended updates

Common mistakes

  • Holding row locks while a user edits a form
  • Ignoring the affected row count in optimistic updates

Follow-ups

  • Can a timestamp replace a version number?
  • How do ORMs implement optimistic locking?

Tips

  • Show the version check