Sub topic 7
Concurrency anomalies: what goes wrong without isolation
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), tables, primary keys and constraints, and that you have seen BEGIN, COMMIT and ROLLBACK. It also assumes you know that many sessions can talk to one database at the same time.
Why anomalies exist
Isolation is the "I" in ACID. The ideal is that each transaction behaves as if it ran alone. Real databases run transactions in parallel, because running them one at a time would be far too slow. When their steps interleave, one transaction can see or overwrite the effects of another in ways that no serial order could produce. These unexpected results are called concurrency anomalies.
An anomaly is a result that could not happen if the transactions had run one after another. The SQL standard names three of them. Practice adds two more that matter just as much. This chapter covers all five:
- dirty read
- non-repeatable read
- phantom read
- lost update
- write skew
The next chapter shows which isolation level prevents which anomaly. Here the goal is to recognize each one, see how it happens, and know the symptom.
All examples use the accounts table from earlier chapters:
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric(12,2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, balance) VALUES (1, 100.00), (2, 50.00);Dirty read
A dirty read happens when a transaction reads data that another transaction has written but not yet committed. If the writer then rolls back, the reader has acted on a value that never officially existed.
-- Session A -- Session B
BEGIN;
UPDATE accounts SET balance = 0 WHERE id = 1;
BEGIN;
SELECT balance FROM accounts WHERE id = 1;
-- dirty read: returns 0.00
ROLLBACK;
-- the real balance is still 100.00Session B may have decided to reject a payment because the balance looked empty. That decision rests on a value that was undone.
Dirty reads are only possible at the weakest standard level, READ UNCOMMITTED. PostgreSQL does not allow them at all: asking for READ UNCOMMITTED gives you READ COMMITTED behavior.
Non-repeatable read
A non-repeatable read happens when a transaction reads the same row twice and gets different values, because another transaction committed a change in between.
-- Session A -- Session B
BEGIN; BEGIN;
SELECT balance FROM accounts WHERE id = 1;
-- returns 100.00
UPDATE accounts SET balance = 0 WHERE id = 1;
COMMIT;
SELECT balance FROM accounts WHERE id = 1;
-- READ COMMITTED: returns 0.00
-- REPEATABLE READ: still returns 100.00
COMMIT;Nothing uncommitted was read here. Both values were committed at the time they were seen. The problem is that Session A's transaction has no stable view of the data. A report that reads the same balance in two places, or a check followed by a decision, can contradict itself.
Phantom read
A phantom read is the same problem applied to a set of rows instead of one row. A transaction runs a query with a condition, and when it runs the query again, new rows match (or old rows no longer match) because another transaction inserted, deleted or updated rows and committed.
-- Session A -- Session B
BEGIN; BEGIN;
SELECT count(*) FROM accounts
WHERE balance > 10;
-- returns 2
INSERT INTO accounts VALUES (3, 500.00);
COMMIT;
SELECT count(*) FROM accounts
WHERE balance > 10;
-- may return 3: a "phantom" row appeared
COMMIT;A row-level lock cannot stop a phantom by itself, because the phantom row did not exist when Session A read the data. There was nothing to lock. This is why phantoms need either a snapshot of the data or locks on key ranges.
Lost update
A lost update happens when two transactions read the same value, each computes a new value from it, and each writes back. The second write silently replaces the first, so one change disappears.
-- Session A -- Session B
BEGIN; BEGIN;
SELECT balance FROM accounts WHERE id = 1;
-- 100.00
SELECT balance FROM accounts WHERE id = 1;
-- 100.00
-- application computes 100 - 30 = 70
UPDATE accounts SET balance = 70 WHERE id = 1;
COMMIT;
-- application computes 100 - 20 = 80
UPDATE accounts SET balance = 80 WHERE id = 1;
COMMIT;
-- final balance: 80.00. The 30 withdrawal is lost.The cause is the read-modify-write pattern in application code. Both transactions worked from a stale copy of the balance. The final state is valid for the CHECK constraint, but money has appeared from nowhere: 50 was withdrawn and the balance only fell by 20.
There are three standard fixes:
- Let the database do the arithmetic in one statement:
UPDATE accounts SET balance = balance - 30 WHERE id = 1;. The row is locked during the update, so the second statement sees the first one's result. - Lock the row when you read it with
SELECT ... FOR UPDATE, covered in the locking chapter. - Use an isolation level that detects the conflict and aborts one transaction, which you then retry.
Write skew
Write skew is the hardest anomaly to spot. Two transactions each read an overlapping set of rows, make a decision based on what they read, and then write to different rows. Neither write touches a row the other wrote, so there is no direct conflict. Yet together the writes break a rule that each transaction checked on its own.
The classic example is an on-call schedule where at least one doctor must always be on duty:
CREATE TABLE doctors (id integer PRIMARY KEY, on_call boolean NOT NULL);
INSERT INTO doctors VALUES (1, true), (2, true);
-- Session A (same steps in Session B, but with id = 2)
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM doctors WHERE on_call; -- 2, so it looks safe to leave
UPDATE doctors SET on_call = false WHERE id = 1;
COMMIT;Both sessions see a count of 2. Session A updates row 1 and Session B updates row 2. Because they changed different rows, a snapshot-based REPEATABLE READ in PostgreSQL lets both commit. Nobody is on call.
Write skew is not a lost update, because no row was overwritten. It is not a phantom in the strict sense either, although it is often described as a close relative. Constraints such as CHECK or UNIQUE cannot catch it when the rule spans several rows. Only SERIALIZABLE isolation, explicit locking of every row that was read, or a design change prevents it.
How the anomalies relate
The anomalies differ in what the victim transaction observes and in whether it writes.
| Anomaly | What goes wrong | Needs a write by the victim? |
|---|---|---|
| Dirty read | Reads another transaction's uncommitted data | No |
| Non-repeatable read | Same row read twice gives different committed values | No |
| Phantom read | Same query returns a different set of rows | No |
| Lost update | A read-modify-write overwrites a concurrent change | Yes |
| Write skew | Decisions based on overlapping reads break a multi-row rule | Yes |
Common errors in practice
- Assuming constraints protect you. A CHECK constraint validates one row. It cannot enforce "at least one doctor on call" across rows. A rule over several rows needs serializable isolation, locking, or a database-level structure that makes the rule single-row.
- Reading in the application, then writing. Code that fetches a value, changes it in memory and saves it back is the usual source of lost updates. Prefer a single
UPDATEexpression. - Trusting a check-then-act sequence. A
SELECTthat tests a condition followed by anINSERTorUPDATEthat depends on it can race with another session. This is the pattern behind both phantoms and write skew. - Believing the anomaly is rare. Interleavings are timing-dependent, so they may not appear in testing. They show up under load, and they leave no error message. The data is just wrong.
- Mixing up levels across databases. The same level name does not behave identically everywhere. PostgreSQL's REPEATABLE READ uses snapshots and prevents phantoms, while MySQL's InnoDB handles them differently. Check the documentation for your database.
Summary
Concurrency anomalies are results that only occur when transactions overlap. Dirty reads, non-repeatable reads and phantoms are about what a transaction sees. Lost updates and write skew are about what it writes based on what it saw. Isolation levels, locks and MVCC exist to prevent these, and the next chapters examine how.
Exercise
Two sessions each run SELECT balance FROM accounts WHERE id = 1 and both get 100. Session A then runs UPDATE accounts SET balance = 70 WHERE id = 1 and commits. Session B runs UPDATE accounts SET balance = 80 WHERE id = 1 and commits. Which anomaly is this, and how would you change the application code to avoid it without changing the isolation level?
Show answer
This is a lost update. Session A's change is overwritten by Session B, which computed its value from a stale read. To avoid it, replace the read-modify-write with one atomic statement such as UPDATE accounts SET balance = balance - 30 WHERE id = 1, or read with SELECT ... FOR UPDATE so that the second session waits for the first to finish.
Exercise
In the on-call example, why does REPEATABLE READ in PostgreSQL not prevent both doctors from leaving, even though each transaction has a stable snapshot?
Show answer
Each transaction updates a different row, so there is no write-write conflict on any single row, and the snapshot only guarantees that each one sees consistent data from its own start. The rule "at least one doctor on call" spans several rows, and each transaction checked it against a snapshot that did not include the other's change. SERIALIZABLE detects the dependency between the two transactions and aborts one with SQLSTATE 40001.
Exercise
Why can a plain row lock not prevent a phantom read?
Show answer
A phantom is a row that did not exist when the first query ran, so there was no row to lock. Preventing phantoms needs a snapshot that hides new rows, or locks that cover a range of keys or a predicate.