lost updates
read, modify, write, and one change vanishes. four fixes, compared on a real postgres.
- address
- everything.transactions.lost_updates
- part
- part 11, transactions and isolation
- chapter
- chapter 6 of 11
- reading time
- 8 min
a lost update is read, modify, write, twice at once: both transactions read 100.00, both compute a new balance in the app, and the second write replaces the first. at postgres's default level nothing stops it and nobody gets an error. there are four fixes: let the UPDATE do the arithmetic, lock the row as you read it with FOR UPDATE, check a version column, or run at REPEATABLE READ and retry.
the picture
you know the classic bug: a like counter, two clicks at the same moment, and the count goes up by one. the code looks fine. it reads the count, adds one, saves it. it is fine, as long as nobody else does the same thing in between.
think of two people with a copy of the same spreadsheet (the row), each adding their own line to a total (the deposit) and saving the file back (the UPDATE). whoever saves second wins, and the first person's line is gone, even though the save itself worked perfectly.
here it is on a real server: alice has 100.00, T1 deposits 10.00 and T2 deposits 20.00, at the same time. the right answer is 130.00. switch between the five ways to write it.
T1 wants to add 10 to alice's balance.
why waiting isn't enough
look at step 6 of the first run. T2 does wait: T1 holds alice's row lock, and postgres never lets two transactions write one row at the same time. the wait isn't the problem. the problem is what T2 writes when it wakes up. SET balance = 120.00 is a constant the app worked out from a read that is now stale. postgres has no way to know where that number came from, so it writes it.
hover a stage.
that's also why wrapping the read and the write in BEGIN and COMMIT doesn't help. a plain SELECT at READ COMMITTED takes no lock and promises nothing about the next statement. it reads, that's all.
/* T1 */ BEGIN;
/* T1 */ UPDATE accounts SET balance = balance + 10 WHERE id = 1;
/* T2 */ UPDATE accounts SET balance = balance + 20 WHERE id = 1; -- waits
/* T1 */ COMMIT;
/* T2 */ -- wakes up. alice = ?fix 1: let the UPDATE do the arithmetic
if the new value is a function of the old one, say so in the UPDATE and skip the read. one statement, so there's nothing in between to go stale:
UPDATE accounts SET balance = balance + 10.00 WHERE id = 1
RETURNING owner, balance;| ownertext | balancenumeric |
|---|---|
| alice | 110.00 |
it stretches further than you'd think. a withdrawal that mustn't overdraw is a WHERE:
UPDATE accounts SET balance = balance - 50.00
WHERE id = 1 AND balance >= 50.00
RETURNING owner, balance;
UPDATE accounts SET balance = balance - 50.00
WHERE id = 3 AND balance >= 50.00
RETURNING owner, balance;| ownertext | balancenumeric |
|---|---|
| alice | 50.00 |
| ownertext | balancenumeric |
|---|
alice had the money, carol (0.00) didn't: UPDATE 0, no rows back, and the app knows the withdrawal didn't happen. under concurrency the WHERE is checked again on the row's newest version after any wait, so two withdrawals can't both pass on the same 50.00. this is the fix to reach for first.
fix 2: lock it when you read it
sometimes the new value needs logic the database can't run: an API call, a pricing rule in your code. then read with FOR UPDATE. the row is locked from the read until COMMIT, so a second FOR UPDATE on it waits, and when it wakes up it gets the newest version, not the one from before. in the figure, T2's read returns 110.00. the cost is that T2 holds nothing and does nothing while it waits, so keep the transaction short. SELECT ... FOR UPDATE and SKIP LOCKED has the other strengths and NOWAIT.
fix 3: check a version
web apps often can't hold a transaction open while a person looks at a form. so don't: read the row and a version number, let the user think, then write only if the version is still the one you read. bank's accounts already have a version column:
SELECT balance, version FROM accounts WHERE id = 1;
UPDATE accounts SET balance = 110.00, version = version + 1
WHERE id = 1 AND version = 0;
UPDATE accounts SET balance = 120.00, version = version + 1
WHERE id = 1 AND version = 0;
SELECT balance, version FROM accounts WHERE id = 1;| balancenumeric | versionint4 |
|---|---|
| 100.00 | 0 |
| balancenumeric | versionint4 |
|---|---|
| 110.00 | 1 |
the first save is UPDATE 1 and bumps the version. the second one, still holding version 0, matches nothing: UPDATE 0. that zero is the whole signal. the app re-reads (110.00, version 1), redoes its work, and saves again. this is optimistic locking: nobody waits, conflicts are found at write time. most ORMs have it built in (a @Version field in JPA, lock_version in Rails).
fix 4: REPEATABLE READ, and retry
run the read-modify-write at REPEATABLE READ and postgres refuses the second write itself. T2 waits for T1's lock, sees that the row changed after its snapshot, and fails with 40001: could not serialize access due to concurrent update. no app-side check, but every writer needs a retry loop: the whole transaction, from BEGIN, with a fresh snapshot. SERIALIZABLE does the same for this case.
the scoreboard
UPDATE 0, and its retry would make 130.00.| fix | who waits | who has to retry | reach for it when |
|---|---|---|---|
SET balance = balance + x | the second writer, briefly | nobody | the new value is arithmetic on the old one |
SELECT ... FOR UPDATE | the second reader, until the first commits | nobody | the new value needs app logic, inside one short transaction |
| version column | nobody | the app, on UPDATE 0 | a person sits between the read and the write |
| REPEATABLE READ | the second writer, then it fails | the app, on 40001 | many rows are read and written, and you'd rather not reason about each one |
keylines
- a lost update is a write computed from a stale read. no error, just a missing change.
- the row lock makes the second writer wait, but not rethink.
SET x = x + 1re-computes from the newest row after the wait. reach for it first.- FOR UPDATE makes the second reader wait. a version column makes the second writer get
UPDATE 0. - REPEATABLE READ turns a lost update into a 40001, which your app must retry.