Databases

Optimistic vs. Pessimistic Locking: Concurrency Control in Practice

Master database concurrency. Learn the trade-offs between Optimistic and Pessimistic locking, and when to use each for high-traffic backend systems.

Sachin Sarawgi·April 20, 2026·2 min read
#database#concurrency#locking#sql#performance#transaction

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

📚

Recommended Resources

Designing Data-Intensive ApplicationsEssential

The go-to book for understanding databases, consistency, and distributed data.

View on Amazon
MongoDB — The Complete Developer's Guide — Udemy

Comprehensive MongoDB course from basics to advanced aggregations.

View Course

Practical engineering notes

Get the next backend guide in your inbox

One useful note when a new deep dive is published: system design tradeoffs, Java production lessons, Kafka debugging, database patterns, and AI infrastructure.

No spam. Just practical notes you can use at work.

Sachin Sarawgi

Written by

Sachin Sarawgi

Engineering Manager and backend engineer with 10+ years building distributed systems across fintech, enterprise SaaS, and startups. CodeSprintPro is where I write practical guides on system design, Java, Kafka, databases, AI infrastructure, and production reliability.

Found this useful? Share it: