Sixteen clients withdrew £1,600 from an account holding £100 in my test, every withdrawal inside a transaction, on PostgreSQL 18.6, without one error. The final balance read zero, so nothing looked wrong until I counted the withdrawal rows.
BEGIN and COMMIT don't make a read and a later write atomic against other sessions at READ COMMITTED, which is the Postgres default. There are four standard fixes: a conditional UPDATE, a row lock, REPEATABLE READ and SERIALIZABLE. The pages that rank for this problem explain them well (Craig Ringer's 2014 post on read-modify-write cycles, now hosted by EDB, is still the best short one), but almost none of them measure anything. So I ran all four on PostgreSQL 18.6: Docker on a 2-vCPU, 2 GiB colima VM, default configuration, pgbench with 16 clients and 12-second runs. The absolute numbers are small and repeats varied by up to 10%. Read the ratios.
How Does a Double Spend Happen in Postgres at READ COMMITTED?
The broken version looks reasonable in a code review:
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- app checks balance >= 100
UPDATE accounts SET balance = 9900 WHERE id = 1; -- value computed in the app
INSERT INTO withdrawals (account_id, amount) VALUES (1, 100);
COMMIT;
All sixteen clients read the same balance, queue on the row lock, and write the same new value one after another. Each £1 drop in the balance funds sixteen £1 withdrawals. That is a lost update, and the transaction did nothing to stop it.
I started the account at 10,000 pence and fired 1,600 withdrawals of 100 pence at it. A correct system pays 100 of them.
| Variant | Withdrawals paid | Final balance |
|---|---|---|
App-computed SET balance = 9900 | 1,598 to 1,600 | 0 |
SET balance = balance - 100 after a stale check | 115 | -1,500 |
Same, plus CHECK (balance >= 0) | 100 | 0 (4 rejected with 23514) |
Conditional UPDATE | 100 | 0 |
SELECT ... FOR NO KEY UPDATE first | 100 | 0 |
REPEATABLE READ, no retry | 100 | 0 (876 failed with 40001) |
SERIALIZABLE, no retry | 100 | 0 (889 failed with 40001) |
The second row is the version people write after they learn about lost updates. The arithmetic is now relative, but the balance check still ran against a stale read, so all sixteen clients passed it on the last pound and fifteen overdrew.
This isn't a lab curiosity. Flexcoin lost 896 BTC on 2 March 2014 when an attacker sent thousands of simultaneous transfer requests that overdrew accounts before the balances updated. The ACIDRain paper (Warszawski and Bailis, SIGMOD 2017) found 22 such vulnerabilities in 12 self-hosted e-commerce applications. Only 5 came from weak isolation levels. The other 17 came from transactions scoped around the wrong statements.
Does an Atomic UPDATE Prevent Double Spending in Postgres?
Yes, for a rule that lives on one row. Move the check into the statement that writes:
UPDATE accounts
SET balance = balance - 100
WHERE id = 1 AND balance >= 100
RETURNING balance;
At READ COMMITTED, a second UPDATE that hits a row locked by the first waits for it to commit, then re-evaluates its WHERE clause against the new row version. If the balance no longer covers the amount, it updates zero rows. Your code has to treat zero rows as "insufficient funds", which is the step people forget.
Add CHECK (balance >= 0) as well. In the table above it turned an overdraft into four 23514 errors, at the cost of one comparison per write. (I ran that row through 16 parallel psql sessions, because pgbench stops a client on a constraint error.) A check violation on a balance means some code path is skipping the guard, so alert on it rather than retrying.
The conditional UPDATE has two limits. It protects a single row, and it relies on the wait-and-recheck behaviour that only READ COMMITTED has. At REPEATABLE READ the same statement fails with could not serialize access due to concurrent update.
SELECT FOR UPDATE vs SERIALIZABLE in Postgres 18: Benchmark
Each transaction debits an account and inserts a withdrawal row. I compared the conditional UPDATE, a SELECT ... FOR NO KEY UPDATE followed by a check in the client, and a plain read-then-write at REPEATABLE READ and at SERIALIZABLE with pgbench --max-tries=0, which retries a failed transaction immediately and forever. Three workloads: every transaction on one account (think of a platform fee account), a Zipfian skew of 1.1 over 100,000 accounts, and uniform random.
Transactions per second with statements sent back to back over a Unix socket (retries in brackets):
| Workload | Conditional UPDATE | FOR NO KEY UPDATE | REPEATABLE READ | SERIALIZABLE |
|---|---|---|---|---|
| One hot account | 5,589 | 5,187 | 3,712 (165,893) | 2,832 (172,521) |
| Zipfian 1.1 | 19,906 | 14,866 | 8,054 (95,161) | 8,548 (99,589) |
| Uniform | 21,017 | 19,733 | 16,793 (15) | 16,866 (24) |
No production client talks to Postgres with zero latency, so I repeated it with a 1 ms pause after every statement to stand in for a network round trip:
| Workload | Conditional UPDATE | FOR NO KEY UPDATE | REPEATABLE READ | SERIALIZABLE |
|---|---|---|---|---|
| One hot account | 277 | 197 | 170 (29,880) | 170 (29,821) |
| Zipfian 1.1 | 2,534 | 1,662 | 1,343 (17,553) | 1,307 (18,417) |
| Uniform (median of 3) | 3,732 | 2,833 | 2,824 (5) | 2,828 (3) |
When accounts rarely collide, the isolation level barely matters. With round trips, the row lock and both stricter levels land within 1% of each other. The conditional UPDATE is 32% ahead only because it is one statement shorter. Without round trips, SERIALIZABLE costs about 15% against the row lock, which is the price of tracking predicate locks.
Contention changes the picture. On the skewed workload the two retrying levels manage between 40% and 53% of the conditional UPDATE. On the hot account with round trips, each committed withdrawal at SERIALIZABLE burned nearly 15 failed attempts (29,821 retries for 2,038 commits). Every one of those is a full transaction of wasted work, and in a real service it is also wasted application time.
How Fast Can Postgres Update One Hot Account Row?
Look at the hot-account row of the second table again: 277, 197, 170, 170. All four approaches collapse, because one row can only be written by one transaction at a time and the lock is held across network round trips. The conditional UPDATE held it for two pauses and the explicit lock for three. Throughput on a hot row is one divided by how long you hold the lock, whatever isolation level you pick.
So shorten the hold. This is the same debit and insert as a single statement in autocommit mode:
WITH debit AS (
UPDATE accounts SET balance = balance - $1
WHERE id = $2 AND balance >= $1
RETURNING id
)
INSERT INTO withdrawals (account_id, amount)
SELECT id, $1 FROM debit;
With the same 1 ms pauses before and after it, that ran at 6,493 transactions a second on the hot account. That is 23 times the multi-statement version. When one statement isn't enough, the next step is to stop having a hot row, with sub-balances or an append-only journal, which I covered in TigerBeetle vs Postgres for payment ledgers.
Advisory locks behave like row locks here. pg_advisory_xact_lock(account_id) ran at 5,177 on the hot account against 5,187 for the row lock. Postgres doesn't enforce them, though, so a code path that forgets to take the lock is unprotected. They earn their place when the thing you need to lock isn't a single row.
Does SELECT FOR UPDATE Prevent Write Skew Across Accounts?
No. Take a customer with two accounts holding 100 each and a rule that the combined balance must not go negative. Two requests arrive together, each withdrawing 150 from a different account after checking that the total covers it.
| Approach | Combined balance | What happened |
|---|---|---|
READ COMMITTED, plain read | -100 | Both committed |
READ COMMITTED, row lock on own account | -100 | Both committed |
REPEATABLE READ, plain read | -100 | Both committed, no error |
REPEATABLE READ + advisory lock on customer | -100 | Both committed |
READ COMMITTED + advisory lock on customer | 50 | Second one declined |
READ COMMITTED, row locks on all the customer's accounts | 50 | Second one declined |
SERIALIZABLE, plain read | 50 | Second one got 40001 |
The two transactions write different rows, so no row lock ever conflicts and REPEATABLE READ has nothing to object to. Postgres implements that level as snapshot isolation, and the manual warns that business rules enforced there are unlikely to work without explicit locks.
Row four is the one that surprised me. The advisory lock call is the first statement in the transaction, so at REPEATABLE READ the snapshot is taken before the wait. When the lock is granted, the transaction reads a total that is already out of date. Advisory locks belong with READ COMMITTED, where the next statement gets a fresh snapshot.
Why Does SERIALIZABLE Abort Transactions That Don't Conflict?
Because predicate locks follow the query plan, not your intent. I gave each of 16 clients its own account, so no two transactions ever shared a row, and ran them at SERIALIZABLE.
| Table and plan | Transactions/s | Retries |
|---|---|---|
| 50 rows, sequential scan | 1,978 | 144,276 |
50 rows, enable_seqscan=off | 18,921 | 19 |
| 100,000 rows, 16 adjacent ids | 17,356 | 2 |
| 100,000 rows, ids 5,000 apart | 21,589 | 0 |
On a 50-row table the planner picks a sequential scan for a primary-key lookup, and the manual says a sequential scan always takes a relation-level predicate lock. Every transaction then conflicts with every other one. Forcing the index removed 99.99% of the retries.
The same promotion happens on big tables. With the defaults (max_pred_locks_per_transaction 64, max_pred_locks_per_relation -2), predicate locks on more than about 32 pages or rows of one table are merged into a lock on the whole table. I checked pg_locks on a 200,000-row ledger table: an index scan returning 31 scattered rows held 31 page-level predicate locks, and one returning 33 held a single lock on the entire table. A serializable transaction that lists a customer's last 50 ledger entries can therefore conflict with unrelated writers. None of the ranking guides mention these settings. The release notes for PostgreSQL 17, 18 and 19 list no changes to this behaviour.
How to Retry SQLSTATE 40001 and 40P01 in Postgres
The manual says to retry 40001 (serialization_failure) unconditionally and that retrying 40P01 (deadlock_detected) may be advisable. The whole transaction has to run again, reads and decisions included, and Postgres will not do it for you.
Nor will your driver. sqlx has no isolation enum (you pass begin_with("BEGIN ISOLATION LEVEL SERIALIZABLE")) and no retry. pgx, node-postgres, Django and Rails surface the error and stop. Spring Framework 7 ships @Retryable in core, opt-in, with 3 retries and a 1-second delay by default. The one mainstream helper that loops is crdbpgxv5.ExecuteTx, and it was written for CockroachDB.
Four rules for the wrapper:
1. Put COMMIT inside it. Under SERIALIZABLE the failure can arrive at commit time.
2. Back off with jitter. My benchmark retried instantly, which is the worst case.
3. Cap the attempts and return a clear error to the caller.
4. Keep calls to a PSP or a message broker out of the retried block, or protect them with an idempotency key.
Deadlocks deserve prevention more than retries. I ran transfers between 20 accounts with the debit and credit issued in request order, then again taking both row locks first in id order:
SELECT id FROM accounts
WHERE id IN ($1, $2)
ORDER BY id
FOR NO KEY UPDATE;
| Transfers | Transactions/s | Deadlocks in 15 s | p99 latency |
|---|---|---|---|
Two UPDATEs in request order | 32 | 18 | 4,010 ms |
| Lock both rows in id order first | 11,266 | 0 | 7.3 ms |
Eighteen deadlocks cost 99.7% of the throughput. deadlock_timeout defaults to 1 second, so Postgres waits a full second before it even looks for a cycle, and everything queued behind those rows waits with it. Of the 485 transactions that completed, 154 took more than a second.
FOR UPDATE vs FOR NO KEY UPDATE With Foreign Keys
Every example above uses FOR NO KEY UPDATE because that is the lock a plain UPDATE takes. FOR UPDATE is stronger than the write it protects, and the difference shows up when another table has a foreign key to accounts. Inserting a child row takes FOR KEY SHARE on the parent, which conflicts with FOR UPDATE and nothing else.
I held each lock on one account for three seconds and inserted a ledger entry that referenced it from another session with lock_timeout set to 1 second. Behind FOR UPDATE the insert was cancelled at the timeout. Behind FOR NO KEY UPDATE it finished in 1.9 ms. In Django this is select_for_update(no_key=True). The same advice applies to job queues built on SKIP LOCKED.
Postgres vs MySQL vs CockroachDB: Lost Updates in 2026
| Database | Default isolation | Naive read-then-write at the default | Retry signal |
|---|---|---|---|
| PostgreSQL 18 | READ COMMITTED | Loses updates silently | 40001 only at stricter levels, 40P01 for deadlocks |
| MySQL 8.4 (InnoDB) | REPEATABLE READ | Still loses updates | Deadlock 1213 maps to 40001; lock wait timeout 1205 is HY000 after 50 s |
| CockroachDB | SERIALIZABLE | Prevented | 40001 "restart transaction" |
| SQL Server, Oracle | READ COMMITTED | Loses updates | Vendor-specific |
The MySQL row catches people migrating to Postgres and the other way round. InnoDB's REPEATABLE READ applies the snapshot to SELECT but lets DML see the latest committed rows, and it raises no first-updater-wins error. The ACIDRain authors reported triggering lost updates at that level. Postgres at the same level name aborts the second writer. A lock wait timeout in MySQL also rolls back only the statement by default, so the transaction stays open.
CockroachDB takes the opposite trade. Correctness is the default and the retry loop becomes your job, although the server retries implicit and single-batch transactions itself while results fit a 16 KiB buffer. READ COMMITTED has been generally available there since v24.1 in May 2024, and Cockroach's own docs say SELECT FOR UPDATE reduces retries without eliminating them.
My position: a payments service on Postgres should stay at READ COMMITTED and use conditional updates with ordered row locks for anything on one row. Choose SERIALIZABLE per invariant, for rules that span rows, and then run every transaction that writes those rows at that level. SSI only tracks conflicts between serializable transactions, so one READ COMMITTED writer on the same rows brings the write skew back. Running the whole service at SERIALIZABLE is defensible only once the retry wrapper exists and has been load-tested against your hottest account.
What This Means for Payments Engineers
1. Search your code for a SELECT of a balance followed by an UPDATE that writes an application-computed value. Each one is the first row of the first table.
2. Make every debit a conditional UPDATE and check the row count. On hot accounts, put the debit and the journal insert in one statement.
3. Add CHECK (balance >= 0) wherever a negative balance is illegal, and page someone on 23514.
4. Use FOR NO KEY UPDATE, and lock multiple rows in primary-key order.
5. For rules across rows, lock a shared parent (the customer row, or an advisory lock at READ COMMITTED) or move every writer to SERIALIZABLE.
6. Wrap write transactions in a retry for 40001 and 40P01 that includes the commit.
7. Under SERIALIZABLE, check the plan for every small table you read, and graph retries per commit.
8. Test with concurrency. Sixteen clients against one account, then compare the journal total with the balance.
I'm Tom Wang, and I write these from test output where I can get it. The scripts are plain pgbench files, so rerun them on your own hardware before quoting my numbers in a design review.