Skip to content

Locks and row versions

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?

Isolation level
How the database keeps transactions apart

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.

All 7 steps
  1. T1SELECT balance → aT1 reads balance and gets 100.
  2. T2UPDATE balance = balance − 50Has to waitT2 has to wait for T1, because of a lock on balance.
  3. T2COMMITQueuedT2 is still waiting for T1, so this statement waits behind it.
  4. T1SELECT balance → bT1 reads balance and gets 100.
  5. T1COMMITT1 commits.
  6. T2UPDATE balance = balance − 50ResumedT2 writes 50 to balance. It is not committed yet.
  7. T2COMMITResumedT2 commits.

State after this step

Rows
RowCommittedNot committedLocks held
balance50nonenone
Transactions
TransactionStatusValues read so far
T1 Reads the balance twiceCommitteda = 100, b = 100
T2 Withdraws 50Committednone

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.
The same schedule at every level, with locks and with MVCC
Isolation levelLocksMVCC (row versions)
Read uncommittedNon-repeatable readNon-repeatable read
Read committedNon-repeatable readNon-repeatable read
Repeatable readNo anomalyWaiting: T2 (shown above)No anomaly
SerializableNo anomalyWaiting: T2No 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.

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?

Isolation level
How the database keeps transactions apart

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.

All 5 steps
  1. T1SELECT balance → aT1 reads balance and gets 100.
  2. T2UPDATE balance = balance − 50T2 writes 50 to balance. It is not committed yet.
  3. T2COMMITT2 commits.
  4. T1SELECT balance → bT1 reads balance and gets 100.
  5. T1COMMITT1 commits.

State after this step

Rows
RowCommittedNot committed
balance50none
Transactions
TransactionStatusValues read so far
T1 Reads the balance twiceCommitteda = 100, b = 100
T2 Withdraws 50Committednone

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.
The same schedule at every level, with locks and with MVCC
Isolation levelLocksMVCC (row versions)
Read uncommittedNon-repeatable readNon-repeatable read
Read committedNon-repeatable readNon-repeatable read
Repeatable readNo anomalyWaiting: T2No anomaly (shown above)
SerializableNo anomalyWaiting: T2No 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.

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.

Isolation level
How the database keeps transactions apart

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.

All 8 steps
  1. T1SELECT balance → aT1 reads balance and gets 100.
  2. T2SELECT balance → bT2 reads balance and gets 100.
  3. T1UPDATE balance = a + 30Has to waitT1 has to wait for T2, because of a lock on balance.
  4. T1COMMITQueuedT1 is still waiting for T2, so this statement waits behind it.
  5. T2UPDATE balance = b + 20AbortedDeadlock: T2 waits for T1, T1 waits for T2. The database aborts T2, whose request closed the cycle, and releases its locks.
  6. T1UPDATE balance = a + 30ResumedT1 writes 130 to balance. It is not committed yet.
  7. T1COMMITResumedT1 commits.
  8. T2COMMITNot runT2 was aborted, so this statement does not run.

State after this step

Rows
RowCommittedNot committedLocks held
balance130nonenone
Transactions
TransactionStatusValues read so far
T1 Deposits 30Committeda = 100
T2 Deposits 20Abortedb = 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.
The same schedule at every level, with locks and with MVCC
Isolation levelLocksMVCC (row versions)
Read uncommittedLost updateLost update
Read committedLost updateLost update
Repeatable readNo anomalyT2 aborted: deadlockWaiting: T1 (shown above)No anomalyT2 aborted: serialization failure, concurrent update
SerializableNo anomalyT2 aborted: deadlockWaiting: T1No 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.

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.