Optimistic vs Pessimistic Locking: How Databases Prevent Lost Updates
Why two users buying the last concert seat at the same millisecond causes a Lost Update, and how SELECT FOR UPDATE vs atomic version checks solve it.
Imagine one VIP concert seat (#A1) is left, and two users (User A and User B) click Buy at the exact same millisecond (12:00:00.001).
Without database-level concurrency control, both backend servers read stock = 1, both pass your application’s if (stock > 0) check, both charge Stripe, and both execute UPDATE seats SET stock = 0. You just sold the exact same seat twice—a classic Lost Update race condition.
To prevent lost updates in production, backend engineers rely on two fundamental strategies: Pessimistic Locking and Optimistic Locking.
1. Pessimistic Locking (SELECT ... FOR UPDATE)
Pessimistic Locking assumes collisions will happen, so it locks the row before reading or modifying it.
BEGIN;
-- Step 1: Acquire an exclusive row-level lock immediately on read
SELECT stock FROM seats
WHERE id = 'A1'
FOR UPDATE;
-- Step 2: Safely deduct inventory inside the lock
UPDATE seats SET stock = 0
WHERE id = 'A1';
COMMIT; -- Releases the row lock
Ordered Workflow (SELECT ... FOR UPDATE)
- Step ① — Lock on Read:
User ArunsSELECT ... FOR UPDATE. PostgreSQL immediately places an exclusive lock on Row#A1. - Step ② — Queue Concurrent Callers:
User Barrives 2ms later and runsSELECT ... FOR UPDATE. PostgreSQL blocksUser Bin a lock wait queue untilUser A’s transaction finishes. - Step ③ — Update & Commit:
User Aupdatesstock = 0and commits. - Step ④ — Unlock & Advance Queue: The lock releases;
User Bwakes up, reads the newly committedstock = 0, and exits cleanly with “Sold Out”.
Production Trap: Never call slow external APIs (like Stripe or SendGrid) inside a
SELECT ... FOR UPDATEtransaction. Holding row locks during an 800ms HTTP call starves your database connection pool and risks deadlocks.
2. Optimistic Locking (WHERE version = 1)
Optimistic Locking assumes collisions are rare. Instead of blocking readers in a queue, every row stores an integer version column (or timestamp) that is verified atomically at write time.
-- Step 1: Both users read without any locks
SELECT stock, version FROM seats WHERE id = 'A1';
-- Returns: stock = 1, version = 1
-- Step 2: Atomic compare-and-swap on write
UPDATE seats
SET stock = 0, version = version + 1
WHERE id = 'A1' AND version = 1;
Ordered Workflow (WHERE version = 1)
- Step ① — Parallel Read (Zero Locks): Both
User AandUser Breadstock = 1, version = 1with zero lock wait. - Step ② — First Writer Bumps Version:
User AexecutesUPDATE ... WHERE id = 'A1' AND version = 1. Sinceversionis still1, PostgreSQL updates1 rowand incrementsversionto2. - Step ③ — Stale Writer Rejected:
User Bexecutes the exact sameUPDATE ... WHERE id = 'A1' AND version = 1. Becauseversionis now2, theWHEREclause matches nothing and returns0 rows updated. - Step ④ — Instant Conflict Detection: Your application sees
updatedRows === 0and immediately returns409 Conflict(or retries with fresh data)—zero double-booking and zero lock queues.
Production Trap: Avoid Optimistic Locking on ultra-high-contention flash sales. If 10,000 users read
version = 1simultaneously, 9,999 fail with0 rows updatedand trigger a thundering-herd retry storm.
3. System Design Cheat Sheet
| Dimension | Pessimistic Locking (FOR UPDATE) | Optimistic Locking (version column) |
|---|---|---|
| Core Mechanism | Exclusive Row Lock on Read | Atomic Version Check on Write |
| When It Checks | At Read Time (Blocks concurrent readers) | At Write Time (Zero locks on read) |
| Contention Fit | High Contention (Many users hit 1 row) | Low Contention (Collisions are rare) |
| Best Use Cases | Concert Tickets, Flash Sales, Ledgers | Shared Docs, Profile Edits, B2B Settings |
| Failure Mode | Connection Pool Exhaustion & Deadlocks | Retry Storms under heavy contention |
Test Your Understanding
Quick architectural scenario challenge based on this breakdown.
A 3rd-party payment gateway starts timing out with 504 errors during peak traffic.
Q1.How should a downstream dependency failure be handled to protect upstream service availability?
Comments –
Sign in to share your thoughts
Nothing yet. Be the first.