Skip to content
We areTOP 1%

What is the difference between optimistic and pessimistic concurrency control?

MediumConceptConcurrency Control & Locking
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

Answer

Pessimistic concurrency control assumes conflicts are likely, so it locks data before using it and makes other transactions wait. Optimistic concurrency control assumes conflicts are rare: transactions work without locks and check for conflicts only when they try to commit.

  • Pessimistic: 2PL and SELECT ... FOR UPDATE. It is safe under heavy contention but reduces concurrency and can deadlock.
  • Optimistic: read, compute, then validate. If another transaction changed the data in the meantime, the write is rejected and retried. There are no deadlocks, but frequent conflicts cause many retries.
  • Timestamp ordering is a related protocol without locks: each transaction gets a timestamp, and an operation that arrives out of timestamp order causes its transaction to roll back.
  • Optimistic control suits low-contention edits, such as profile updates; pessimistic control suits hot rows, such as the last seats on a flight.

Example: An optimistic update with a version column:

-- read earlier: id = 7, stock = 5, version = 3
UPDATE items SET stock = 4, version = 4
WHERE id = 7 AND version = 3;
-- 0 rows affected: someone else updated first, so re-read and retry

More in Concurrency Control & Locking

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account