Optimistic, Pessimistic & Distributed Locking
On this page
Two people book seat 12A on the same flight at the same moment. Both requests read the seat as free, both write "booked", and both get a confirmation email. One of them arrives at the gate to find someone in their seat. Nothing crashed; two correct-looking requests simply interleaved in the wrong order.
Any time several requests read a value, decide, and write it back, you need a rule for who wins. That rule is concurrency control, and in interviews it comes down to three tools: optimistic locking, pessimistic locking, and distributed locks.
How it works
The lost update
The bug in the opening is called a lost update: read, modify, write, while someone else does the same. The second write silently replaces the first. Every technique below prevents it in a different way.
Optimistic locking: check on write

Each row carries a version column. A writer reads the row and its version, then writes with a condition:
UPDATE seats
SET owner = 'alice', version = 8
WHERE id = '12A' AND version = 7;
If someone else wrote first, the version is no longer 7, the update matches zero rows, and the application knows it lost. It re-reads and decides again (pick another seat, or retry the increment). No lock is held while the user thinks, so nothing blocks. Many key-value stores offer the same thing as compare-and-set (CAS) or conditional writes.
Pessimistic locking: lock first
BEGIN;
SELECT * FROM seats WHERE id = '12A' FOR UPDATE; -- others wait here
UPDATE seats SET owner = 'alice' WHERE id = '12A';
COMMIT;
The first transaction takes a row lock; the second blocks until the first commits, then sees the seat is taken. Correct and simple, but every waiting request holds a connection, and two transactions that lock rows in different orders can deadlock (the database detects it and aborts one). Keep these transactions short and lock rows in a fixed order.
Often the best lock is no lock
Many read-modify-write cycles collapse into one atomic statement:
UPDATE inventory SET stock = stock - 1
WHERE product_id = 42 AND stock > 0;
The database does the check and the write together. If it updates one row, you got an item; zero rows means sold out. Same for INCR in Redis.
Distributed locks: coordinating across machines
Sometimes the thing to protect is not a row: "only one worker should run the nightly billing job", "only one process should refresh this cache key". A distributed lock is a key in a shared store that one process holds at a time:
SET lock:billing <owner-id> NX PX 30000 # set only if absent, expire in 30 s
Two rules make it safe:
- Always use a lease (TTL). If the holder crashes, the lock expires instead of blocking forever. The holder renews it while working.
- Use fencing tokens for anything that writes. A process can pause (a long garbage-collection pause, a network stall) past its lease, wake up, and still believe it holds the lock.

Each time the lock is granted, the lock service hands out a number that only increases. The protected storage remembers the highest token it has seen and rejects writes with a smaller one. The lock decides who should work; the token stops a stale holder from doing damage.
Redis with a single primary is fine for efficiency locks (avoid duplicate work, where an occasional double run is harmless). For correctness locks, use a consensus-backed store such as etcd or ZooKeeper, plus fencing.
Trade-offs and costs
| Approach | Good when | Costs |
|---|---|---|
| Atomic statement | The check and write fit in one statement | Limited to what one statement can express |
| Optimistic (version / CAS) | Conflicts are rare; read-heavy | Retries under contention; wasted work if many collide |
Pessimistic (FOR UPDATE) | Conflicts are common; transaction is short | Blocking, held connections, deadlocks |
| Distributed lock | Work spans machines or is not one row | Extra system, lease tuning, needs fencing for correctness |
When to reach for it
- Booking a seat, room or time slot: optimistic version check, or a unique constraint on
(seat_id, flight_id)so the second insert fails. - Decrementing stock: atomic conditional update; for a flash sale, pre-load stock into Redis and decrement there.
- Editing a document or profile: optimistic locking with an ETag (
If-Matchheader), so the second save gets412 Precondition Failed. - Transferring money between two accounts: a short pessimistic transaction that locks both rows in id order.
- Running a scheduled job once across a fleet: a distributed lock with a lease; make the job idempotent too.
Example
Seat booking for a concert. Assumptions: 50,000 seats, 500,000 fans arrive in the first minute, most of them on the best 2,000 seats.
- Hold step: the user picks a seat. The service runs
UPDATE seats SET status='HELD', holder=:user, held_until=now()+interval '5 min' WHERE id=:seat AND status='AVAILABLE'. One row updated means the hold succeeded; zero means someone else got it. No lock is held while the user types card details. - Why not
FOR UPDATEon browse: thousands of users looking at the same seat would queue behind each other's locks and exhaust connections. - Pay step: after payment succeeds,
UPDATE … SET status='SOLD' WHERE id=:seat AND holder=:user AND status='HELD'. If the hold expired and someone else took the seat, this matches zero rows and the payment is refunded. - Expiry: a sweeper job (or a check at read time) returns expired holds to
AVAILABLE. Only one sweeper runs at a time, guarded by a distributed lock with a 30-second lease; the sweeper's own updates are conditional, so a rare double run is harmless.
Common mistakes
- Reading, checking in code, then writing with no version check or lock: the classic lost update.
- Holding a database lock while waiting on the user or a slow external call.
- Distributed locks without a TTL, so a crashed holder blocks everyone forever.
- Trusting a lease alone for correctness, without fencing tokens.
- Reaching for a distributed lock when a unique constraint or a conditional update would do.
- Locking rows in random order inside transactions and then being surprised by deadlocks.
Say this in the interview
"Holding a seat is a single conditional update: set it to HELD where it's still AVAILABLE. If it updates zero rows, someone else got it. That's optimistic, so nothing blocks while thousands of users browse. For the money transfer I'll use a short transaction that locks both account rows in id order. The expiry sweeper takes a distributed lock with a lease, but its updates are conditional too, so a stale holder can't do damage."
Used in
- Idempotency & Deduplication, TTL, Expiration & Cleanup, Database.
- Design a Flash Sale System, Design an Online Banking System, Design Google Calendar.