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.
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.
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:
- Sarah reads 40.
- Alex reads 40.
- Alex saves 20 (40 − 20).
- 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.
“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.
A few things make this work in practice:
- The check and the write must be one statement. Reading the version, comparing it in your code
and then issuing an unconditional
UPDATEreintroduces exactly the race you were closing. The database has to do the compare-and-set. - Your ORM probably does it already. JPA and Hibernate do this for any entity with a
@Versionfield and throwOptimisticLockExceptionon the zero. Rails does it for any table with alock_versioncolumn. It is worth knowing the SQL underneath, because that is what the interviewer will ask you to write. - A timestamp can stand in for the version, but a counter is safer: two writes inside the clock’s resolution produce the same timestamp, and a counter cannot collide.
- It works across requests. Nothing is held open while the user stares at the form. The version travels to the browser and back with the edit, which is why this is the only sane choice when the “transaction” is a human taking two minutes to fill in a page.
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
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:
FOR UPDATE NOWAITfails immediately instead of queueing. Useful when “someone else is editing this” is the right thing to tell the user.FOR UPDATE SKIP LOCKEDskips rows that are already locked. That is not for editing a specific record; it is how you build a job queue in Postgres, where any free row will do.
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.
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:
- 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.
- 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.
“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
“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
- “Isn’t the default isolation level enough?” No.
READ COMMITTEDallows lost updates on a read-modify-write. Raise it, add a version check, or take a lock. - “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.
- “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.
- “How do you avoid deadlocks?” Consistent lock order, short transactions, and a retry on
40P01for the ones that still happen. - “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
ETagwithIf-Match. - “What does
SKIP LOCKEDdo?” 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.