03. Data & Storage / Lesson 10 of 11
Transactions & Isolation
Make several changes all-or-nothing, even when many users change data at once.
- 12 min
- Advanced
- 11 steps
- What T2 sees$800 (good)
- Anomalynone (good)
- Hot row speed—
- Request
- Response
- Write
- Failed request
Step 1 of 11: Moving $100 is two writes
Read every step as text
Step 1: Moving $100 is two writes
Alice has $500 and Bob has $300, so the bank holds $800. A transfer of $100 is two separate updates: take $100 from Alice, then add $100 to Bob.
After both, the balances are $400 and $400, and the total is still $800. The rule "money is never created or lost" must hold at all times. That rule is the point of a transaction.
A transaction groups several operations into one unit that behaves as a single step.
Step 2: Atomic: all of it, or none of it
Suppose the database crashes after the first update. Alice has $400, Bob still $300, and the total is $700: $100 has vanished.
Wrap the two updates in
BEGINandCOMMIT. The database writes the changes to a log first. If it crashes beforeCOMMIT, it rolls back on restart and both balances return to the old values.Transactions give ACID: Atomic, Consistent, Isolated, Durable. Atomic and durable come from the write-ahead log; this lesson is about the I.
Step 3: Many transactions run at the same time
A real database runs thousands of transactions at once. T1 is the transfer. T2 is a report that reads both balances to add them up.
If transactions ran one after the other, nothing could go wrong, but it would be slow. Isolation is the promise that overlapping transactions behave as if they had run one after the other. Weaker levels give up part of that promise for speed.
Isolation bugs are rare, silent and hard to reproduce, because they depend on exact timing.
Step 4: Dirty read: seeing a change that is not committed
T1 has taken $100 from Alice (now $400) but has not credited Bob or committed. T2 reads both rows and adds them:
400 + 300 = $700.Then T1 fails and rolls back. T2 reported a total that never existed: the bank never held $700. Reading uncommitted data is a dirty read.
Only the lowest level, read uncommitted, allows this. Almost every database defaults to something stronger.
Step 5: Non-repeatable read: a row changes mid-transaction
Now T1 commits properly. T2 reads Alice first: $500. Then T1 transfers $100 and commits. T2 reads Bob next and gets $400.
T2 adds
500 + 400 = $900, which is $100 too much. Each value was committed, but they come from two different moments. The same row read twice can also give two answers, a non-repeatable read.A read-committed database blocks dirty reads, yet T2 still sees the world change under its feet.
Step 6: Phantom: new rows appear in a repeated query
T2 runs
SELECT COUNT(*) WHERE balance < 400and gets 1 row (Bob, 300). Meanwhile T1 opens a new account with a balance of 100 and commits.T2 runs the same query again and gets 2 rows. No row it had read was changed; a new one slid into the range. Locking the rows already read cannot stop it, because the new row did not exist yet.
Phantoms break checks like "only 1 booking per room" or "at least 1 doctor on call", which look at a range of rows.
Step 7: Four levels: pay more, get more safety
SQL defines four isolation levels, each blocking more anomalies: read uncommitted, read committed, repeatable read and serializable. Serializable means the result is the same as running the transactions one at a time.
Defaults differ: PostgreSQL, Oracle and SQL Server use read committed; MySQL's InnoDB uses repeatable read. Real databases also differ from the textbook, so check the manual for yours.
Higher isolation means fewer surprises and more waiting or retries. Pick the lowest level your rules can live with.
Step 8: Locks: make the other transaction wait
With two-phase locking a transaction takes a lock on each row it touches and keeps it until it commits. T1 holds the lock on Alice's row, so T2 must wait for T1 to finish. No dirty read, no changing values.
The cost is waiting. If every transfer touches the same hot row and holds its lock for 20 ms, that row allows at most
1000 ÷ 20 = 50 tx/s. Two transactions that lock rows in opposite order can also wait for each other forever, a deadlock: the database detects it and aborts one.Keep transactions short and touch rows in the same order everywhere. Never wait for a user's click inside a transaction.
Step 9: MVCC: readers see a snapshot and never wait
Multi-version concurrency control keeps old versions of a row. A write adds a new version instead of changing the old one. Each transaction reads the versions that were committed when it started: its snapshot.
T2 starts before T1 commits, so it reads Alice's old version ($500) and Bob's old version ($300): a clean $800, with no waiting. Writers on the same row still queue, so a hot row still allows only 50 tx/s. Old versions are cleaned up later (
VACUUMin PostgreSQL).PostgreSQL, MySQL InnoDB and Oracle all use MVCC. Reads do not block writes, and writes do not block reads.
Step 10: Lost update: two writers overwrite each other
Snapshots do not stop everything. Alice's balance is $500. T1 reads it and plans to add $100; T2 reads it and plans to add $50. T1 writes $600, then T2 writes $550.
The final balance is $550, but it should be $650. T1's deposit is gone. Fixes: update in one statement (
SET bal = bal + 100), lock the row when reading (SELECT … FOR UPDATE), keep a version number and retry on conflict, or use serializable.Whenever you read, think, then write, ask what happens if someone else does the same at that moment.
Step 11: Transactions in one picture
A transaction makes several changes all-or-nothing. Isolation decides what overlapping transactions can see: dirty reads, changing values and phantoms appear as you go down the levels.
Databases give isolation with locks (wait) or MVCC (snapshots). Across several databases a plain transaction is not enough; that needs sagas or two-phase commit, covered in the Architecture chapter.