Locks and row versions
Wait, or read an older copy
Section titled “Wait, or read an older copy”Two transactions want the same row. One is writing it and has not committed. What should the other one do?
There are two answers, and databases use both, in different mixes.
- Wait. Put a lock on the row. The other transaction waits until the lock is released.
- Read an older copy. Keep the previous version of the row. The other transaction reads that, and carries on.
Mental model. Locks make transactions take turns. Row versions let a reader look at the past while the writer works on the present. Taking turns is simple and costs waiting. Looking at the past costs keeping the past around, and still has to settle two writers who want the same row.
A lock has a mode. A shared lock (written S in the lab) is taken to read. Any number of transactions can hold a shared lock on the same row. An exclusive lock (X) is taken to write, and nobody else can hold any lock on that row while it is held.
| One holds, another asks | Shared | Exclusive |
|---|---|---|
| Shared | Granted | Has to wait |
| Exclusive | Has to wait | Has to wait |
When a lock is released decides the isolation level. Under the locking definitions of Berenson et al. that the lab follows, write locks are held until the transaction ends at every level. Read locks are the difference: none at read uncommitted, released right after the read at read committed, held on the rows read until the end at repeatable read, and, at serializable, held also on searches until the end. Holding locks until the end is called two-phase locking: a transaction only acquires locks while it runs, and releases them all at its end.
Here is a non-repeatable read, run with locks at repeatable read.
Non-repeatable read
An account holds 100. T1 reads the balance, does some other work, and reads it again. T2 withdraws 50 and commits between the two reads.
What to watch Do T1's two reads return the same value?
Rows that were read stay locked until the end, so they cannot change under the transaction. A search is locked only while it runs, so new rows can still appear.
- T1
SELECT balance → aT1 reads balance and gets 100. - T2
UPDATE balance = balance − 50Has to waitT2 has to wait for T1, because of a lock on balance. - T2
COMMITQueuedT2 is still waiting for T1, so this statement waits behind it. - T1
SELECT balance → bT1 reads balance and gets 100. - T1
COMMITT1 commits. - T2
UPDATE balance = balance − 50ResumedT2 writes 50 to balance. It is not committed yet. - T2
COMMITResumedT2 commits.
State after this step
| Row | Committed | Not committed | Locks held |
|---|---|---|---|
balance | 50 | none | none |
| Transaction | Status | Values read so far |
|---|---|---|
| T1 Reads the balance twice | Committed | a = 100, b = 100 |
| T2 Withdraws 50 | Committed | none |
Outcome
No anomaly happened in this run.
- The result is the same as running T1, T2 one at a time, in that order.
- Waited for another transaction to finish: T2.
- Committed values at the end: balance = 50.
| Isolation level | Locks | MVCC (row versions) |
|---|---|---|
| Read uncommitted | Non-repeatable read | Non-repeatable read |
| Read committed | Non-repeatable read | Non-repeatable read |
| Repeatable read | No anomalyWaiting: T2 (shown above) | No anomaly |
| Serializable | No anomalyWaiting: T2 | No anomaly |
Model notes
Assumptions
- The levels have the names of the SQL standard, but real databases differ. In PostgreSQL, read uncommitted behaves as read committed, and repeatable read is snapshot isolation: no phantom reads, but write skew is possible. In MySQL’s InnoDB, read uncommitted can read uncommitted data, and locking reads lock index ranges to stop phantoms. This lab shows a textbook model, not any one product.
- Locks follows the locking definitions in Berenson et al., A Critique of ANSI SQL Isolation Levels (1995): write locks are held until the end at every level; read locks are absent at read uncommitted, released at once at read committed, held on rows until the end at repeatable read (a search is locked only while it runs), and held on rows and searches until the end at serializable.
- MVCC follows PostgreSQL’s documentation: a read never waits and sees a committed version of a row, from a snapshot taken at the first statement at repeatable read and serializable, and two writers of the same row wait for each other. At repeatable read and serializable, the writer that waited is aborted if the first one commits.
- Serializable with MVCC aborts a transaction at commit when committing it would make the dependencies between the committed transactions form a cycle. PostgreSQL’s serializable level uses a related method, and its documentation warns that it can raise errors that would not occur in a true serial execution.
- A deadlock is resolved by aborting the transaction whose request closed the cycle. Databases choose differently (PostgreSQL’s documentation says which one is aborted is difficult to predict), and the application has to retry the transaction that was aborted. With locks, two transactions that each hold a read lock on a row and then both want to write it deadlock, which is what happens at repeatable read and serializable in the lost-update and write-skew schedules.
Simplifications
- Each lab runs one fixed interleaving. A level that avoids an anomaly in this schedule can still allow it in another, and a transaction that has to wait changes the timing of the statements behind it.
- A statement is one atomic step. There are no timeouts, no indexes and no gap or next-key locks, a statement waits until every transaction it waits for has finished, and an aborted transaction is not retried. Durability, the log and crashes are not modelled.
- A search matches rows by the start of their name and, if one is given, an exact value. A lock on a search, and a conflict with it, looks at both the old and the new value of a row that is written.
Parameter values are illustrative. They are not benchmarks of any real product.
T1 reads the balance and keeps a shared lock on it. T2 wants to write the balance and has to wait for T1. T1 reads again and gets 100 both times, commits and releases its lock, and only then does T2 write 50. The anomaly is gone because T2 was made to wait.
Row versions
Section titled “Row versions”With MVCC, multiversion concurrency control, a write does not overwrite a row: it adds a new version, and the old one stays while someone might need it. Each statement or transaction reads from a consistent picture of the data. PostgreSQL’s documentation describes it as each statement seeing a snapshot of the data as it was some time ago, whatever the current state is, and says the consequence: locks taken to read do not conflict with locks taken to write, so reading does not block writing and writing does not block reading.
At read committed the picture is renewed at every statement. At repeatable read it is a snapshot taken at the start of the first statement and used by all the others. InnoDB documents the same two behaviours for its consistent reads: a snapshot set by the first read at repeatable read, and a fresh snapshot for each read at read committed.
Run the same schedule with row versions at repeatable read.
Non-repeatable read
An account holds 100. T1 reads the balance, does some other work, and reads it again. T2 withdraws 50 and commits between the two reads.
What to watch Do T1's two reads return the same value?
A snapshot is taken at the first statement and every read uses it. If a row you write was changed by a transaction that committed after your snapshot, you are aborted: the first updater wins.
- T1
SELECT balance → aT1 reads balance and gets 100. - T2
UPDATE balance = balance − 50T2 writes 50 to balance. It is not committed yet. - T2
COMMITT2 commits. - T1
SELECT balance → bT1 reads balance and gets 100. - T1
COMMITT1 commits.
State after this step
| Row | Committed | Not committed |
|---|---|---|
balance | 50 | none |
| Transaction | Status | Values read so far |
|---|---|---|
| T1 Reads the balance twice | Committed | a = 100, b = 100 |
| T2 Withdraws 50 | Committed | none |
Outcome
No anomaly happened in this run.
- The result is the same as running T1, T2 one at a time, in that order.
- Committed values at the end: balance = 50.
| Isolation level | Locks | MVCC (row versions) |
|---|---|---|
| Read uncommitted | Non-repeatable read | Non-repeatable read |
| Read committed | Non-repeatable read | Non-repeatable read |
| Repeatable read | No anomalyWaiting: T2 | No anomaly (shown above) |
| Serializable | No anomalyWaiting: T2 | No anomaly |
Model notes
Assumptions
- The levels have the names of the SQL standard, but real databases differ. In PostgreSQL, read uncommitted behaves as read committed, and repeatable read is snapshot isolation: no phantom reads, but write skew is possible. In MySQL’s InnoDB, read uncommitted can read uncommitted data, and locking reads lock index ranges to stop phantoms. This lab shows a textbook model, not any one product.
- Locks follows the locking definitions in Berenson et al., A Critique of ANSI SQL Isolation Levels (1995): write locks are held until the end at every level; read locks are absent at read uncommitted, released at once at read committed, held on rows until the end at repeatable read (a search is locked only while it runs), and held on rows and searches until the end at serializable.
- MVCC follows PostgreSQL’s documentation: a read never waits and sees a committed version of a row, from a snapshot taken at the first statement at repeatable read and serializable, and two writers of the same row wait for each other. At repeatable read and serializable, the writer that waited is aborted if the first one commits.
- Serializable with MVCC aborts a transaction at commit when committing it would make the dependencies between the committed transactions form a cycle. PostgreSQL’s serializable level uses a related method, and its documentation warns that it can raise errors that would not occur in a true serial execution.
- A deadlock is resolved by aborting the transaction whose request closed the cycle. Databases choose differently (PostgreSQL’s documentation says which one is aborted is difficult to predict), and the application has to retry the transaction that was aborted. With locks, two transactions that each hold a read lock on a row and then both want to write it deadlock, which is what happens at repeatable read and serializable in the lost-update and write-skew schedules.
Simplifications
- Each lab runs one fixed interleaving. A level that avoids an anomaly in this schedule can still allow it in another, and a transaction that has to wait changes the timing of the statements behind it.
- A statement is one atomic step. There are no timeouts, no indexes and no gap or next-key locks, a statement waits until every transaction it waits for has finished, and an aborted transaction is not retried. Durability, the log and crashes are not modelled.
- A search matches rows by the start of their name and, if one is given, an exact value. A lock on a search, and a conflict with it, looks at both the old and the new value of a row that is written.
Parameter values are illustrative. They are not benchmarks of any real product.
Nobody waits. T1 reads 100 twice, from its snapshot, while T2 writes 50 and commits in between. The balance ends at 50, and T1 never saw it change.
Two writers still queue
Section titled “Two writers still queue”Versions help readers. They do not remove the conflict between two writers of the same row, because only one of them can produce the next version. PostgreSQL’s documentation says that row-level locks block only writers and lockers of the same row, not queries.
The lost update shows what that means. With row versions at repeatable read, T2 waits for nobody until it tries to write: T1 has changed and committed the row after T2’s snapshot, and T2 is aborted. This is the “first updater wins” rule, and it is the case from the last lesson, ending at 130.
With locks the same schedule goes differently.
Lost update
An account holds 100. T1 and T2 each read the balance, add their deposit in the application, and write the result back.
What to watch Both deposits applied would make 150. Look at what the balance ends up as, and why.
Rows that were read stay locked until the end, so they cannot change under the transaction. A search is locked only while it runs, so new rows can still appear.
- T1
SELECT balance → aT1 reads balance and gets 100. - T2
SELECT balance → bT2 reads balance and gets 100. - T1
UPDATE balance = a + 30Has to waitT1 has to wait for T2, because of a lock on balance. - T1
COMMITQueuedT1 is still waiting for T2, so this statement waits behind it. - T2
UPDATE balance = b + 20AbortedDeadlock: T2 waits for T1, T1 waits for T2. The database aborts T2, whose request closed the cycle, and releases its locks. - T1
UPDATE balance = a + 30ResumedT1 writes 130 to balance. It is not committed yet. - T1
COMMITResumedT1 commits. - T2
COMMITNot runT2 was aborted, so this statement does not run.
State after this step
| Row | Committed | Not committed | Locks held |
|---|---|---|---|
balance | 130 | none | none |
| Transaction | Status | Values read so far |
|---|---|---|
| T1 Deposits 30 | Committed | a = 100 |
| T2 Deposits 20 | Aborted | b = 100 |
Outcome
No anomaly happened in this run.
- T2 was aborted by the database (deadlock). An application would retry it.
- Waited for another transaction to finish: T1.
- Committed values at the end: balance = 130.
| Isolation level | Locks | MVCC (row versions) |
|---|---|---|
| Read uncommitted | Lost update | Lost update |
| Read committed | Lost update | Lost update |
| Repeatable read | No anomalyT2 aborted: deadlockWaiting: T1 (shown above) | No anomalyT2 aborted: serialization failure, concurrent update |
| Serializable | No anomalyT2 aborted: deadlockWaiting: T1 | No anomalyT2 aborted: serialization failure, concurrent update |
Model notes
Assumptions
- The levels have the names of the SQL standard, but real databases differ. In PostgreSQL, read uncommitted behaves as read committed, and repeatable read is snapshot isolation: no phantom reads, but write skew is possible. In MySQL’s InnoDB, read uncommitted can read uncommitted data, and locking reads lock index ranges to stop phantoms. This lab shows a textbook model, not any one product.
- Locks follows the locking definitions in Berenson et al., A Critique of ANSI SQL Isolation Levels (1995): write locks are held until the end at every level; read locks are absent at read uncommitted, released at once at read committed, held on rows until the end at repeatable read (a search is locked only while it runs), and held on rows and searches until the end at serializable.
- MVCC follows PostgreSQL’s documentation: a read never waits and sees a committed version of a row, from a snapshot taken at the first statement at repeatable read and serializable, and two writers of the same row wait for each other. At repeatable read and serializable, the writer that waited is aborted if the first one commits.
- Serializable with MVCC aborts a transaction at commit when committing it would make the dependencies between the committed transactions form a cycle. PostgreSQL’s serializable level uses a related method, and its documentation warns that it can raise errors that would not occur in a true serial execution.
- A deadlock is resolved by aborting the transaction whose request closed the cycle. Databases choose differently (PostgreSQL’s documentation says which one is aborted is difficult to predict), and the application has to retry the transaction that was aborted. With locks, two transactions that each hold a read lock on a row and then both want to write it deadlock, which is what happens at repeatable read and serializable in the lost-update and write-skew schedules.
Simplifications
- Each lab runs one fixed interleaving. A level that avoids an anomaly in this schedule can still allow it in another, and a transaction that has to wait changes the timing of the statements behind it.
- A statement is one atomic step. There are no timeouts, no indexes and no gap or next-key locks, a statement waits until every transaction it waits for has finished, and an aborted transaction is not retried. Durability, the log and crashes are not modelled.
- A search matches rows by the start of their name and, if one is given, an exact value. A lock on a search, and a conflict with it, looks at both the old and the new value of a row that is written.
Parameter values are illustrative. They are not benchmarks of any real product.
Both transactions have read the balance and hold a shared lock on it. Each wants to write it, which needs an exclusive lock, and neither can have it while the other holds a shared one. Each waits for the other: a deadlock. The database aborts T2, and T1 writes 130 and commits. Locks stopped the lost update here, but they did it by creating a deadlock. The next lesson is about those.
What happens if a long report runs?
Section titled “What happens if a long report runs?”Imagine a transaction that reads many rows for a report, while others update those rows.
With locks at repeatable read, the report holds a shared lock on every row it has read, until it ends. A writer that wants one of those rows waits for the whole report, as T2 waited for T1 above. The longer the report, the longer the writers wait.
With row versions, writers carry on and the report reads its snapshot. The price is that old versions have to be kept as long as a transaction might still read them, which follows from the way a snapshot works. A long-running transaction therefore keeps old versions alive for as long as it runs. How a product cleans them up, and how much space they take, is outside what this lesson has checked.
- Locks make transactions take turns: shared to read, exclusive to write, and the second one waits.
- Under two-phase locking, locks are held until the end. How long read locks are held is what separates the levels.
- Row versions let a reader see a committed older copy, so readers and writers do not wait for each other.
- Two writers of the same row still conflict. With versions, the later writer waits and, at repeatable read or serializable, is aborted if the first commits.
- With locks at repeatable read, the lost update ends in a deadlock, and T2 is aborted. The balance ends at 130.
Next: deadlocks, what a cycle of waiting looks like and how to avoid it.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.