Should you lock the row or retry on conflict?
Pessimistic locking (SELECT … FOR UPDATE) vs optimistic retries (a version column) vs a single atomic UPDATE, measured on PostgreSQL 17 at high and low contention, plus 50 buyers rushing the last 10 tickets.
The verdict, which the measurements below will prove: neither, if you can help it. When the whole change fits in one statement (UPDATE … SET stock = stock - 1 WHERE stock > 0), let the database do the read and the write together. That was about 7× faster than either approach on a hot row and never wrong. When you must read, think, then write:
- Lock (
SELECT … FOR UPDATE) when conflicts are frequent and the work between the read and the write is short. - Retry on a version check (optimistic) when conflicts are rare, or when the “work” is a human looking at a form for minutes, where no database lock can help.
Measured on PostgreSQL 17.11. The code is in database-tradeoffs-lab, and make locking reruns every number below.
The case: a shop sells its last item to dozens of people, a stock count drifts away from reality, an admin’s careful edit silently disappears. The usual suspects are “we need locks” or “we need retries”, and teams argue about which. This is one of those questions where measuring beats arguing. Spoiler for the reveal: the winner turns out to be the plainest option on the list, a single, well-written UPDATE.
Case file
The case The last item sold to dozens, stock drifts, an admin’s edit disappears Suspects “We need locks”, “we need retries” Culprit Read-modify-write: a stale read written back The fix One atomic UPDATE … WHERE stock > 0; locks or version checks only when you must read firstEvidence database-tradeoffs-lab on PostgreSQL 17.11 ( make locking)
Setting the scene #
Every strategy does “buy one item”:
- read the stock;
- do 2 ms of application work (a price calculation, a call to another service);
- write stock - 1.
32 buyers make 25 purchases each. Under high contention they all buy the same item; under low contention they pick from 1,000 items.
The suspects at a glance #
| Naive read-modify-write | Pessimistic: FOR UPDATE |
Optimistic: version check + retry | Atomic UPDATE |
SERIALIZABLE + retry |
|
|---|---|---|---|---|---|
| How | Read, work, write the computed value | Lock the row on read; others wait until commit | Write WHERE version = <what I read>; 0 rows → retry |
One statement computes from the current row | Plain reads and writes; PostgreSQL aborts one of two conflicting transactions |
| Lost updates (one hot row) | 772 of 800 | 0 | 0 | 0 | 0 |
| Purchases/s, one hot row | wrong | 191-284 | 41-275, unstable | ~1,900 | ~300 |
| Purchases/s, 1,000 items | wrong | ~8,400 | ~7,400-9,000 | ~9,000 | ~3,400-4,200 |
| Costs | Correctness | Waiting; a lock held for the whole work; deadlocks if you lock in different orders | Wasted work on every retry; starvation on hot rows | Logic must fit in SQL | Retries, including false positives |
| Pick it when | Never for shared data | Hot rows, short work, you must read before deciding | Rare conflicts, long or human “think time”, or across systems (HTTP, caches, DynamoDB) | The rule can be a WHERE clause |
Many rows and invariants you can’t name one by one |
Throughput ranges are across three runs; results.md has every number. Correctness columns were identical in all three.
The scene of the crime: one hot row #
Here’s what happened when 32 buyers wanted the same item.
| Strategy | Sold | Stock went down by | Retries | Gave up | p99 |
|---|---|---|---|---|---|
| Naive | 800 | 28 | 0 | 0 | 74-355 ms |
FOR UPDATE |
800 | 800 | 0 | 0 | 1.5-2.3 s |
| Optimistic | 766-798 | same as sold | 8,568-11,740 | 2-34 | 0.7-7.3 s |
Atomic UPDATE |
800 | 800 | 0 | 0 | ~56 ms |
| Serializable | 772-780 | same as sold | ~5,400 | 20-28 | ~1.0 s |
Four clues stand out:
- The naive version told 800 buyers “you got it” and moved the stock by 28. Every buyer read the same number, and each wrote that number minus one. Even at low contention (1,000 items) it lost 16-25 updates per run, because two random buyers picking the same item in the same few milliseconds is common. A lost update needs only a small collision chance multiplied by enough traffic, not a hot row.
FOR UPDATEturns a hot row into a single-file queue. Each buyer holds the lock through its 2 ms of work, so throughput is about 1 / (work + round trips): ~200-280/s, no matter how many buyers you add. Everyone gets served, but the p99 was over 1.5 s.- Optimistic does the same queueing, badly, and turns out to be a false lead here. Only one of the 32 buyers who read version n can win, and the other 31 throw away their work and try again. That was 11-15 retries per purchase, throughput that swung 7× between runs, and up to 34 buyers who gave up after 100 attempts. Under heavy contention, optimistic locking behaves like a lock with extra waste and no fairness.
- The atomic
UPDATEwas ~7× faster than both and never wrong, because the 2 ms of work happens before the statement and the row is locked only for the instant of the write. In PostgreSQL’s default Read Committed, a concurrentUPDATEwaits for the other writer, then re-checks itsWHEREagainst the newest row version. Sostock > 0is evaluated on the current stock, not on a stale read. That re-check is the clever bit, and the reveal of the whole case: the database does the careful thing for you, without a lock held across your work.
At low contention the differences mostly vanish: everything except Serializable ran at roughly 7,400-9,300 purchases/s with a p99 under 8 ms. Optimistic needed 18-23 retries in 800 purchases. Contention, not the strategy, decides the cost. If you remember one line from this post, I’d make it that one.
Case 1: the last 10 tickets #
50 buyers hit “buy” at the same moment for the last 10 tickets:
| Strategy | Buyers told “you got one” | Stock left |
|---|---|---|
| Naive | 50 | 9 |
FOR UPDATE |
10 | 0 |
| Optimistic | 10 | 0 |
Atomic UPDATE … WHERE stock > 0 |
10 | 0 |
| Serializable | 10 | 0 |
Diagram source
xychart-beta
title "Buyers told you got one, for the last 10 tickets"
x-axis ["Naive", "FOR UPDATE", "Optimistic", "Atomic UPDATE", "Serializable"]
y-axis "buyers"
bar [50 , 10 , 10 , 10 , 10]
The naive version sold 50 tickets and still showed 9 left. Every correct strategy sold exactly 10. It’s hard to think of a clearer picture of why this matters: the evidence practically confesses.
What I’d use: the atomic UPDATE with RETURNING, checking the row count:
UPDATE events SET seats_left = seats_left - $2
WHERE id = $1 AND seats_left >= $2
RETURNING seats_left; -- no row back = sold out
If you also need to insert the order and charge a card, do it in the same transaction after this statement. The row stays locked only from the UPDATE to the commit, not during the price calculation before it. Keep slow external calls (the payment provider) outside the transaction: reserve, commit, charge, then confirm or release the reservation.
For assigned seats (seat 14C, not “any seat”), use SELECT … FOR UPDATE SKIP LOCKED to grab a free row nobody else is holding. That’s the same pattern a job queue uses (the delayed retries post builds one), and a small PostgreSQL feature that pays for itself. The outbox relay in my event-driven reference uses it so several replicas can publish without sending the same row twice. (SKIP LOCKED exists since PostgreSQL 9.5.)
Case 2: two people editing the same profile #
An admin opens a customer’s profile, spends three minutes on it, and saves. Meanwhile a colleague changed the phone number and saved. The first save silently puts the old phone number back.
Here the obvious suspect is innocent: a database lock can’t fix this. The three minutes happen between two HTTP requests, and you can’t hold a transaction open across them. The blogging platform I run had this exact gap. Saving a post locked the row with FOR UPDATE, so the revision history and slug redirect were written consistently. But that lock lasted only for the save, so two editors who opened the same post could still overwrite each other. The fix was to keep the lock and add a version check (below). Now a save from an editor opened before someone else’s save is refused. The author keeps their text in the form, with a link to the latest version. Saving again is a deliberate overwrite, and the other save stays in the revision history.
Optimistic concurrency is the fix, carried through the UI:
UPDATE profiles SET phone = $2, name = $3, version = version + 1
WHERE id = $1 AND version = $4; -- $4 = the version the form was loaded with
-- 0 rows: someone saved first. Show their changes; don't overwrite.
Over HTTP this is the standard ETag / If-Match pair: GET returns ETag: "7", PUT sends If-Match: "7", and a mismatch returns 412 Precondition Failed (RFC 9110). Here the retry isn’t a loop; it’s a person reviewing a conflict, which is fine because conflicts are rare. The same idea works from a database row all the way up to a human decision.
The same idea exists in other stores:
- DynamoDB:
ConditionExpression: "version = :v", which fails withConditionalCheckFailedException. - MongoDB:
updateOne({_id, version: v}, {$set: …, $inc: {version: 1}})and checkmatchedCount. - Mongoose:
optimisticConcurrency: true, but only forsave().
Case 3: counters and balances #
Likes, view counts, API quota used, an account balance. People write these as read-add-write all the time. The naive run above is exactly that bug: 772 of 800 increments lost on one hot row.
What I’d use: UPDATE … SET n = n + 1, with a WHERE guard for limits (AND balance >= $amount). It needs no lock, no version and no retry loop, and it was the fastest correct strategy measured. If a single counter row gets so hot that even this queues (millions of likes on one post), the next step isn’t a different lock. Split it: N counter rows summed on read, or increments buffered and flushed in batches.
Case 4: a decision that reads several rows #
“Approve this leave request only if at least two people stay on call that day.” The decision reads other rows than the one it writes, so a version on the written row doesn’t protect it. That’s the write-skew case from the isolation-levels post. The options:
FOR UPDATEon every row the decision reads;- a lock on a parent row that all writers touch (the team’s row for that day);
SERIALIZABLEwith a retry loop.
Serializable is the easiest to get right, and it costs retries even when nothing truly conflicts. At low contention, on 1,000 different items, it needed ~480 retries in 800 purchases and ran at under half the speed of the others. PostgreSQL tracks what a transaction read in coarse units: here a whole page of the primary-key index (an SIReadLock on items_pkey, visible in pg_locks). Two buyers of different items on the same index page therefore look like a conflict. The PostgreSQL docs say to expect these false positives; budget for them.
Diagram source
flowchart TD
Q1{"Rule fits in a WHERE clause?"} -- yes --> A["Atomic UPDATE"]
Q1 -- no --> Q2{"Decision reads several rows?"}
Q2 -- yes --> S["SERIALIZABLE with a retry loop"]
Q2 -- no --> Q3{"Human or another request between read and write?"}
Q3 -- yes --> O["Optimistic version check"]
Q3 -- no --> Q4{"Hot row, short local work?"}
Q4 -- yes --> L["SELECT … FOR UPDATE"]
Q4 -- no --> O
The details that trip up detectives #
These are the small details that separate a design that works in a demo from one that works on a busy day.
- Lock order. Two transactions that each
FOR UPDATErows A and B in opposite orders deadlock. PostgreSQL detects it afterdeadlock_timeout(1 s by default) and aborts one with SQLSTATE40P01. Always lock in a fixed order (by id), and treat 40P01 as retryable. - Don’t wait forever. Set
lock_timeout(e.g.SET LOCAL lock_timeout = '2s'), or useNOWAITto fail immediately, so a stuck transaction can’t make every request pile up behind it. - Never hold a row lock across a network call. A 2 ms “work” step capped a hot row at ~250 purchases/s. A 300 ms call to a payment provider would cap it at about 3/s.
- Choose the weaker lock if you can.
FOR NO KEY UPDATEis what a plainUPDATEtakes when it doesn’t change a key column. It doesn’t block foreign-key checks from other tables, whichFOR UPDATEdoes. - Retries need limits and jitter. Unbounded retries turn contention into a self-inflicted overload. The demo backs off with jitter, gives up after 100 attempts, and counts every give-up.
Remember this
- If the rule fits in a
WHEREclause, write it as one statement.- Contention, not the strategy, decides the cost.
- A human between read and write needs a version check, not a lock.
Case closed: what I’d do by default #
- Write it as one statement if the rule fits in a
WHEREclause: counters, stock, balances, quotas. SELECT … FOR UPDATE(withlock_timeout, in a fixed order) when you must read before deciding, the row can be hot, and the work between read and write is milliseconds of local code.- Optimistic version checks when conflicts are rare, when the gap between read and write is a human or another request, or when there’s no transaction to hold: HTTP APIs, DynamoDB, caches.
SERIALIZABLEwith a retry loop for decisions that read many rows, with the retry rate on a dashboard.FOR UPDATE SKIP LOCKEDfor queues and “give me any free one” allocation.
What I like most about this topic is that the best answer is usually the simplest one: tell the database what you mean in one statement, and let decades of careful engineering in its concurrency control do the rest.
Checked on PostgreSQL 17.11 and pgx 5.12.0 (Nov 2026), on one laptop (i7-8550U, 8 threads, everything in Docker), with 2 ms of simulated work between read and write. Across a network every round trip is longer, which makes locks held during work and retry loops both more expensive. Code and full results: database-tradeoffs-lab/05-locking.
Comments
No comments yet.
Sign in to comment. We'll email you a link; no password needed.