← Lessons

quiz vs the machine

Platinum1880

Concurrency

Optimistic vs Pessimistic Locking

Two strategies for handling concurrent updates to shared data.

6 min read · advanced · beat Platinum to climb

Optimistic vs Pessimistic Locking

When many transactions update the same data, you can coordinate them with either a pessimistic or an optimistic strategy.

Pessimistic locking assumes conflicts are likely. A transaction takes a lock before reading or writing, blocking others until it finishes. This guarantees safety but reduces concurrency and risks deadlock when locks are held across long operations.

Optimistic locking assumes conflicts are rare. It takes no lock during the read. Instead it records a version number or timestamp. At commit time it checks whether the version still matches. If another transaction changed the row, the version differs, the commit is rejected, and the transaction retries.

How to choose:

  • Use pessimistic when contention is high, so retries would be wasteful and conflicts costly.
  • Use optimistic when contention is low and you want maximum throughput, accepting occasional retries.

Optimistic locking maps naturally to compare and swap at the hardware level and to versioned rows in databases.

Key idea

Pessimistic locking blocks others up front for high contention; optimistic locking validates a version at commit and retries when contention is rare.

Check yourself

Answer to earn rating on the learn ladder.

1. What does optimistic locking check at commit time?

2. When is pessimistic locking the better choice?