Optimistic vs. Pessimistic Locking
Imagine two users trying to book the last seat on a flight at the same time. If both read the count as "1" and decrement it, you've oversold the flight. This is the Lost Update Problem, and solving it requires a locking strategy.
1. Pessimistic Locking: "Nobody Move"
This approach assumes the worst. When a thread reads data, it locks it immediately so no other thread can modify it until the first thread is done.
-- PostgreSQL Example
SELECT * FROM seats WHERE id = 101 FOR UPDATE;
- Pros: Guaranteed consistency; best for high-contention write-heavy systems.
- Cons: High risk of deadlocks; destroys throughput as threads wait for locks.
2. Optimistic Locking: "Check Before Commit"
This assumes conflicts are rare. You don't lock anything on read. Instead, you add a version column to your table.
// Java/JPA Example
@Version
private Long version;
When updating, the database checks if the version has changed.
UPDATE seats SET status = 'BOOKED', version = version + 1 WHERE id = 101 AND version = 5;
- Pros: Non-blocking; excellent for high-read / low-write systems.
- Cons: Performance degrades if write contention is high, as retries increase.
3. Which one to choose?
- Use Pessimistic when the cost of a collision is high and the volume of writes to the same record is frequent.
- Use Optimistic for typical CRUD applications where user overlap is minimal.
Next: Docker for Java Developers: Production Guide Related: Database Isolation Levels Explained
