Optimistic vs Pessimistic Locking: How to Explain It in an Interview

"Two users edit the same record at the same time. What happens?" This comes up in backend and system design interviews constantly, often disguised as a ticket-booking or inventory question. The answer interviewers want is a comparison of two concurrency strategies and when you'd choose each.

The lost update problem

Alice and Bob both read a product with stock = 5. Alice sells 2 and writes 3. Bob sells 1 and writes 4. Final stock: 4, though 3 units left the warehouse. Nothing crashed; one update silently overwrote the other. Name this problem first: it shows you know what you're protecting against.

Pessimistic locking: block first

Assume conflict is likely and take a lock before reading:

BEGIN;
SELECT stock FROM products WHERE id = 42 FOR UPDATE;
UPDATE products SET stock = stock - 2 WHERE id = 42;
COMMIT;

Bob's SELECT ... FOR UPDATE waits until Alice commits. Correct, but every writer queues behind the lock, and holding locks across slow work (or user think-time) wrecks throughput and invites deadlocks.

Optimistic locking: check at write time

Assume conflict is rare. Add a version column, read without locking, and make the write conditional:

UPDATE products
SET stock = 3, version = version + 1
WHERE id = 42 AND version = 7;

If zero rows were updated, someone else got there first: reload and retry, or tell the user. No locks are held between read and write, so it scales well and suits long-lived edits like forms or documents.

How to choose (the part being graded)

A strong closing line

"For inventory I'd start with an atomic conditional update, SET stock = stock - 2 WHERE stock >= 2, which avoids both explicit locks and version checks for this simple case. I'd move to versioned optimistic locking for edits users make over minutes, and to a per-item queue if a single hot item caused heavy retries." It shows you know the third option many candidates miss.


Disclosure: I work on an AI interview assistant at Linkjob AI. This explanation stands on its own.