Correctness under concurrency · senior
Locking, oversell and optimistic concurrency
To stop two buyers taking the last item, either make the change atomic in one statement (UPDATE ... SET qty = qty - 1 WHERE qty > 0), lock the row while you decide (SELECT ... FOR UPDATE), or use optimistic concurrency with a version column, and keep a consistent lock order to avoid deadlocks.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Read-then-write in application code (read qty, check, write qty - 1) races under concurrency and oversells.
- Atomic conditional update: UPDATE stock SET qty = qty - 1 WHERE sku = $1 AND qty > 0; check the affected row count (0 = sold out). Simplest and fastest.
- Pessimistic lock: SELECT ... FOR UPDATE inside a transaction locks the rows until commit; others wait. FOR UPDATE SKIP LOCKED lets many workers each take different rows (a job queue in Postgres).
- Optimistic lock: add a version column; UPDATE ... SET ..., version = version + 1 WHERE id = $1 AND version = $2; 0 rows updated = someone else changed it -> reload and retry or show a conflict (HTTP 409/412 with ETag/If-Match).
- Deadlocks: two transactions lock rows in opposite orders. Lock in a consistent order (sort ids), keep transactions short; Postgres detects deadlocks and aborts one transaction.
- Distributed locks (Redis SET NX PX) are for coordinating work across services, not a replacement for database constraints.
The red pen
Common traps: mistake → fix
Mistake: Check stock in a SELECT, then UPDATE, and it is safe because both are fast
Fix: two requests can pass the check at the same moment.
Mistake: FOR UPDATE outside a transaction protects the row
Fix: the lock is released at the end of the statement's transaction (immediately with autocommit).
Easy to hard
Questions interviewers ask, easy to hard
- Flash sale: 1 item left and 1,000 buyers. How do you make sure only one gets it?
- Pessimistic vs optimistic locking: when do you use each?
- What is SELECT ... FOR UPDATE SKIP LOCKED good for?
- What is a deadlock and how do you avoid one?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.