Concurrency Control

Difficulty: Advanced

Question

What is the difference between optimistic and pessimistic locking, and how do you decide which one to use?

Answer

Both strategies prevent the lost update problem, where two users read the same row and the second write silently overwrites the first. Pessimistic locking locks the row when you read it (SELECT ... FOR UPDATE) so nobody else can change it until you commit. Optimistic locking takes no lock; instead it checks at write time that the row has not changed since you read it, usually with a version column, and fails the update if it has.

The problem both solve

Two support agents open ticket 501 at version 3. Agent A changes the status and saves. Agent B, still looking at version 3, changes the priority and saves, overwriting A's status change. Without some form of concurrency control, A's work disappears with no error.

How pessimistic locking works

  1. Start a transaction.
  2. SELECT * FROM seats WHERE id = 7 FOR UPDATE acquires a row lock.
  3. Any other transaction trying to lock or update that row waits.
  4. Update and COMMIT, which releases the lock.

Useful options in PostgreSQL and MySQL 8.0+:

  • FOR UPDATE NOWAIT fails immediately instead of waiting.
  • FOR UPDATE SKIP LOCKED skips rows already locked, which is the standard way to build a job queue where many workers pull tasks.
  • FOR SHARE allows other readers to also lock for share but blocks writers.

How optimistic locking works

  1. Read the row along with its version (or updated_at).
  2. Do the work without holding any lock, possibly while the user edits a form for minutes.
  3. Write with UPDATE ... SET ..., version = version + 1 WHERE id = ? AND version = ?.
  4. If zero rows were affected, someone else changed it. Reload and retry, or show a conflict message.

ORMs support this directly: JPA and Hibernate use @Version, Entity Framework uses concurrency tokens, and Django needs a manual filter on the version. HTTP APIs expose the same idea with ETag and If-Match headers.

Choosing between them

FactorOptimisticPessimistic
ContentionLow, conflicts are rareHigh, many writers on the same rows
Holds locksNoYes, until commit
Conflict handlingRetry or show errorWaiting, possible deadlocks
Long user think timeWorks wellBad, locks held too long
ExampleEditing a profile or a wiki pageBooking the last seat, debiting an account

Rule of thumb: if conflicts are rare and retrying is cheap, go optimistic. If conflicts are frequent or a retry is expensive or user-visible (flash sales, ticket booking for a popular show), go pessimistic, and keep the transaction short.

Gotchas

  • Never hold a pessimistic lock across user interaction or an external API call such as a payment gateway request.
  • Pessimistic locks taken in different orders by two transactions can deadlock. Lock rows in a consistent order.
  • With optimistic locking, always check the affected row count. Forgetting this turns it into no locking at all.
  • For simple counters, an atomic statement such as UPDATE stock SET qty = qty - 1 WHERE id = ? AND qty > 0 avoids both strategies.
Optimistic locking conflict. The second writer's update matches zero rows because the version has moved on.
  1. User A → Database: Read ticket 501, version 3
  2. User B → Database: Read ticket 501, version 3
  3. User A → Database: UPDATE ... WHERE version = 3
  4. Database → User A: 1 row updated, now version 4
  5. User B → Database: UPDATE ... WHERE version = 3
  6. Database → User B: 0 rows updated, conflict

Code examples

Optimistic locking with a version column

-- Read: remember the version
SELECT id, status, priority, version FROM tickets WHERE id = 501;
-- returns version = 3

-- Write: only succeeds if nobody else changed it
UPDATE tickets
   SET priority = 'HIGH', version = version + 1
 WHERE id = 501 AND version = 3;
-- App checks affected rows: 0 means conflict, reload and retry

No lock is held between the read and the write. The WHERE clause on version turns the update into a compare-and-swap.

Pessimistic locking for seat booking

BEGIN;

SELECT id, status FROM seats
 WHERE show_id = 9 AND seat_no = 'F12'
 FOR UPDATE NOWAIT;   -- fail fast if someone else holds it

UPDATE seats SET status = 'BOOKED', user_id = 42
 WHERE show_id = 9 AND seat_no = 'F12' AND status = 'AVAILABLE';

COMMIT;

The row is locked from the SELECT until COMMIT, so two users cannot both book F12. NOWAIT returns an error instead of making the second user wait.

Key points

  • Both prevent lost updates; they differ in when the conflict is detected
  • Optimistic: no locks, check version at write time, retry on zero affected rows
  • Pessimistic: SELECT ... FOR UPDATE holds a row lock until commit
  • SKIP LOCKED is the standard pattern for database-backed job queues
  • Never hold pessimistic locks across user think time or external API calls

Common follow-up questions

  • How does JPA's @Version annotation implement optimistic locking?
  • How would you build a job queue in PostgreSQL using SKIP LOCKED?
  • How do ETag and If-Match headers relate to optimistic locking?
  • What isolation level prevents lost updates without explicit locks?

Interview tips

  • Start by naming the lost update problem; it shows you know why locking exists
  • Tie the choice to contention level with one example for each side
  • Mention checking the affected row count; many candidates forget this detail

Concepts covered

Optimistic Locking, Pessimistic Locking, Version Column, SELECT FOR UPDATE, Lost Update

More Database Design questions