7.1 Problems When Reading and Writing Concurrently

If transactions ran strictly one at a time, isolation would hold automatically. A real server, however, handles hundreds of connections at once, and transactions overlap in time. Statements from another transaction can slip in between the statements of one transaction, and the order in which they interleave differs from run to run. A situation in which the result depends on execution order is called a race condition. Many bugs that never appear when you test alone in a development environment and show up intermittently in production under heavy traffic belong to this category.

The anomalies produced by overlapping transactions have had names for a long time. Using the transfer example, we look at four of them in turn. Each row of a table is a point in time, and we assume there is no isolation mechanism at all.

① Dirty Read: Reading an Uncommitted Value

TimeTransfer T1Balance query T2
1Changes Hong Gildong's balance from 500,000 to 400,000
2Reads Hong Gildong's balance: 400,000
3Finds that Kim Cheolsu's account is closed, ROLLBACK
4Calculates a loan limit based on 400,000

The 400,000 won that T2 read is a value that was never committed. Because T1 rolled back, Hong Gildong's balance was 500,000 all along. Reading an intermediate value that has not been finalized is called a Dirty Read. It is a problem even without a rollback. If a query that totals the balances of the whole bank runs after T1 has changed Hong Gildong's balance but before it has changed Kim Cheolsu's, the total sees a state that never actually existed, one that is "short by 100,000 won".

② Lost Update: One of Two Writes Disappears

This is the most common and most dangerous race condition. It occurs in the "read-modify-write" pattern, where an application reads a value, computes in memory, and writes the result back. Here two withdrawals arrive almost simultaneously against Hong Gildong's balance of 500,000 won.

TimeWithdrawal T1 (100,000 won)Withdrawal T3 (200,000 won)
1Reads balance: 500,000
2Reads balance: 500,000
3Writes 500,000 − 100,000 = 400,000 and COMMITs
4Writes 500,000 − 200,000 = 300,000 and COMMITs

The final balance is 300,000 won. 300,000 won was withdrawn, but the balance dropped by only 200,000 won. T1's withdrawal vanished without a trace. This is a Lost Update. The value T3 read had already become stale by the time of its write, yet T3, unaware of that, overwrote the row with a result computed from it. This would not have happened had the two transactions run one after the other; it happened because T3's read slipped in during the few milliseconds between times 1 and 3. Every feature that "reads the current value and computes a new one", such as stock deduction, point accrual, view counters, and seat reservation, carries the same risk.

sequenceDiagram
  participant T1 as T1 (withdraw 100K)
  participant R as Hong Gildong row
  participant T3 as T3 (withdraw 200K)
  T1->>R: Read
  R-->>T1: 500K
  T3->>R: Read
  R-->>T3: 500K
  T1->>R: Write 400K, COMMIT
  T3->>R: Write 300K, COMMIT
  Note over R: Final 300K. T1's write is lost

The diagram redraws the same table as messages between sessions. T1 and T3 both read the same value, 500K, and then each writes the value it computed. T3's write is a value that does not reflect T1's write, so only the last write, T3's, remains and T1's change is overwritten.

③ Non-repeatable Read: Reading the Same Row Twice Yields Different Values

TimeBalance verification T2Transfer T1
1Reads Hong Gildong's balance: 500,000
2Hong Gildong 500,000 → 400,000, Kim Cheolsu 200,000 → 300,000, COMMIT
3Reads Hong Gildong's balance again: 400,000
4Reports the error "the balance changed during verification"

T2 read the same row twice within one transaction and got different values, because T1 committed in between. It differs from a Dirty Read in that every value read is a committed value. Each one is correct on its own; the problem is that "the data a transaction sees changes midway". This is called a Non-repeatable Read. It is the cause of logic that checks the same data across several steps, such as a transfer verification, and of reports whose first table and later table do not agree.

④ Phantom Read: Running the Same Query Twice Returns a Different Number of Rows

TimeVIP aggregation T2Account opening T5
1Queries accounts with a balance of at least 1,000,000: 100 rows
2Opens a new account with a balance of 1,500,000, COMMIT
3Queries the sum of balances of accounts with at least 1,000,000: sum of 101 rows
4A report whose count is 100 but whose sum is based on 101 rows

None of the 100 rows T2 read changed. Yet when it queries again with the same condition, a row that was not there at first appears. Because a row that was absent at first newly appears in the result, this is called a Phantom Read. If a Non-repeatable Read is "the value of an already-read row changed", a phantom is "the set of rows matching the condition itself changed". The two are distinguished because they are prevented differently. A row that has already been read can be protected by locking that row, but a row that does not yet exist cannot be locked. So to prevent phantoms in a lock-based system, you must also lock the empty ranges between rows (this is what InnoDB's gap locks are), and in a snapshot-based system they are prevented by not seeing rows created after the snapshot.

How the Four Anomalies Relate

AnomalyType of conflictWhat goes wrong
Dirty ReadRead vs. in-progress writeReads a value that is not finalized
Lost UpdateWrite vs. writeOne write overwrites another without knowing about it
Non-repeatable ReadRead vs. committed writeThe value of the same row changes during the transaction
Phantom ReadRead vs. committed insert/deleteThe set of rows matching the condition changes midway

The four anomalies fall into two broad groups. Lost Update is a write-write conflict, and the other three are read-write conflicts. This distinction is used throughout the chapter. As we will see later, MVCC resolves read-write conflicts at almost no cost, while write-write conflicts are still resolved with locks. And the isolation levels in Section 7.8 are a setting for choosing how many of these anomalies to prevent.