✏️ Explanatory Question

What is the difference between optimistic and pessimistic locking?

👁 7 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

65

What is the difference between optimistic and pessimistic locking?

Level: Advanced — A design-level concurrency question that shows architectural thinking.

These are two strategies for handling concurrent updates to the same data — they differ in when and whether they lock the resource.

  • Pessimistic Locking: Assumes conflicts will happen, so it locks the row immediately when read, blocking others until the transaction finishes. "Lock first, work later."
  • Optimistic Locking: Assumes conflicts are rare, so it doesn't lock. It checks at update time (using a version number or timestamp) whether the data changed, and rejects the update if it did. "Work first, verify later."
Key point: Optimistic locking is typically implemented at the application level using a version column, while pessimistic locking uses database locks like SELECT ... FOR UPDATE.

Side-by-Side Comparison

Feature Pessimistic Optimistic
Assumption Conflicts are likely Conflicts are rare
Locks resource? Yes, immediately No lock
Conflict check Prevents upfront Detects at update time
Concurrency Lower Higher
Deadlock risk Higher None (no locks)
Best for High-contention data Low-contention, read-heavy

Pessimistic Locking Example

-- Lock the row so no one else can modify it until we commit
START TRANSACTION;

SELECT balance FROM accounts
WHERE acc_id = 1
FOR UPDATE;              -- exclusive lock held here

UPDATE accounts SET balance = balance - 500 WHERE acc_id = 1;

COMMIT;                  -- lock released

Optimistic Locking Example (version column)

-- Table has a 'version' column
-- 1) Read the row and its current version
SELECT balance, version FROM accounts WHERE acc_id = 1;   -- version = 5

-- 2) Update ONLY if version hasn't changed since we read it
UPDATE accounts
SET balance = balance - 500,
    version = version + 1
WHERE acc_id = 1 AND version = 5;

-- 3) If 0 rows are affected, someone else updated it first -> conflict!
--    The application must re-read and retry.
Interviewer tip: The one-liner they want — "Pessimistic locking locks the row upfront (SELECT ... FOR UPDATE), assuming conflicts are likely, while optimistic locking uses a version column to detect conflicts at update time, assuming conflicts are rare. Optimistic offers higher concurrency."