Sub topic 8
Lost Updates and How to Prevent Them
Assume you know basic SELECT and UPDATE statements and can use BEGIN, COMMIT, and ROLLBACK. Also assume that two transactions can run at the same time against the same database.
A lost update occurs when one transaction overwrites a change made by another transaction. The database accepts both updates, but the final row contains only one transaction's result.
The read-modify-write problem
Suppose an account has a balance of 100. Two customers deposit money at nearly the same time:
- Transaction A reads 100.
- Transaction B reads 100.
- Transaction A calculates 110 and writes it.
- Transaction B calculates 120 and writes it.
The final balance is 120. The deposit from A has disappeared. The correct balance should be 130.
This often happens when application code reads a value, performs arithmetic outside the database, and then writes the result.
-- Initial state
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance integer NOT NULL
);
INSERT INTO accounts (id, balance) VALUES (1, 100);
-- Unsafe pattern in two concurrent sessions
SELECT balance FROM accounts WHERE id = 1;
-- Application calculates a new value from 100
UPDATE accounts
SET balance = 110
WHERE id = 1;The default READ COMMITTED isolation level usually does not prevent this pattern. Each UPDATE can see a row that another transaction changed after the first transaction read it.
Let the database perform the update
For arithmetic changes, put the calculation inside the UPDATE. The database evaluates the expression while changing the row.
UPDATE accounts
SET balance = balance + 10
WHERE id = 1;
UPDATE accounts
SET balance = balance + 20
WHERE id = 1;When these statements both commit, the balance becomes 130. Each update uses the current stored balance instead of an old value copied into application memory.
This approach works well for counters, inventory changes, and account adjustments. Add a condition when the operation must obey a limit.
UPDATE accounts
SET balance = balance - 30
WHERE id = 1
AND balance >= 30;The application should check the number of affected rows. Zero affected rows can mean that the account did not exist or that the balance was too small.
Lock the row before reading it
When the application needs to read a row, make a decision, and then write a derived value, use a row lock. In PostgreSQL, MySQL InnoDB, and several other systems, SELECT ... FOR UPDATE locks the selected rows until the transaction ends.
BEGIN;
SELECT balance
FROM accounts
WHERE id = 1
FOR UPDATE;
-- Check the value in application code, then write the decision
UPDATE accounts
SET balance = balance - 30
WHERE id = 1;
COMMIT;A second transaction that tries to lock the same row waits until the first transaction commits or rolls back. It then reads the newer balance.
| Technique | Best use | Main cost |
|---|---|---|
| Atomic `UPDATE` | Simple increments or decrements | Cannot express every business rule |
| `SELECT ... FOR UPDATE` | Multi-step decisions about one row | Waiting and possible deadlocks |
| Version check | Web requests with short database transactions | Application must handle rejected updates |
Use optimistic version checks
An alternative is optimistic concurrency control. Store a version number and update only if the version is still the one that was read.
CREATE TABLE documents (
id integer PRIMARY KEY,
body text NOT NULL,
version integer NOT NULL
);
INSERT INTO documents VALUES (1, 'First draft', 1);
-- The application read version 1
UPDATE documents
SET body = 'Edited draft',
version = version + 1
WHERE id = 1
AND version = 1;If the update affects zero rows, another transaction changed the document first. The application must reload the row, merge the changes, or tell the user that the edit is stale.
Higher isolation can also help. SERIALIZABLE may abort one conflicting transaction instead of silently allowing a lost update. The application must retry the whole transaction after a serialization failure.
Exercise
Two requests both read a stock count of 5. Each wants to sell 3 items. Which database-side condition prevents the stock from becoming negative?
Show answer
Use UPDATE inventory SET stock = stock - 3 WHERE product_id = ... AND stock >= 3, then reject the request when the affected-row count is zero.