Database Concurrency Problems
What you will learn
- What concurrency means for a database
- The four classic problems: lost update, dirty read, non-repeatable read, phantom read
- How to reproduce and fix a lost update
1. Many users at once
A shop website may serve hundreds of customers at the same moment. Their transactions overlap in time. This is concurrency. When two transactions touch the same rows, the order of their steps matters, and some orders give wrong results.
The examples use a stock table and two connections, a and b, each playing one shopper:
import sqlite3, os, tempfile
path = os.path.join(tempfile.mkdtemp(), "shop.db")
a = sqlite3.connect(path, timeout=0.2, isolation_level=None)
b = sqlite3.connect(path, timeout=0.2, isolation_level=None)
a.execute("CREATE TABLE stock (item TEXT PRIMARY KEY, qty INTEGER NOT NULL)")
a.execute("INSERT INTO stock VALUES ('pen', 10)")
2. Lost update
Shopper A buys 3 pens and shopper B buys 4. The program reads the quantity, calculates in Python and writes the result back:
qa = a.execute("SELECT qty FROM stock WHERE item='pen'").fetchone()[0]
qb = b.execute("SELECT qty FROM stock WHERE item='pen'").fetchone()[0]
print("A read", qa, "| B read", qb)
a.execute("UPDATE stock SET qty = ? WHERE item='pen'", (qa - 3,))
b.execute("UPDATE stock SET qty = ? WHERE item='pen'", (qb - 4,))
print("final qty:", a.execute("SELECT qty FROM stock").fetchone()[0], "(should be 3)")
A read 10 | B read 10
final qty: 6 (should be 3)
Both read 10. A wrote 7, then B wrote 6 over it, and A's purchase vanished. This is a lost update: two read-modify-write cycles overlapped.
The usual fix is to let the database do the arithmetic in one statement:
a.execute("UPDATE stock SET qty = 10")
a.execute("UPDATE stock SET qty = qty - 3 WHERE item='pen'")
b.execute("UPDATE stock SET qty = qty - 4 WHERE item='pen'")
print("final qty:", a.execute("SELECT qty FROM stock").fetchone()[0])
final qty: 3
Each statement reads and writes the row in one step, so neither purchase is lost. Lesson 6.7 shows other cures when you cannot do it in one statement.
The same two purchases in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). Python shows two real connections above; a SQL cell has only one, so the cells below play shopper A and shopper B one after the other, each using the number it read. It adds a small table of its own to your browser's copy; Reset data starts again.
CREATE TABLE stock (item TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 10);
SELECT qty AS a_reads FROM stock WHERE item = 'pen';
SELECT qty AS b_reads FROM stock WHERE item = 'pen';
a_reads
-------
10
(1 row)
b_reads
-------
10
(1 row)
Each shopper calculates in the program (10 - 3 = 7 and 10 - 4 = 6) and writes the result back:
UPDATE stock SET qty = 7 WHERE item = 'pen';
UPDATE stock SET qty = 6 WHERE item = 'pen';
SELECT qty AS final_qty, 3 AS should_be FROM stock;
final_qty should_be
--------- ---------
6 3
(1 row)
A's purchase vanished: the lost update. With the arithmetic inside the statement, each update reads and writes in one step:
UPDATE stock SET qty = 10;
UPDATE stock SET qty = qty - 3 WHERE item = 'pen';
UPDATE stock SET qty = qty - 4 WHERE item = 'pen';
SELECT qty AS final_qty FROM stock;
final_qty
---------
3
(1 row)
CREATE TABLE stock (item TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 10);
SELECT qty AS a_reads FROM stock WHERE item = 'pen';
SELECT qty AS b_reads FROM stock WHERE item = 'pen';
a_reads
-------
10
(1 row)
b_reads
-------
10
(1 row)
Each shopper calculates in the program (10 - 3 = 7 and 10 - 4 = 6) and writes the result back:
UPDATE stock SET qty = 7 WHERE item = 'pen';
UPDATE stock SET qty = 6 WHERE item = 'pen';
SELECT qty AS final_qty, 3 AS should_be FROM stock;
final_qty should_be
--------- ---------
6 3
(1 row)
A's purchase vanished: the lost update. With the arithmetic inside the statement, each update reads and writes in one step:
UPDATE stock SET qty = 10;
UPDATE stock SET qty = qty - 3 WHERE item = 'pen';
UPDATE stock SET qty = qty - 4 WHERE item = 'pen';
SELECT qty AS final_qty FROM stock;
final_qty
---------
3
(1 row)
CREATE TABLE stock (item TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock VALUES ('pen', 10);
SELECT qty AS a_reads FROM stock WHERE item = 'pen';
SELECT qty AS b_reads FROM stock WHERE item = 'pen';
a_reads
-------
10
(1 row)
b_reads
-------
10
(1 row)
Each shopper calculates in the program (10 - 3 = 7 and 10 - 4 = 6) and writes the result back:
UPDATE stock SET qty = 7 WHERE item = 'pen';
UPDATE stock SET qty = 6 WHERE item = 'pen';
SELECT qty AS final_qty, 3 AS should_be FROM stock;
final_qty should_be
--------- ---------
6 3
(1 row)
A's purchase vanished: the lost update. With the arithmetic inside the statement, each update reads and writes in one step:
UPDATE stock SET qty = 10;
UPDATE stock SET qty = qty - 3 WHERE item = 'pen';
UPDATE stock SET qty = qty - 4 WHERE item = 'pen';
SELECT qty AS final_qty FROM stock;
final_qty
---------
3
(1 row)
3. The other three problems
These are names for what one transaction can see of another's work. Whether they can happen depends on the database and its isolation level (lesson 6.5).
| Problem | What happens | Example |
|---|---|---|
| Dirty read | you read data another transaction has changed but not committed | B sees stock 0 while A is still deciding; A then rolls back, so 0 never existed |
| Non-repeatable read | you read a row twice in one transaction and get different values because someone committed in between | an invoice total is 100 at the start and 107 at the end |
| Phantom read | you run the same query twice and the set of rows changes (new rows appear or vanish) | "orders today" returns 12 rows, then 13 |
| Write skew (a serialization anomaly) | two transactions each read the same rows, then each write different rows based on what they read; each result is fine alone, together they break a rule | two doctors both see "2 on call" and both go off call, leaving 0 (lesson 6.5) |
SQLite does not allow dirty reads by default. Here B looks while A has an uncommitted change:
a.execute("UPDATE stock SET qty = 10")
a.execute("BEGIN")
a.execute("UPDATE stock SET qty = 0 WHERE item='pen'")
print("B sees uncommitted?", b.execute("SELECT qty FROM stock").fetchone()[0])
a.execute("ROLLBACK")
B sees uncommitted? 10
B saw the old, committed value 10, not A's uncommitted 0.
Worked example: spot the problem
| Story | Problem |
|---|---|
| Two clerks each read a seat count of 5, each book 1 seat in code and each write 4. Real count should be 3. | Lost update |
| A report adds up two columns in two queries; between them a refund is committed, so the totals disagree. | Non-repeatable read |
| A script counts customers, then lists them; a new customer signs up between the two queries. | Phantom read |
| A page shows a balance that was changed by a transfer that was later cancelled. | Dirty read |
Data and people are made up.
Common mistakes
- Doing read, calculate in Python, write back for shared numbers such as stock and balances.
- Testing only with one user. These bugs appear only when two things overlap, often rarely and at the worst moment.
- Assuming the database always prevents them. What it prevents depends on its isolation level.
- Mixing up the four names. Dirty = uncommitted data; non-repeatable = same row changes; phantom = row set changes; lost update = an overwrite.
Key takeaways
- Concurrency means transactions overlap; overlapping on the same rows can give wrong results.
- Lost update: two read-modify-write cycles overwrite each other. Fix it with
SET qty = qty - 3in one statement. - Dirty read, non-repeatable read and phantom read describe what you can see of other transactions' work; write skew is the subtler case where two transactions each act on a view that the other is about to make false.
- Which of these can occur is set by the isolation level.
Practice
1. Why did the final stock end up 6 instead of 3 in the first example?
Show answer
Both shoppers read 10; B's write of 6 replaced A's write of 7, so A's purchase was lost.
2. How does SET qty = qty - 3 avoid the lost update?
Show answer
The database reads and changes the row in a single step, so the second statement starts from the value the first one left.
3. Define a dirty read.
Show answer
Reading data that another transaction has changed but not yet committed.
4. What is the difference between a non-repeatable read and a phantom read?
Show answer
In a non-repeatable read, a row you already read has a different value the second time. In a phantom read, the set of rows matching your query changes (rows appear or disappear).
5. Why are concurrency bugs hard to find by testing?
Show answer
They need two actions to overlap at exactly the wrong moment, so they may appear only rarely under real load.
6. Which of the four problems is shown by two people overwriting each other's edit to the same document?
Show answer
A lost update.