← All lessons

Core concepts

Optimistic vs pessimistic locking

Two people hit Save on the same row at the same moment. Whose change wins is not something the database decides for you, and the answer you pick says a lot about how your data is used.

12 min readUpdated November 2026Free

Two people hit Save on the same record at the same time. Whose change wins?

This is where most of us first learn that databases don’t magically sort out concurrency for us. Under the default isolation level of Postgres, MySQL and most of their peers, the honest answer is whoever commits last, and the other person’s change is gone without an error. That has a name — the lost update — and it is the problem both kinds of locking exist to solve.

There are two ways to deal with it, and they start from opposite bets about how often the collision happens.

Sarah and Alex both update stock of 40 units. Optimistic: nobody locks, Alex saves first and the version moves from 1 to 2, so Sarah is left holding stale data at version 1 and her save will fail. Pessimistic: Sarah locks the row and updates it to 30 while Alex waits. OptimisticPessimisticstock: 40version: 1stock: 20version: 2Reads 40, v1Still holds40, v1Reads 40, v1Saved ✓Both read. Nobody locks.Version 1 → 2. Sarah’s save will fail.stock: 40unlockedstock: 40LOCKED: SarahRequests rowUpdatingto 30Requests rowWaiting…Both want the same row.Alex has to wait.SarahAlexSarahAlex
The same collision, two bets. Optimistic lets both proceed and catches the loser at save time; pessimistic makes the second person wait.

The lost update, concretely

Sarah and Alex both work in a warehouse, and the system says there are 40 desk lamps on the shelf. Sarah ships an order of 10; Alex ships an order of 20. Each of them opens the product screen, which reads the stock count, and each saves a new count computed from what they read:

  1. Sarah reads 40.
  2. Alex reads 40.
  3. Alex saves 20 (40 − 20).
  4. Sarah saves 30 (40 − 10).

The row now says 30, but only 10 lamps are left on the shelf. Alex’s write happened, was acknowledged, and was then overwritten by a value computed from data that was already stale. No constraint was violated and no error was raised — the system will happily sell twenty lamps it does not have.

Where candidates lose it

“We use transactions, so this can’t happen” is the answer that fails the question. Each save above can be its own perfectly good transaction. Under READ COMMITTED — the default in Postgres and Oracle — a transaction sees whatever was committed when each statement starts, so nothing stops a read-modify-write cycle from writing over a commit it never saw. Transactions give you atomicity; they do not give you this without either a lock or a check.

Optimistic locking: “conflicts are rare, so I’ll check at the end”

Nobody locks anything. Every row carries a version number. When you save, the update says “apply this only if the version is still what I read”:

-- read
SELECT stock, version FROM product WHERE id = 7;      -- 40, version 1

-- write, conditional on nothing having changed in between
UPDATE product
   SET stock = 30, version = version + 1
 WHERE id = 7 AND version = 1;

If someone else got there first, the version is now 2, the WHERE matches nothing, and the statement reports 0 rows updated. That zero is the conflict. Your application turns it into an error, re-reads fresh data, and either retries or shows the user what changed.

Sequence diagram, optimistic locking. Sarah and Alex both read stock of 40 at version 1 with no lock. Alex sets stock to 20 if the version is still 1, which succeeds and moves the row to version 2. Sarah's update to 30 if version is 1 matches no rows and is rejected, so she re-reads and retries.Optimistic lockingNobody waits. Conflicts are caught at save time.SarahDatabaseAlex① Read stock (no lock)40, version 1② Read stock (no lock)40, version 1③ Set stock = 20 if v = 1Saved ✓④ Set stock = 30 if v = 1Rejected: 0 rows (v1 ≠ v2)DB now: 20, version 2Re-read, then retry
Nobody waits, and the conflict surfaces at save time as a write that matched zero rows.

A few things make this work in practice:

The point

Optimistic locking is the same idea as an HTTP ETag. The client sends If-Match with the version it read; the server answers 412 Precondition Failed if the resource has moved on. Once you see that, you can apply it at any layer — a row, a document in a key-value store, a whole REST resource — without the storage needing locks at all.

The cost is all paid on conflict. When collisions are rare that cost is nearly zero. When they are common, every loser re-reads and retries, the retries collide with each other, and throughput can fall off a cliff while every request is technically making progress.

Pessimistic locking: “conflicts are likely, so I’ll block them up front”

The first transaction to touch the row locks it. Everyone else who wants to write that row waits in line until it is released at commit or rollback. Slower, but nobody ever overwrites anybody.

BEGIN;
SELECT stock FROM product WHERE id = 7 FOR UPDATE;     -- takes a row lock; others block here
UPDATE product SET stock = 30 WHERE id = 7;
COMMIT;                                                 -- lock released, the next one proceeds
Sequence diagram, pessimistic locking. Sarah selects the row for update and it is locked for her. Alex's update of the same row waits. Sarah sets stock to 30 and commits, releasing the lock, and Alex's request resumes and sees 30.Pessimistic lockingLock first. Others wait until it is released.SarahDatabaseAlex① SELECT … FOR UPDATERow loaded (40)② Update the same rowWaiting: lock held③ Set stock = 30④ COMMIT, release lockLock freed, request resumesLOCKED for SarahDB now: 30, unlockedAlex now sees 30
Nobody is rejected. Alex waits for Sarah's lock, then sees her committed value.

FOR UPDATE is what turns a plain read into a claim. Without it the SELECT takes no row lock under the default isolation level, and you are back to the lost update.

You can reproduce the wait with two psql sessions against any Postgres:

-- session 1
CREATE TABLE product (id int PRIMARY KEY, stock int, version int DEFAULT 1);
INSERT INTO product VALUES (7, 40);
BEGIN;
SELECT * FROM product WHERE id = 7 FOR UPDATE;

-- session 2: hangs on this line
UPDATE product SET stock = 20 WHERE id = 7;

-- session 1
UPDATE product SET stock = 30 WHERE id = 7;
COMMIT;      -- session 2 now finishes, and its write lands on top of 30

Note what that last line says: pessimistic locking serialised the two writers, but session 2 still wrote a blind value. It should have taken its own FOR UPDATE, read 30, and decided from there. The lock only protects code that asks for it.

Two variants are worth knowing by name:

The cost is paid on every write, conflict or not: transactions hold locks for as long as they run, and everyone behind them waits. Hold a lock across a network call, or worse, across a user’s think time, and your database’s concurrency becomes the speed of your slowest client.

How to choose

There is no best option, only the one that fits how your data actually gets used.

Optimistic Pessimistic
Bet Conflicts are rare Conflicts are likely
Cost paid Only when a conflict happens (retry) On every write (waiting)
What a conflict looks like A failed write the app must handle A delay, or a deadlock
Spans user think time Yes — the version rides along with the form No — never hold a lock while a human thinks
Fits Profiles, settings, CMS content, carts, wiki pages Balances, inventory, seat and ticket booking

→ Mostly reads, occasional writes to rows that different people rarely touch at once? Go optimistic. No waiting, and you only pay the retry cost when a conflict actually happens.

→ Lots of writes hitting the same rows, and a conflict is expensive? Go pessimistic. Making users wait beats explaining why two customers bought the last lamp — and under heavy contention, waiting in an orderly queue does more useful work than a crowd of optimistic retries all failing each other.

The point

Before picking either, ask whether you need a read-modify-write at all. Shipping an order written as UPDATE product SET stock = stock - 10 WHERE id = 7 AND stock >= 10 reads and writes in one atomic statement: no version column, no SELECT ... FOR UPDATE, and the WHERE refuses to sell stock you do not have. The row lock still exists, but only for the length of one statement. When the change can be expressed relative to the current value, this is usually the best answer of the three.

The catch with pessimistic locking: deadlocks

If two transactions each hold a lock the other needs, neither can ever proceed:

T1: lock lamp (id 7)        T2: lock chair (id 9)
T1: wants chair ...         T2: wants lamp ...        → both wait forever

That is exactly what happens when Sarah ships an order for a lamp and a chair, listed in that order, at the same moment Alex ships one listed chair first. Databases detect the cycle and break it by aborting one transaction — Postgres checks after deadlock_timeout (one second by default) and fails one side with ERROR: deadlock detected, SQLSTATE 40P01. Your data is safe; one user’s request just failed and needs a retry.

Most deadlocks are prevented by two habits:

  1. Lock rows in a consistent order. Sort an order’s products by id and lock them in that order, however the customer happened to list them. Two transactions that acquire locks in the same order can wait on each other but can never form a cycle.
  2. Keep transactions short. Lock as late as possible, do no network calls while holding a lock, commit as soon as the work is done. A deadlock needs overlap, and short transactions overlap less.

And treat 40P01, like a serialization failure (40001), as a retryable error in the code that runs the transaction. You will not prevent every one; you only need to survive the ones that happen.

Where candidates lose it

“We’ll lock with Redis instead” moves the problem rather than solving it. A distributed lock has a lease that can expire while the holder is paused, and then two clients both believe they hold it. For correctness you need the storage layer to reject the stale writer, which is a fencing token — and a fencing token is optimistic locking under another name. The Redis lesson walks through that interleaving.

Saying it in an interview

Say it like this

“Seat booking is a hot row with an expensive conflict — two people cannot both get 14C — so I’d lock it pessimistically: SELECT ... FOR UPDATE on the seat inside a short transaction, no external calls while it’s held, and a retry on deadlock. For the user’s profile and preferences I’d use a version column instead: conflicts there are rare, and I don’t want a lock open while someone’s filling in a form.”

The follow-ups, and the one-line answers

  1. “Isn’t the default isolation level enough?” No. READ COMMITTED allows lost updates on a read-modify-write. Raise it, add a version check, or take a lock.
  2. “What happens when the optimistic check fails?” Zero rows updated. Re-read, then retry automatically if the change can be recomputed, or show the user the new value if it can’t.
  3. “Optimistic under heavy contention?” Retries pile up and throughput collapses. That is the signal to switch to a lock — or to an atomic relative update if the change allows it.
  4. “How do you avoid deadlocks?” Consistent lock order, short transactions, and a retry on 40P01 for the ones that still happen.
  5. “How does this work across a web form?” Optimistically. The version goes to the client with the data and comes back with the edit, or as an ETag with If-Match.
  6. “What does SKIP LOCKED do?” Skips rows someone else holds. It turns a table into a work queue where each worker claims a different row.

Have you ever hit a deadlock in production because of a locking choice? The fix is almost always one of the two habits above — and the interesting part is which one you were missing.