Lesson 4 of 19
17. Transactions and Locking

17.3 What is a lost update?

3 min read+10 XP

On the train: Two clerks each look at the board: "100 seats left". Each sells one and writes "99" on the board. Two seats were sold, but the board only went down by one.

In the system: A lost update happens when two transactions read the same value, compute a new value from it, and both write. The second write overwrites the first, and one change is lost.

two requests read 100, both write 99; one booking is lost.

Figure: read-modify-write in application code loses updates. Let the database do it in one step.

python

Fixes, from simplest to most general:

  1. Atomic update in the database: UPDATE events SET seats_left = seats_left - 1 WHERE id = 1 AND seats_left > 0. The database reads and writes in one step, and the WHERE stops it going below zero. In the chapter's code, 130 booking attempts for 100 seats sell exactly 100.
  2. Lock the row first (17.6).
  3. Check a version when writing (17.7).
  4. A stronger isolation level that detects the conflict (17.5).

Memory code: "Don't read, think and write back; let the database subtract."