Optimistic or pessimistic locking: measured on a 100-seat booking
Pessimistic locking, optimistic locking (version), conditional updates and a Redis lock with a fencing token, measured on a 100-seat flight with 400 concurrent requests on MySQL 8.4: which are correct, which are fast, which turn people away for no reason; plus locking best practices and the four conditions for deadlock.
On this page
1. The problem
A 100-seat flight, 400 simultaneous booking requests. The "read the seat count, write the new number" version sells 400 tickets and still reports 87 seats left. Adding synchronized makes the tests pass, but production runs 3 instances behind a load balancer and the bug returns.
2. Key idea
- Pessimistic:
SELECT ... FOR UPDATElocks the row; later callers wait until commit. - Optimistic: read
version, write... WHERE id = ? AND version = 7; 0 rows means someone changed it first, so re-read and retry. JPA: a@Versionfield, failing withOptimisticLockException. - Conditional update: check and write in one statement:
UPDATE flight SET available_seats = available_seats - 1 WHERE id = ? AND available_seats > 0, then look at the affected row count.
2.1 Measured: 100 seats, 400 requests, 32 threads (MySQL 8.4)
| Strategy | Bookings | Correct? | Wrongly rejected | Retries | Time |
|---|---|---|---|---|---|
| Naive read-then-write | 400 | no | 0 | 0 | 571 ms |
Pessimistic FOR UPDATE |
100 | yes | 0 | 0 | 266 ms |
Conditional UPDATE |
100 | yes | 0 | 0 | 203 ms |
| Optimistic (5 attempts) | 100 | yes | 176 | 1,028 | 484 ms |
| Redis lock TTL 5 ms, no version | 311 | no | 0 | 0 | 1,997 ms |
| Redis lock TTL 5 ms + version | 100 | yes | 211 | 1,257 | 2,351 ms |
| Mechanism | Use when | Don't use when |
|---|---|---|
Conditional UPDATE |
single-row counters: stock, seats | the decision needs several reads first |
| Pessimistic | read several things then decide, high contention | holding the lock across an external API call |
Optimistic version |
low contention; versions across HTTP requests (like an ETag) | hot rows: retry storms |
| Distributed lock + version | exclusive work that extends beyond the DB | just to protect one DB row |
Optimistic still takes locks: UPDATE ... WHERE version = ? holds a write lock until commit, and can still deadlock.
3. In Java
public interface FlightRepository extends JpaRepository<Flight, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE) // SELECT ... FOR UPDATE
@Query("select f from Flight f where f.id = :id")
Optional<Flight> findForUpdate(@Param("id") long id);
@Modifying
@Query("update Flight f set f.availableSeats = f.availableSeats - 1 where f.id = :id and f.availableSeats > 0")
int decrementIfAvailable(@Param("id") long id); // 1: booked; 0: sold out
}
@Entity
class Flight {
@Id Long id;
int availableSeats;
@Version int version; // Hibernate adds "and version = ?" on write
}Retries for optimistic locking wrap outside the transaction. Don't use a timestamp as the version: two writes in the same second slip through.
Deadlocks and best practices
- The four Coffman conditions: mutual exclusion, hold and wait, no preemption, circular wait. Breaking one is enough.
- Locking in a fixed order breaks circular wait:
SELECT ... WHERE id IN (?, ?) ORDER BY id FOR UPDATE. "Debit first, credit later" doesn't: A→B and B→A both debiting first still lock crosswise, and InnoDB rolls one back (error 1213). - Lock through the primary key: just one record lock. An
UPDATEfiltered on a non-unique secondary index locks gaps too;SELECTthe ids first, thenUPDATE ... WHERE id IN (...), repeating the business condition in theWHERE. - A distributed lock (Redis) can expire mid-work (GC pause, short TTL): two requests both "hold" it. A
versionat the final write is the fencing token that stops whoever lost the lock. - Keep a retry loop for error 1213, since other code may lock in a different order.
4. Working with AI
Delegate to AI: a 400-concurrent-request harness, tests for the invariant bookings + seats left = 100.
Check yourself:
- No "read, then write the computed value" for counters; use a conditional update.
- No
synchronizedprotecting data that lives in the database. - Optimistic retries sit outside
@Transactional, bounded and with jitter. - Every distributed lock comes with a
versionor a condition on the write.
5. Exercises
Exercise 1: Review "overselling prevented with a Redis lock"
AI wrote: take a Redis lock SET lock:flight:1 token NX PX 5000, read the seats, call the airline's hold API (usually 200 ms, 8 s when slow), write available_seats = ?, then delete the lock. Description: "the lock is exclusive so overselling is impossible". Find the bugs and fix them.
Solution to Exercise 1
- When the API takes 8 s, the 5 s TTL expires mid-work; another request takes the lock, both read and write: overselling (measured at 311 tickets for 100 seats).
- Deleting with a plain
DELcan remove someone else's lock; compare the token (Lua compare-and-delete). - Fix: the write protects itself:
UPDATE ... SET available_seats = available_seats - 1 WHERE id = ? AND available_seats > 0(orAND version = ?). The lock only reduces contention; it isn't the last line of defence. - Test: TTL 5 ms, 10 ms of work inside, 400 requests: the invariant still holds.
Exercise 2: Optimistic or pessimistic?
(a) Editing a customer profile where users keep the form open 5 minutes. (b) Transferring money between two accounts. (c) A flash sale of 1,000 slots with 50,000 requests in 10 seconds. Choose a mechanism for each.
Solution to Exercise 2
- (a) Optimistic: low contention, and a lock can't live for 5 minutes across two HTTP requests. Send the
versionlike an ETag, return 409 if someone else changed it. - (b) Pessimistic on both rows in id order (
ORDER BY id FOR UPDATE), or a conditional updateWHERE balance >= :amounton the debit side; retry on error 1213. - (c) Conditional update for the counter; at 50,000 requests in 10 s a single hot row chokes, so change the model: reserve slots in Redis first (
DECR), queue, then write to the DB.
Summary
- Pessimistic: later callers wait; optimistic: later callers fail and retry.
- Single-row counters: a conditional
UPDATE, correct and fastest. - Optimistic on a hot row turns customers away while stock remains.
- A distributed lock always needs a
versionas a fencing token. - Lock multiple rows in id order;
synchronizedonly locks one JVM.
Further reading: Reviewing a Redis distributed lock.
Practice interview questions on this topic
- How do optimistic and pessimistic locking differ, and when do you use each?
- How does optimistic locking with a version column work, and why not use a timestamp?
- What LockModeTypes does JPA offer? Do you still need them with a high isolation level or a distributed lock?
- What is a database deadlock, and how do you prevent and handle it?
Comments
Community rules