Sub topic 4
What Goes Wrong Without Control: Dirty Reads, Lost Updates and More
This chapter assumes you know what a transaction is, the ACID properties, and how to write a schedule as a list of operations such as R1(A) and W2(A). It also assumes basic SQL. Here you learn the four classic concurrency anomalies, how to spot each one in a schedule, and which ACID property each one breaks.
Why interleaving is risky
A serial schedule runs one transaction completely before the next begins. It is always correct, but it is slow because the system sits idle during disk waits. A concurrent schedule interleaves the operations of several transactions to keep the system busy.
Interleaving is safe only when the result matches some serial order. When it does not, the database shows an anomaly: a result that no serial execution could produce. GATE questions name four anomalies, and you must recognize each from a schedule.
Notation used in this chapter:
Ri(X)means transaction Ti reads item X.Wi(X)means Ti writes item X.Cimeans Ti commits.Aimeans Ti aborts and rolls back.
Dirty read (write-read conflict)
A dirty read happens when a transaction reads a value written by another transaction that has not yet committed. If the writer later aborts, the reader has used a value that never officially existed.
T1: R1(A) W1(A) A1
T2: R2(A) W2(B) C2Suppose A starts at 100. T1 changes A to 150 but has not committed. T2 reads 150 and uses it to compute B, then commits. T1 then aborts and restores A to 100. T2 has committed a result based on 150, a value that was rolled back.
The pattern to remember is Wi(X) ... Rj(X) with Ti not committed when Tj reads. It is also called a write-read (WR) conflict. A dirty read breaks isolation and, through the committed result, also threatens consistency and durability's meaning. The recoverability chapter later in this tutorial classifies which schedules survive such cases.
Lost update (write-write conflict)
A lost update happens when two transactions read the same value, both compute a new value from it, and the second write overwrites the first. The first update disappears.
T1: R1(A) W1(A)
T2: R2(A) W2(A)Take A = 1000. T1 reads 1000 and plans to subtract 100. T2 reads 1000 and plans to subtract 50. T1 writes 900. T2 then writes 950. The final value is 950, but the correct result of any serial order is 850. The 100 withdrawal is lost.
A related case is the blind write: W1(A) W2(A) where T2 never read A. If T1 later aborts and the system restores the old value, it can erase T2's write too. GATE often groups both under write-write (WW) conflicts.
The following SQL shows the same problem and its standard fix. Without FOR UPDATE, both sessions read the same balance. With it, the second session waits for the first to commit.
-- Session 1 -- Session 2
BEGIN; BEGIN;
SELECT balance FROM account SELECT balance FROM account
WHERE id = 1 FOR UPDATE; WHERE id = 1 FOR UPDATE; -- blocks here
UPDATE account SET balance = balance - 100
WHERE id = 1;
COMMIT; -- now proceeds and reads the committed balance
UPDATE account SET balance = balance - 50
WHERE id = 1;
COMMIT;FOR UPDATE takes an exclusive row lock held until commit. Session 2 therefore reads the committed 900 and writes 850. No update is lost.
Unrepeatable read (read-write conflict)
An unrepeatable read happens when a transaction reads the same item twice and gets different values because another transaction committed a change in between.
T1: R1(A) R1(A)
T2: W2(A) C2T1 first sees A = 100. T2 changes A to 200 and commits. T1 reads A again and sees 200. Inside one transaction the same query returned two answers.
The pattern is Ri(X) ... Wj(X) ... Ri(X), a read-write (RW) conflict followed by a second read. The difference from a dirty read is that the other transaction has committed. The data is real, but it changed under T1's feet.
Phantom read
A phantom read is the unrepeatable read applied to a set of rows instead of one row. T1 runs a query with a condition, and T2 inserts or deletes a row that matches the condition. When T1 repeats the query, rows have appeared or vanished.
-- T1
BEGIN;
SELECT COUNT(*) FROM employee WHERE dept = 'CS'; -- returns 10
-- T2 (separate session)
INSERT INTO employee(id, dept) VALUES (99, 'CS');
COMMIT;
-- T1 again
SELECT COUNT(*) FROM employee WHERE dept = 'CS'; -- returns 11
COMMIT;Locking only the ten existing rows does not stop this. The new row did not exist when T1 locked anything. Preventing phantoms requires locking the range or predicate, or running at the serializable level. That is why phantoms are treated separately from unrepeatable reads.
Comparing the four anomalies
| Anomaly | Conflict pattern | Other transaction committed? | Typical symptom |
|---|---|---|---|
| Dirty read | Write then read (WR) | No, not at the time of the read | Reads data that may be rolled back |
| Lost update | Read, read, write, write (RW then WW) | Both commit | One update overwritten |
| Unrepeatable read | Read, write, read (RW) | Yes, before the second read | Same row, two values |
| Phantom read | Predicate read, insert or delete, predicate read | Yes | Same query, different row set |
Some textbooks list only three or four anomalies and merge lost update into others. For GATE, learn all four by their schedule pattern.
Which ACID property each anomaly breaks
All four anomalies are failures of isolation: the transactions were meant to behave as if alone, and they did not. They also lead to other failures.
- Dirty read: isolation fails. If T2 commits a result based on aborted data, consistency is also violated, because the database now holds a state that no valid execution produces.
- Lost update: isolation fails, and the effect of a committed transaction vanishes. This looks like a durability violation to the user, although the cause is concurrency, not a crash.
- Unrepeatable read and phantom read: isolation fails, and the transaction's own view is inconsistent.
Spotting anomalies in a schedule
Work through a schedule step by step. Track each item's last writer and whether that writer has committed.
S: R1(A) W1(A) R2(A) W2(A) C2 R1(B) C1W1(A)thenR2(A)while T1 is uncommitted: a dirty read by T2.W1(A)thenW2(A)while T1 is uncommitted: an uncommitted overwrite, a WW conflict.- T1 did not abort here, so no rollback damage occurs yet. But the schedule is risky. If T1 aborted after
C2, T2 would have committed a result based on rolled-back data and could not be undone.
You can also scan a schedule with code. The function below flags dirty reads: a read of an item whose last writer has not committed or aborted yet.
def find_dirty_reads(schedule):
# schedule: list of (txn, op, item); op is 'R', 'W', 'C' or 'A'.
# For 'C' and 'A' the item is None.
last_writer = {} # item -> transaction that wrote it last
finished = set() # transactions that committed or aborted
found = []
for step, (t, op, x) in enumerate(schedule):
if op in ('C', 'A'):
finished.add(t)
elif op == 'W':
last_writer[x] = t
elif op == 'R':
w = last_writer.get(x)
if w is not None and w != t and w not in finished:
found.append((step, t, w, x))
return found
s = [('T1', 'R', 'A'), ('T1', 'W', 'A'), ('T2', 'R', 'A'),
('T2', 'W', 'A'), ('T2', 'C', None), ('T1', 'R', 'B'),
('T1', 'C', None)]
print(find_dirty_reads(s)) # [(2, 'T2', 'T1', 'A')]The output says: at step 2, T2 read A, which T1 wrote and had not finished.
Common errors
- Calling any read-write overlap a dirty read. A dirty read needs the writer to be uncommitted at the time of the read. If the writer has already committed, it is not dirty.
- Confusing unrepeatable read with phantom. Unrepeatable read involves the same row with a changed value. Phantom involves a changed set of rows from the same condition.
- Assuming a lost update needs an abort. It does not. Both transactions can commit, and one update is still gone.
- Assuming a schedule free of these four anomalies is correct. The anomalies are symptoms. The real test is serializability, covered in later chapters.
- Forgetting that the anomaly list alone does not give a complete classification of schedules. Some non-serializable schedules show none of the four named patterns.
Exercises
Exercise
Schedule: R1(A) R2(A) W1(A) W2(A) C1 C2, with A = 500. T1 subtracts 100 from the value it read. T2 subtracts 200 from the value it read. What is the final value of A, and which anomaly occurred?
Show answer
T1 writes 500 - 100 = 400. T2 then writes 500 - 200 = 300, because T2 read 500 before T1 wrote. The final value is 300. Any serial order gives 200. T1's update is lost, so this is a lost update.
Exercise
Schedule: W1(A) R2(A) C2 A1. Name the anomaly and explain why it is a problem even though T2 committed.
Show answer
T2 performed a dirty read of A, written by T1 before T1 finished. T1 then aborted, so its write is rolled back. T2 already committed a result based on a value that never became permanent, and the system cannot undo a committed transaction. This is a write-read conflict that makes the schedule unrecoverable.
Exercise
T1 runs SELECT SUM(balance) FROM account twice. Between the two queries, T2 inserts a new account row and commits. The second sum is larger. Is this an unrepeatable read or a phantom read? Why?
Show answer
It is a phantom read. No existing row changed. A new row matching the query condition appeared, so the set of rows changed. An unrepeatable read would require an existing row to have its value changed.