System design concepts · Consistency and concurrency control

Optimistic vs Pessimistic Locking

Short answer

Optimistic locking assumes conflicts are rare. It reads without taking a lock, then makes the update conditional on the data being unchanged, usually by checking a version number in the WHERE clause; if another writer got there first, the update affects zero rows and the application retries or reports a conflict. Pessimistic locking assumes conflicts are likely. It locks the rows before changing them, for example with SELECT ... FOR UPDATE, and other writers wait until the lock is released at commit. Optimistic locking is cheaper when contention is low and fits flows with user think time, because nothing is held while the user edits. Pessimistic locking does better when many writers fight over the same few rows, because they queue instead of repeatedly retrying.

Read the video transcript

Two people try to change the same row at the same moment. There are two classic ways to stop one of them from silently overwriting the other. Optimistic locking takes no lock at all. Both writers read the row at version seven. Each update says: set the new balance and version eight, but only where the version is still seven. The first one lands. The second matches zero rows, so it re-reads and retries. Pessimistic locking locks first. Select for update grabs the row, and every other writer waits in line until that transaction commits. Which one wins depends on contention. When conflicts are rare, optimistic is cheap, and nothing is held while a user is still typing. But on a hot row, optimistic writers keep colliding and retrying, and the work is wasted. A queue of lock waiters makes steady progress instead. And for the last seat in a booking system, one atomic conditional update often beats both: mark it held only if it's still available, and exactly one caller wins.

Optimistic vs Pessimistic Locking: comparison table

AspectOptimistic lockingPessimistic locking
AssumptionConflicts are rareConflicts are likely
When a conflict is handledAt write time: the version check failsUp front: other writers block
MechanismVersion column, compare-and-set, ETag with If-Match, Redis WATCHSELECT ... FOR UPDATE, row locks, advisory locks, a distributed lock with a lease
Under low contentionCheap: no lock waitsPays for locks that were not needed
Under high contentionMany failed attempts and wasted workWriters queue but steadily make progress
Deadlock riskNone from the scheme itselfReal; needs consistent lock order or timeouts
Long edits by a userA good fit: nothing is held while they typeNot acceptable: locks would be held for minutes
ExamplesWiki edits, profile updates, DynamoDB conditional writes, Kubernetes resourceVersionDebiting a hot account, a short critical section on inventory

When to use each

Use optimistic locking when

  • Two writers rarely touch the same record at the same time.
  • The read and the write are separated by user think time or a network round trip.
  • The store has no long-lived locks to offer, as with most key-value stores and HTTP APIs.

Use pessimistic locking when

  • Many writers hit the same row, and retries would waste more than waiting.
  • The work inside the critical section is short and inside one database transaction.
  • Redoing the work after a conflict is expensive or has side effects you cannot easily undo.
The verdict

Use optimistic locking when

Two writers rarely touch the same record at the same time.

Otherwise

Use pessimistic locking when

Many writers hit the same row, and retries would waste more than waiting.

What the SQL looks like

Optimistic: read the row with its version, say 7. Later, run UPDATE accounts SET balance = ?, version = 8 WHERE id = ? AND version = 7. If the update reports one row changed, you won. If it reports zero, someone else changed the row; re-read and decide whether to retry.

A version-checked UPDATE beside SELECT FOR UPDATE.

Pessimistic: inside a transaction, run SELECT balance FROM accounts WHERE id = ? FOR UPDATE. The row is now locked until commit or rollback. Do the check, run the update, and commit. Concurrent transactions that try to lock the same row wait in line.

Booking systems often need neither in pure form

For seat or room booking, a single conditional update usually beats both: UPDATE seats SET status = 'held', holder = ? WHERE id = ? AND status = 'available'. It is atomic, holds no lock beyond the statement, and one caller wins. Add a hold with an expiry so abandoned checkouts release the seat.

An atomic conditional UPDATE holds the seat, and an expiry frees abandoned holds.

Across services there is no database row lock to lean on. Distributed locks need leases so a crashed holder does not block forever, and fencing tokens so a holder that paused past its lease cannot overwrite newer work.

Interview angle

How it comes up in a system design interview

This comes up whenever two users can change the same thing: the last seat, the last room, the last unit in a flash sale, or the same wallet balance. Interviewers want to hear which approach you pick, why it fits the contention level, and what the user sees when they lose the race.

Where you will meet it

  • Thousands of users click "buy" on the last few items in a flash sale. How do you avoid overselling without serializing all traffic?
  • Two devices update the same wallet balance at once. What prevents a lost update?
  • A hotel room is held while the guest enters payment details. How long is the hold, and how is it released?
  • How do you build a lock that works across services, and what happens if the holder crashes?
How a strong answer sounds
“Most edits to a listing rarely conflict, so I would use optimistic locking with a version column and return a conflict if the version changed. The inventory decrement in the flash sale is the opposite case: every request hits the same row, so I would use an atomic conditional decrement, and put a queue in front so the database sees a steady rate rather than a stampede.”

Common mistakes

  • Using optimistic locking on a hot row, then being surprised that most requests fail and retry.
  • Holding a database lock across a call to another service or across user input.
  • Building a distributed lock without a lease or fencing token.

Frequently asked questions

Is optimistic locking really a lock?

No lock is held. It is a check at write time that the data has not changed since you read it, so it is often called optimistic concurrency control.

Does MVCC mean the database is optimistic?

Not exactly. MVCC lets readers see a snapshot without blocking writers. Writers in databases such as PostgreSQL still take row locks, and higher isolation levels detect conflicting writes and abort one transaction.

What does the @Version annotation in JPA do?

It turns on optimistic locking: the entity carries a version field, every update checks and increments it, and a mismatch raises an exception instead of silently overwriting.

Can you combine both?

Yes. A common pattern uses optimistic checks for ordinary edits and pessimistic locks or atomic conditional updates on the few hot records where contention is high.

Learn and practise

Lessons

Problems where this choice matters

Knowing the trade-off is half of it

Practise saying it under follow-up questions: a timed system design interview with an AI interviewer that probes your choices and grades against a rubric.

Start a mock interview