Alex has one hundred dollars. He pays the pizza shop twenty and the flower shop forty, at the same moment, from one bank account. Both payments say done. He should have forty left. He has sixty, and the bank is twenty dollars short. There was no error anywhere. This article shows why, and three ways to make it safe.
The video tells the same story in five minutes. This is the written version, with the SQL.
One account, one row
Alex's account is one row in MySQL:
CREATE TABLE accounts (
owner VARCHAR(64) NOT NULL,
balance INT NOT NULL,
PRIMARY KEY (owner)
) ENGINE=InnoDB;
INSERT INTO accounts VALUES ('Alex', 100);
What MySQL gets right: the row lock
First, the case that works. Each payment takes its money in one statement:
-- the pizza payment
START TRANSACTION;
UPDATE accounts SET balance = balance - 20 WHERE owner = 'Alex';
-- the flower payment, at the same moment
START TRANSACTION;
UPDATE accounts SET balance = balance - 40 WHERE owner = 'Alex'; -- waits
The flower payment's update waits, because the pizza payment's update locked Alex's row. A lock is how MySQL guards a row while one payment writes to it. The manual (17.7.1, InnoDB Locking) says that if one transaction holds an exclusive lock on a row, another transaction's request for a lock on that row "cannot be granted immediately", and it has to wait.
Now the pizza payment finds that the pizza shop's account is closed, so it rolls back:
ROLLBACK; -- the pizza payment takes nothing, and its lock is released
The flower payment's update runs, on the balance that is really there, one hundred. Alex has sixty, which is exactly right.
What goes wrong: read, then write
Many apps do not write balance - 40. They read the balance first, to check there is enough money, then work out the new balance in the app, and write the number:
-- both payments, at the same moment
START TRANSACTION;
SELECT balance FROM accounts WHERE owner = 'Alex'; -- 100, for both of them
-- the pizza payment: 100 - 20 = 80
UPDATE accounts SET balance = 80 WHERE owner = 'Alex';
COMMIT;
-- the flower payment: 100 - 40 = 60
UPDATE accounts SET balance = 60 WHERE owner = 'Alex';
COMMIT;
If the flower payment's update arrives while the pizza payment still holds the lock, it waits, and then it still writes 60. Both commits succeed. Alex should have forty, and he has sixty, as if the pizza payment never happened. Its update was written over. This is called a lost update.
Why didn't the lock help?
An ordinary read takes no lock. The manual says "A consistent read does not set any locks on the tables it accesses" (17.7.2.3). So both reads went straight through, and both got one hundred.
The lock did its job on the writes: the flower payment's update waited for the pizza payment. But MySQL only saw an update that said "set the balance to 60". It could not know that 60 came from an old balance, worked out in the app. The manual says it plainly: "the regular SELECT statement does not give enough protection" (17.7.2.4).
The lock guarded the write, but nothing guarded the read.
The isolation level
MySQL has a setting for what a read can see while another payment is changing the row: the isolation level.
SELECT @@transaction_isolation;
-- REPEATABLE-READ
InnoDB offers the four levels of the SQL standard, and its default is REPEATABLE READ (17.7.2.1). Here is what the flower payment's SELECT returns while the pizza payment has written 80 and has not committed yet:
| Level | What the read returns |
|---|---|
| READ UNCOMMITTED | 80, a change that is not committed. If it rolls back, the read saw a balance that never existed (a dirty read). |
| READ COMMITTED | 100, then 80 once the pizza payment commits. Every read gets the latest committed balance. |
| REPEATABLE READ | 100, and still 100 after the commit. Every read in the transaction shows what the first read saw. |
| SERIALIZABLE | It waits. Every plain read inside a transaction becomes a locking read (FOR SHARE). |
Read committed does not stop the lost update
You might think read committed fixes it, because every read gets the latest balance. That was my first answer too. But both payments read before either one wrote, so both got the same latest balance: one hundred. The danger is the gap between the read and the write, and no ordinary read closes it.
(The strictest level does stop it in MySQL, but through a deadlock: both reads take a shared lock, both payments then try to write, and MySQL rolls one back with error 1213. It works, at the price of making every read wait.)
Three ways to make it safe
1. Let MySQL do the arithmetic. The update says "take forty off", and MySQL takes it from the latest balance, under the row lock:
UPDATE accounts SET balance = balance - 40 WHERE owner = 'Alex';
The enough-money check moves into the same statement. Then look at the rows changed: one means paid, zero means there was not enough money.
UPDATE accounts SET balance = balance - 40
WHERE owner = 'Alex' AND balance >= 40;
2. Lock what you read. Add FOR UPDATE to the select, so the read takes a lock:
START TRANSACTION;
SELECT balance FROM accounts WHERE owner = 'Alex' FOR UPDATE;
-- the flower payment's read waits here until the pizza payment commits, then returns 80
UPDATE accounts SET balance = 40 WHERE owner = 'Alex'; -- 80 - 40
COMMIT;
The manual: "A SELECT ... FOR UPDATE reads the latest available data, setting exclusive locks on each row it reads" (17.7.2.4).
3. Check before you write. The update sets the new balance only if the balance is still what the app read:
UPDATE accounts SET balance = 60 WHERE owner = 'Alex' AND balance = 100;
-- Query OK, 0 rows affected
Zero rows changed means another payment wrote first. Start the payment again, as a new transaction: at REPEATABLE READ a plain read inside the same transaction keeps showing the old balance. The new try reads 80 and writes 40 with AND balance = 80. This is optimistic locking; a version number column is its common form.
Locks have a cost: the deadlock
Say Alex pays Sam while Sam pays Alex. Each payment locks one row, then waits for the row the other one locked:
-- Alex pays Sam
START TRANSACTION;
UPDATE accounts SET balance = balance - 10 WHERE owner = 'Alex';
UPDATE accounts SET balance = balance + 10 WHERE owner = 'Sam'; -- waits for Sam's payment
-- Sam pays Alex, at the same moment
START TRANSACTION;
UPDATE accounts SET balance = balance - 5 WHERE owner = 'Sam';
UPDATE accounts SET balance = balance + 5 WHERE owner = 'Alex'; -- waits for Alex's payment
Both would wait forever. That is a deadlock. InnoDB "automatically detects transaction deadlocks and rolls back a transaction or transactions to break the deadlock" (17.7.5), and the one it rolls back gets this error:
ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
The other payment goes through. Your app catches the error and tries the rolled-back payment again. The manual's advice: "Always be prepared to re-issue a transaction if it fails due to deadlock" (17.7.5.3).
What this does not cover
- A waiting statement does not wait forever. After
innodb_lock_wait_timeout(50 seconds by default) it fails with error 1205, and MySQL rolls back that statement, not the whole transaction (17.20.5). - PostgreSQL behaves differently at REPEATABLE READ: the second payment's update fails with
ERROR: could not serialize access due to concurrent update, and the app has to start the payment again. Its default level is READ COMMITTED, which lets the lost update through, as MySQL's does. -
NOWAITandSKIP LOCKEDmake a locking read fail at once, or skip locked rows, instead of waiting. The manual warns that skipping locked rows gives an inconsistent view, so it is for queue-like tables, not for a balance. - Gap locks, next-key locks and phantoms come later in the series.
The law
The lock guards the write, not the read. Lock what you read, or let the database do the arithmetic.
Go deeper
- Transaction isolation levels (MySQL 8.4 Reference Manual)
- Consistent nonlocking reads (MySQL 8.4 Reference Manual)
- Locking reads (MySQL 8.4 Reference Manual)
- Deadlock detection and how to minimize and handle deadlocks (MySQL 8.4 Reference Manual)
- InnoDB error handling (MySQL 8.4 Reference Manual)
- Transaction isolation (PostgreSQL 18 documentation)
Next time
This is part 4 of Database Internals. Next time, the row already holds the new balance, but repeatable read still shows the old one. We'll find out where that old balance comes from.
The behaviour in this article was checked on a MySQL 8.0 server, and the PostgreSQL case on PostgreSQL 16. Alex, Sam, the shops, the bank and the amounts are an invented example. Have you ever found a balance or a counter that was wrong after two requests ran at the same moment? How did you fix it?
Top comments (0)