Sub topic 2
What goes wrong when transactions run concurrently
This chapter explains why two correct transactions can produce a wrong result when they overlap. It sets up the vocabulary that the later chapters on specific anomalies and isolation levels rely on.
Prerequisites
This chapter assumes you can:
- Write basic
SELECT,INSERT,UPDATEandDELETEstatements. - Use
BEGIN,COMMITandROLLBACK. - Read a table definition with a primary key.
- Accept that a database serves many clients at once.
You do not need to know how locks or MVCC (multiversion concurrency control) work yet. Later chapters cover them.
Each transaction is correct alone
Transactions are usually written and tested one at a time. Take a transfer of 50 from account 1 to account 2:
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE id = 1;
UPDATE accounts SET balance = balance + 50 WHERE id = 2;
COMMIT;Run on its own, this transaction moves money and keeps the total constant. Atomicity guarantees that both updates happen or neither does. Nothing in the code is wrong.
Production is different. Many sessions run at the same moment, and the database interleaves their statements. A bug can appear only when a particular interleaving occurs, which makes it rare, timing-dependent and hard to reproduce.
The reference point: serial execution
The database needs a definition of "correct" for concurrent work. The standard one is serializability. A concurrent execution is serializable if its result is the same as running the same transactions one after another in some order. The order is not specified, and any order is acceptable.
This gives a practical test for a suspected bug. Run the transactions serially in every possible order and list the outcomes. If the concurrent run produces an outcome that no serial order can produce, the interleaving caused an anomaly.
An anomaly (also called a phenomenon) is a result that could not occur if the transactions had run serially. The database is not malfunctioning when an anomaly occurs. It is running at an isolation level that permits that interleaving.
A worked schedule
A schedule is the exact order in which statements from several transactions execute. Consider this setup:
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100), (2, 100);The total is 200. Session A is a report that reads two balances with two separate statements. Session B is the transfer from above. Run the schedule below under PostgreSQL's default level, READ COMMITTED:
-- Session A (report) -- Session B (transfer)
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- 100
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE id = 1;
UPDATE accounts SET balance = balance + 50 WHERE id = 2;
COMMIT;
SELECT balance FROM accounts WHERE id = 2; -- 150
COMMIT;
-- The report adds 100 + 150 = 250. The real total was never 250.Session B committed correctly, and Session A only read committed data. The report is still wrong, because it combined a value from before the transfer with a value from after it.
Serial execution gives two outcomes. If A runs first, it sees 100 and 100, total 200. If B runs first, it sees 50 and 150, total 200. The total 250 appears in neither, so this interleaving is an anomaly. It is usually called read skew.
Three kinds of conflict
Interference happens only when two transactions touch the same data and at least one of them writes it. Two transactions that only read never interfere. Conflicts fall into three types, named by the order of the two operations.
| Conflict | First operation | Second operation | What can go wrong |
|---|---|---|---|
| Write-read | T1 writes a row | T2 reads that row | T2 sees data that T1 has not committed, or may later roll back |
| Read-write | T1 reads a row | T2 writes that row | T1 reads the same row again and sees a different value, or acts on a value that is no longer current |
| Write-write | T1 writes a row | T2 writes that row | One update overwrites the other, or the two interleave into a mixed state |
The anomalies you will study in the next chapters are specific cases of these three patterns. Each one differs in what the second transaction does with the data and whether the first transaction has committed.
The catalogue of anomalies
This table is a map for the rest of the tutorial. Each anomaly gets its own chapter, so the descriptions here are short.
| Anomaly | Conflict pattern | One-line description |
|---|---|---|
| Dirty read | Write-read | A transaction reads data another transaction has written but not committed |
| Non-repeatable read | Read-write | Reading the same row twice in one transaction returns different values |
| Phantom read | Read-write | Running the same query twice returns a different set of rows |
| Lost update | Write-write after read | Two read-modify-write cycles overwrite each other |
| Read skew | Read-write across rows | Two related rows are read at different moments, as in the schedule above |
| Write skew | Read-write across rows | Two transactions read overlapping data, then write different rows, and together break a rule |
The SQL standard names only the first three as phenomena (dirty read, non-repeatable read and phantom read), and defines its isolation levels in terms of them. Lost update, read skew and write skew are not in that list. Real engines can still exhibit them at levels the standard treats as safe, which is why the standard alone is not enough to reason about your database.
Why not just run everything serially?
Serial execution is always correct, so the obvious question is why databases do not use it. The reason is throughput. While one transaction waits for disk, a network round trip or an application server, the database could be serving others. Strict serial execution wastes that time and leaves CPU cores idle.
Databases therefore offer a range of choices. Stronger isolation prevents more anomalies but costs more, in one of three ways:
- Transactions wait for locks held by others, which lowers concurrency.
- The database keeps old row versions and tracks dependencies, which uses memory and CPU.
- Some transactions are aborted and must be retried by the application.
Weaker isolation avoids these costs but leaves the application responsible for any anomaly it can hit. An isolation level is a setting that picks a point on this trade-off. Choosing the point deliberately is the goal of this tutorial.
Finding the anomaly in your own code
Anomalies come from a recognizable shape in application code: the transaction reads something, makes a decision outside the database, and then writes. Look for these signs:
- A
SELECTfollowed by anUPDATEorINSERTwhose values or existence depend on what theSELECTreturned. - Several
SELECTstatements in one transaction that are expected to describe the same moment in time. - An application-level rule that spans more than one row, such as "the total stays constant" or "at least one doctor is on call".
- Code that checks whether a row exists and inserts it if not.
Any of these can break when another session changes the data between the read and the write. A single UPDATE accounts SET balance = balance + 10 WHERE id = 1 is safe from many of these problems, because the database reads and writes in one atomic statement.
Common mistakes
- Assuming
BEGINmeans "nobody else can interfere". A transaction groups statements for atomicity. It does not by itself stop other sessions from changing data you have read. What other sessions can change depends on the isolation level. - Testing with one connection. Anomalies need at least two sessions. A test suite that runs one transaction at a time cannot find them. Reproduce them with two terminal sessions, or with a test harness that pauses between statements.
- Trusting a clean run. An absence of failures under light load proves little. A rare interleaving may need heavy traffic to appear.
- Believing the standard names settle behavior. REPEATABLE READ in PostgreSQL, MySQL and SQL Server does not mean the same thing. Later chapters compare them.
- Blaming the database. An anomaly allowed at the chosen level is working as specified. The fix is to change the level, add locking, or restructure the statements.
Exercise
A table holds accounts (id 1, balance 100) and (id 2, balance 100). Transaction T1 reads account 1, then reads account 2. Between those two reads, transaction T2 runs UPDATE accounts SET balance = balance - 30 WHERE id = 1; and UPDATE accounts SET balance = balance + 30 WHERE id = 2; and then commits. At READ COMMITTED, what total does T1 compute, and is this an anomaly? Justify your answer with the serial orders.
Show answer
T1 reads 100 for account 1 (before T2) and 130 for account 2 (after T2), so it computes 230. The serial orders give 200 in both cases: T1 first sees 100 and 100, and T2 first sees 70 and 130. Since 230 matches neither serial order, it is an anomaly (read skew). T2 committed before T1 read account 2, so no dirty read is involved.
Exercise
Name the three costs a database can pay to provide stronger isolation, and explain why running all transactions strictly one at a time is not the default.
Show answer
Stronger isolation can cost lock waits (lower concurrency), extra bookkeeping such as old row versions and dependency tracking (memory and CPU), and aborted transactions that the application must retry. Strictly serial execution is always correct but wastes time whenever a transaction waits on disk, the network or the application, so overall throughput is far lower than when the database interleaves transactions.