Transactions
Designing Data-Intensive Applications · Chapter 7 · Recall lab
In the harsh reality of data systems, many things can go wrong. The database software or hardware can fail in the middle of a write. The application can crash halfway through a series of operations. The network can cut the application off from the database, or one database node from another. Several clients can write at the same time and overwrite each other’s changes, or read data that is only half updated. For decades, the tool of choice for simplifying these problems has been the transaction: a way for an application to group several reads and writes into one logical unit, which either succeeds as a whole (commit) or fails as a whole (abort, rollback), and if it fails, can safely be retried.
Transactions are not a law of nature. They were created with a purpose: to simplify the programming model for applications, so that a large class of errors and concurrency problems becomes a simple abort that the application can retry. Not every application needs that, and sometimes there are advantages to weakening the guarantees or dropping them entirely, for performance or availability. So the question this chapter keeps asking is which safety properties you actually get, and what each one costs.
Four letters, of uneven weight
Almost all relational databases, and some nonrelational ones, support transactions, and most follow the style IBM System R introduced in 1975. The safety guarantees are often described by the acronym ACID, coined in 1983 by Theo Härder and Andreas Reuter. In practice, one database’s ACID does not equal another’s, and “ACID compliant” has become mostly a marketing term. Systems that do not meet it are sometimes called BASE (basically available, soft state, eventual consistency), which is even vaguer.
Atomicity
Not about concurrency, despite what the word means in multithreaded programming. It describes what happens when a client makes several writes and a fault occurs after some of them: the transaction is aborted and the database discards or undoes every write it made so far. Without it, an error part way through leaves you not knowing which changes took effect. Abortability would have been a better name.
Consistency
The most overloaded word in the book: replica consistency, consistent hashing, linearizability in CAP, and here an application-specific notion of the database being in a good state: certain invariants hold, such as credits and debits balancing. That is a property of the application, which relies on the database’s atomicity and isolation to keep it. The C does not really belong in ACID.
Isolation
Concurrently executing transactions cannot step on each other. Textbooks formalize it as serializability: each transaction can pretend it is the only one running, and the result is as if they ran one after another. In practice serializable isolation is rarely used, because of its performance cost; Oracle 11g’s “serializable” is in fact snapshot isolation.
Durability
Once committed, data is not forgotten, even after a crash: written to nonvolatile storage and a write-ahead log on one node, copied to some number of nodes in a replicated one. Perfect durability does not exist. Correlated faults take out every replica; SSDs develop bad blocks (30 to 80 percent within four years) and can lose data within weeks if left unpowered in the heat; fsync has bugs. Use disks, replication and backups together.
Several writes, one decision
Atomicity and isolation matter most when a transaction modifies several objects at once, and those objects need to stay in sync. The book’s example is an email application that keeps an unread counter next to the messages, a denormalization for speed. Inserting a message and incrementing the counter are two writes, and both or neither must happen.
Insert the email, bump the counter, and lose the connection between them
- INSERT INTO emails … · ok
- UPDATE mailboxes SET unread = unread + 1 · fails: the connection drops
- INSERT INTO emails … · ok
- UPDATE mailboxes SET unread = unread + 1 · fails: the connection drops
- ROLLBACK · the insert is undone
A relational database decides which writes belong together by the client’s TCP connection:
everything between BEGIN TRANSACTION and COMMIT is one transaction. Many nonrelational databases
have no such grouping; even a multi-put API that updates several keys in one call does not
necessarily mean transaction semantics. On a single object, storage engines almost universally
provide atomicity (a log for crash recovery) and isolation (a lock per object), and some offer an
atomic increment or compare-and-set. Those are useful, and calling them “lightweight transactions”
is misleading: a transaction usually means grouping several operations on several objects.
When you need multi-object transactions
Many distributed datastores dropped them, as hard to implement across partitions and in the way of high availability or performance. But plenty of things need them: a foreign key reference kept valid as rows change; denormalized documents in a document database updated together; and secondary indexes, which are different objects from the values they index and must be updated with them.
Retrying an aborted transaction is not perfect
The network may fail after the commit succeeded, so the retry does it twice, unless you deduplicate. If the error was overload, retrying makes it worse: limit retries and back off exponentially. Retrying is only worth it after transient errors (deadlock, an isolation violation, a network blip, a failover), not a constraint violation. Side effects outside the database, like an email sent, happen even if the transaction aborts. And if the client crashes while retrying, what it was writing is lost.
Six race conditions, eight defences, forty-eight runs
Concurrency issues only come into play when one transaction reads data another is concurrently modifying, or two transactions modify the same data. They are hard to find by testing, because they depend on unlucky timing, and they have caused substantial losses of money, audits and corrupted customer data. “Use an ACID database if you handle financial data” misses the point: even many popular relational databases use weak isolation by default.
The rest of the chapter walks through six race conditions and the isolation levels that prevent them. Instead of a table to memorise, here is the experiment. Each row is one of the book’s examples as two concurrent transactions with a rule that must hold. Each column runs it under one strategy, in a small transaction engine with versioned rows, locks, snapshots and deadlock detection. The columns are ordered roughly from weakest to strongest, and each run opens with how its column works, in words and as a small timeline. Click any cell for the trace that produced it.
Every cell is a run: click one to see what happened
| No isolation reads anything, locks nothing | Read committed the default in Oracle, PostgreSQL, SQL Server | Read committed + FOR UPDATE every read locks what it returns | Snapshot isolation MySQL InnoDB’s repeatable read | Snapshot + lost-update detection PostgreSQL repeatable read, Oracle “serializable” | Two-phase locking MySQL InnoDB and SQL Server serializable | Serializable snapshot isolation PostgreSQL serializable | Actual serial execution VoltDB, Redis, Datomic | |
|---|---|---|---|---|---|---|---|---|
| Dirty read figure 7-4 | ||||||||
| Dirty write figure 7-5 | ||||||||
| Read skew figure 7-6 | ||||||||
| Lost update figure 7-1 | ||||||||
| Write skew figure 7-8 | ||||||||
| Phantom meeting rooms |
anomaly the invariant broke waits prevented by a lock aborts prevented by an abort, safe to retry prevented by the snapshot alone
How the column works A read returns the newest version of a row, even one another transaction has not committed yet. A write overwrites whatever is there. Nothing ever waits or aborts, so every race gets through. This is the baseline the other seven are measured against.
In miniatureCan a read see a write that has not committed yet?
Yes. T2 reads 2 while T1 could still roll it back.
Dirty read under No isolationUser 1 sets x = 3; user 2 reads x before user 1 commits.
| # | User 1 | User 2 |
|---|---|---|
| 1 | writes x = 3 | |
| 2 | reads x → 3, not yet committed | |
| 3 | commits | |
| 4 | commits |
Anomaly User 2 saw x = 3 while user 1 had not committed it.
How the column works A read only sees committed data, so there are no dirty reads. A write takes a lock on its row and holds it until commit, so a second writer to the same row waits: no dirty writes. But each read sees whatever is committed at that moment, so two reads in one transaction can disagree, and two read-modify-write cycles can overwrite each other.
In miniatureCan a read see a write that has not committed yet?
No. T2 reads 1, the last committed value, without waiting.
Dirty read under Read committedUser 1 sets x = 3; user 2 reads x before user 1 commits.
| # | User 1 | User 2 |
|---|---|---|
| 1 | writes x = 3 | |
| 2 | reads x → 2 | |
| 3 | commits | |
| 4 | commits |
Correct User 2 saw x = 2, a committed value.
How the column works Read committed, with every read written as SELECT … FOR UPDATE: the read takes an exclusive lock on each row it returns and holds it until commit, so anyone else who touches those rows waits. The application does this by hand. It can only lock rows that exist, so a query that finds nothing locks nothing, and a phantom insert gets through.
In miniatureCan a read see a write that has not committed yet?
No. T2 waits for T1’s lock, then reads 2 once it is committed.
Dirty read under Read committed + FOR UPDATEUser 1 sets x = 3; user 2 reads x before user 1 commits.
| # | User 1 | User 2 |
|---|---|---|
| 1 | writes x = 3 | |
| 2 | waits: User 1 holds a write lock on x | |
| 3 | commits | |
| 4 | reads x → 3 (locked) | |
| 5 | commits |
Correct, because it waits User 2 saw x = 3, a committed value.
How the column works Each transaction reads from a snapshot of what was committed when it started, kept as multiple versions of each row (MVCC). Reads never wait for writes, and every read in a transaction sees the same moment. Writes still lock their row. But two transactions can read the same old value and both write back a result based on it, so lost updates and write skew get through.
In miniatureCan a read see a write that has not committed yet?
No. T2 reads 1, the last committed value, without waiting.
Dirty read under Snapshot isolationUser 1 sets x = 3; user 2 reads x before user 1 commits.
| # | User 1 | User 2 |
|---|---|---|
| 1 | writes x = 3 | |
| 2 | reads x → 2 | |
| 3 | commits | |
| 4 | commits |
Correct User 2 saw x = 2, a committed value.
How the column works Snapshot isolation plus “first updater wins”: if a transaction writes a row that someone else changed and committed after its snapshot was taken, it aborts and can retry. That catches lost updates. It does not catch write skew, where the two transactions read the same rows but write different ones.
In miniatureCan a read see a write that has not committed yet?
No. T2 reads 1, the last committed value, without waiting.
Dirty read under Snapshot + lost-update detectionUser 1 sets x = 3; user 2 reads x before user 1 commits.
| # | User 1 | User 2 |
|---|---|---|
| 1 | writes x = 3 | |
| 2 | reads x → 2 | |
| 3 | commits | |
| 4 | commits |
Correct User 2 saw x = 2, a committed value.
How the column works A read takes a shared lock and a write takes an exclusive lock, and every lock is held until commit. Writers wait for readers and readers wait for writers. A query also locks its search condition (a predicate lock), which covers rows that do not exist yet. When two transactions end up waiting for each other, the deadlock detector aborts one.
In miniatureCan a read see a write that has not committed yet?
No. T2 waits for T1’s lock, then reads 2 once it is committed.
Dirty read under Two-phase lockingUser 1 sets x = 3; user 2 reads x before user 1 commits.
| # | User 1 | User 2 |
|---|---|---|
| 1 | writes x = 3 | |
| 2 | waits: User 1 holds a write lock on x | |
| 3 | commits | |
| 4 | reads x → 3 (shared lock) | |
| 5 | commits |
Correct, because it waits User 2 saw x = 3, a committed value.
How the column works Snapshot isolation that also remembers what each transaction read. Nobody waits. When a transaction that wrote something tries to commit, the database checks whether another transaction has since committed a write to data it read. If so, a premise of its decision may be out of date, and it aborts. First updater wins still applies to the same row.
In miniatureCan a read see a write that has not committed yet?
No. T2 reads 1, the last committed value, without waiting.
Dirty read under Serializable snapshot isolationUser 1 sets x = 3; user 2 reads x before user 1 commits.
| # | User 1 | User 2 |
|---|---|---|
| 1 | writes x = 3 | |
| 2 | reads x → 2 | |
| 3 | commits | |
| 4 | commits |
Correct User 2 saw x = 2, a committed value.
How the column works One transaction at a time, start to finish, on a single thread. No locks, no snapshots, nothing to detect: the races cannot happen because nothing interleaves. The cost is that every transaction must be short, and throughput is limited to one CPU core per partition.
In miniatureCan a read see a write that has not committed yet?
Never. T1 finishes before T2 starts, so T2 reads 2.
Dirty read under Actual serial executionUser 1 sets x = 3; user 2 reads x before user 1 commits.
| # | User 1 | User 2 |
|---|---|---|
| 1 | writes x = 3 | |
| 2 | commits | |
| 3 | reads x → 3 | |
| 4 | commits |
Correct User 2 saw x = 3, a committed value.
How the column works A read returns the newest version of a row, even one another transaction has not committed yet. A write overwrites whatever is there. Nothing ever waits or aborts, so every race gets through. This is the baseline the other seven are measured against.
In miniatureTwo transactions write the same row. What happens?
T2 overwrites T1’s uncommitted write straight away. Nothing waits.
Dirty write under No isolationAlice and Bob buy the same car. Buying is two writes: the listing and the invoice.
| # | Alice | Bob |
|---|---|---|
| 1 | writes the listing’s buyer = ‘Alice’ | |
| 2 | writes the listing’s buyer = ‘Bob’ | |
| 3 | writes the invoice’s recipient = ‘Bob’ | |
| 4 | writes the invoice’s recipient = ‘Alice’ | |
| 5 | commits | |
| 6 | commits |
Anomaly The car went to Bob and the invoice to Alice.
How the column works A read only sees committed data, so there are no dirty reads. A write takes a lock on its row and holds it until commit, so a second writer to the same row waits: no dirty writes. But each read sees whatever is committed at that moment, so two reads in one transaction can disagree, and two read-modify-write cycles can overwrite each other.
In miniatureTwo transactions write the same row. What happens?
T2 waits for T1’s lock, then writes. x ends at 3.
Dirty write under Read committedAlice and Bob buy the same car. Buying is two writes: the listing and the invoice.
| # | Alice | Bob |
|---|---|---|
| 1 | writes the listing’s buyer = ‘Alice’ | |
| 2 | waits: Alice holds a write lock on the listing’s buyer | |
| 3 | writes the invoice’s recipient = ‘Alice’ | |
| 4 | commits | |
| 5 | writes the listing’s buyer = ‘Bob’ | |
| 6 | writes the invoice’s recipient = ‘Bob’ | |
| 7 | commits |
Correct, because it waits The car and the invoice both went to Bob.
How the column works Read committed, with every read written as SELECT … FOR UPDATE: the read takes an exclusive lock on each row it returns and holds it until commit, so anyone else who touches those rows waits. The application does this by hand. It can only lock rows that exist, so a query that finds nothing locks nothing, and a phantom insert gets through.
In miniatureTwo transactions write the same row. What happens?
T2 waits for T1’s lock, then writes. x ends at 3.
Dirty write under Read committed + FOR UPDATEAlice and Bob buy the same car. Buying is two writes: the listing and the invoice.
| # | Alice | Bob |
|---|---|---|
| 1 | writes the listing’s buyer = ‘Alice’ | |
| 2 | waits: Alice holds a write lock on the listing’s buyer | |
| 3 | writes the invoice’s recipient = ‘Alice’ | |
| 4 | commits | |
| 5 | writes the listing’s buyer = ‘Bob’ | |
| 6 | writes the invoice’s recipient = ‘Bob’ | |
| 7 | commits |
Correct, because it waits The car and the invoice both went to Bob.
How the column works Each transaction reads from a snapshot of what was committed when it started, kept as multiple versions of each row (MVCC). Reads never wait for writes, and every read in a transaction sees the same moment. Writes still lock their row. But two transactions can read the same old value and both write back a result based on it, so lost updates and write skew get through.
In miniatureTwo transactions write the same row. What happens?
T2 waits for T1’s lock, then writes. x ends at 3.
Dirty write under Snapshot isolationAlice and Bob buy the same car. Buying is two writes: the listing and the invoice.
| # | Alice | Bob |
|---|---|---|
| 1 | writes the listing’s buyer = ‘Alice’ | |
| 2 | waits: Alice holds a write lock on the listing’s buyer | |
| 3 | writes the invoice’s recipient = ‘Alice’ | |
| 4 | commits | |
| 5 | writes the listing’s buyer = ‘Bob’ | |
| 6 | writes the invoice’s recipient = ‘Bob’ | |
| 7 | commits |
Correct, because it waits The car and the invoice both went to Bob.
How the column works Snapshot isolation plus “first updater wins”: if a transaction writes a row that someone else changed and committed after its snapshot was taken, it aborts and can retry. That catches lost updates. It does not catch write skew, where the two transactions read the same rows but write different ones.
In miniatureTwo transactions write the same row. What happens?
T2 waits for T1, then aborts: the row changed after T2’s snapshot was taken. T2 can retry.
Dirty write under Snapshot + lost-update detectionAlice and Bob buy the same car. Buying is two writes: the listing and the invoice.
| # | Alice | Bob |
|---|---|---|
| 1 | writes the listing’s buyer = ‘Alice’ | |
| 2 | waits: Alice holds a write lock on the listing’s buyer | |
| 3 | writes the invoice’s recipient = ‘Alice’ | |
| 4 | commits | |
| 5 | aborts: Alice committed a concurrent update to the listing’s buyer |
Correct, because it aborts Bob The car and the invoice both went to Alice.
How the column works A read takes a shared lock and a write takes an exclusive lock, and every lock is held until commit. Writers wait for readers and readers wait for writers. A query also locks its search condition (a predicate lock), which covers rows that do not exist yet. When two transactions end up waiting for each other, the deadlock detector aborts one.
In miniatureTwo transactions write the same row. What happens?
T2 waits for T1’s lock, then writes. x ends at 3.
Dirty write under Two-phase lockingAlice and Bob buy the same car. Buying is two writes: the listing and the invoice.
| # | Alice | Bob |
|---|---|---|
| 1 | writes the listing’s buyer = ‘Alice’ | |
| 2 | waits: Alice holds a write lock on the listing’s buyer | |
| 3 | writes the invoice’s recipient = ‘Alice’ | |
| 4 | commits | |
| 5 | writes the listing’s buyer = ‘Bob’ | |
| 6 | writes the invoice’s recipient = ‘Bob’ | |
| 7 | commits |
Correct, because it waits The car and the invoice both went to Bob.
How the column works Snapshot isolation that also remembers what each transaction read. Nobody waits. When a transaction that wrote something tries to commit, the database checks whether another transaction has since committed a write to data it read. If so, a premise of its decision may be out of date, and it aborts. First updater wins still applies to the same row.
In miniatureTwo transactions write the same row. What happens?
T2 waits for T1, then aborts: the row changed after T2’s snapshot was taken. T2 can retry.
Dirty write under Serializable snapshot isolationAlice and Bob buy the same car. Buying is two writes: the listing and the invoice.
| # | Alice | Bob |
|---|---|---|
| 1 | writes the listing’s buyer = ‘Alice’ | |
| 2 | waits: Alice holds a write lock on the listing’s buyer | |
| 3 | writes the invoice’s recipient = ‘Alice’ | |
| 4 | commits | |
| 5 | aborts: Alice committed a concurrent update to the listing’s buyer |
Correct, because it aborts Bob The car and the invoice both went to Alice.
How the column works One transaction at a time, start to finish, on a single thread. No locks, no snapshots, nothing to detect: the races cannot happen because nothing interleaves. The cost is that every transaction must be short, and throughput is limited to one CPU core per partition.
In miniatureTwo transactions write the same row. What happens?
They never overlap: T1 writes and commits, then T2 does.
Dirty write under Actual serial executionAlice and Bob buy the same car. Buying is two writes: the listing and the invoice.
| # | Alice | Bob |
|---|---|---|
| 1 | writes the listing’s buyer = ‘Alice’ | |
| 2 | writes the invoice’s recipient = ‘Alice’ | |
| 3 | commits | |
| 4 | writes the listing’s buyer = ‘Bob’ | |
| 5 | writes the invoice’s recipient = ‘Bob’ | |
| 6 | commits |
Correct The car and the invoice both went to Bob.
How the column works A read returns the newest version of a row, even one another transaction has not committed yet. A write overwrites whatever is there. Nothing ever waits or aborts, so every race gets through. This is the baseline the other seven are measured against.
In miniatureIf someone commits while I am working, do my reads change?
Yes. T1 asks twice and gets 1, then 2.
Read skew under No isolationAlice looks at her two accounts while $100 moves from one to the other.
| # | Alice | Transfer |
|---|---|---|
| 1 | reads account 1 → 500 | |
| 2 | writes account 1 = 600 | |
| 3 | writes account 2 = 400 | |
| 4 | commits | |
| 5 | reads account 2 → 400 | |
| 6 | commits |
Anomaly Alice sees $500 + $400 = $900. $100 has vanished.
How the column works A read only sees committed data, so there are no dirty reads. A write takes a lock on its row and holds it until commit, so a second writer to the same row waits: no dirty writes. But each read sees whatever is committed at that moment, so two reads in one transaction can disagree, and two read-modify-write cycles can overwrite each other.
In miniatureIf someone commits while I am working, do my reads change?
Yes. T1 asks twice and gets 1, then 2.
Read skew under Read committedAlice looks at her two accounts while $100 moves from one to the other.
| # | Alice | Transfer |
|---|---|---|
| 1 | reads account 1 → 500 | |
| 2 | writes account 1 = 600 | |
| 3 | writes account 2 = 400 | |
| 4 | commits | |
| 5 | reads account 2 → 400 | |
| 6 | commits |
Anomaly Alice sees $500 + $400 = $900. $100 has vanished.
How the column works Read committed, with every read written as SELECT … FOR UPDATE: the read takes an exclusive lock on each row it returns and holds it until commit, so anyone else who touches those rows waits. The application does this by hand. It can only lock rows that exist, so a query that finds nothing locks nothing, and a phantom insert gets through.
In miniatureIf someone commits while I am working, do my reads change?
No. T2 has to wait for T1’s lock to write, so T1 reads 1 both times.
Read skew under Read committed + FOR UPDATEAlice looks at her two accounts while $100 moves from one to the other.
| # | Alice | Transfer |
|---|---|---|
| 1 | reads account 1 → 500 (locked) | |
| 2 | waits: Alice holds a write lock on account 1 | |
| 3 | reads account 2 → 500 (locked) | |
| 4 | commits | |
| 5 | writes account 1 = 600 | |
| 6 | writes account 2 = 400 | |
| 7 | commits |
Correct, because it waits Alice sees $500 + $500 = $1,000.
How the column works Each transaction reads from a snapshot of what was committed when it started, kept as multiple versions of each row (MVCC). Reads never wait for writes, and every read in a transaction sees the same moment. Writes still lock their row. But two transactions can read the same old value and both write back a result based on it, so lost updates and write skew get through.
In miniatureIf someone commits while I am working, do my reads change?
No. T1 reads from its snapshot: 1 both times, though T2 committed 2.
Read skew under Snapshot isolationAlice looks at her two accounts while $100 moves from one to the other.
| # | Alice | Transfer |
|---|---|---|
| 1 | reads account 1 → 500 | |
| 2 | writes account 1 = 600 | |
| 3 | writes account 2 = 400 | |
| 4 | commits | |
| 5 | reads account 2 → 500 | |
| 6 | commits |
Correct Alice sees $500 + $500 = $1,000.
How the column works Snapshot isolation plus “first updater wins”: if a transaction writes a row that someone else changed and committed after its snapshot was taken, it aborts and can retry. That catches lost updates. It does not catch write skew, where the two transactions read the same rows but write different ones.
In miniatureIf someone commits while I am working, do my reads change?
No. T1 reads from its snapshot: 1 both times, though T2 committed 2.
Read skew under Snapshot + lost-update detectionAlice looks at her two accounts while $100 moves from one to the other.
| # | Alice | Transfer |
|---|---|---|
| 1 | reads account 1 → 500 | |
| 2 | writes account 1 = 600 | |
| 3 | writes account 2 = 400 | |
| 4 | commits | |
| 5 | reads account 2 → 500 | |
| 6 | commits |
Correct Alice sees $500 + $500 = $1,000.
How the column works A read takes a shared lock and a write takes an exclusive lock, and every lock is held until commit. Writers wait for readers and readers wait for writers. A query also locks its search condition (a predicate lock), which covers rows that do not exist yet. When two transactions end up waiting for each other, the deadlock detector aborts one.
In miniatureIf someone commits while I am working, do my reads change?
No. T2 has to wait for T1’s lock to write, so T1 reads 1 both times.
Read skew under Two-phase lockingAlice looks at her two accounts while $100 moves from one to the other.
| # | Alice | Transfer |
|---|---|---|
| 1 | reads account 1 → 500 (shared lock) | |
| 2 | waits: Alice holds a shared lock on account 1 | |
| 3 | reads account 2 → 500 (shared lock) | |
| 4 | commits | |
| 5 | writes account 1 = 600 | |
| 6 | writes account 2 = 400 | |
| 7 | commits |
Correct, because it waits Alice sees $500 + $500 = $1,000.
How the column works Snapshot isolation that also remembers what each transaction read. Nobody waits. When a transaction that wrote something tries to commit, the database checks whether another transaction has since committed a write to data it read. If so, a premise of its decision may be out of date, and it aborts. First updater wins still applies to the same row.
In miniatureIf someone commits while I am working, do my reads change?
No. T1 reads from its snapshot: 1 both times, though T2 committed 2.
Read skew under Serializable snapshot isolationAlice looks at her two accounts while $100 moves from one to the other.
| # | Alice | Transfer |
|---|---|---|
| 1 | reads account 1 → 500 | |
| 2 | writes account 1 = 600 | |
| 3 | writes account 2 = 400 | |
| 4 | commits | |
| 5 | reads account 2 → 500 | |
| 6 | commits |
Correct Alice sees $500 + $500 = $1,000.
How the column works One transaction at a time, start to finish, on a single thread. No locks, no snapshots, nothing to detect: the races cannot happen because nothing interleaves. The cost is that every transaction must be short, and throughput is limited to one CPU core per partition.
In miniatureIf someone commits while I am working, do my reads change?
No. Nothing runs beside T1, so it reads 1 both times.
Read skew under Actual serial executionAlice looks at her two accounts while $100 moves from one to the other.
| # | Alice | Transfer |
|---|---|---|
| 1 | reads account 1 → 500 | |
| 2 | reads account 2 → 500 | |
| 3 | commits | |
| 4 | writes account 1 = 600 | |
| 5 | writes account 2 = 400 | |
| 6 | commits |
Correct Alice sees $500 + $500 = $1,000.
How the column works A read returns the newest version of a row, even one another transaction has not committed yet. A write overwrites whatever is there. Nothing ever waits or aborts, so every race gets through. This is the baseline the other seven are measured against.
In miniatureBoth read x, add one and write it back. Does x go up by two?
No. Both read 1 and both write 2: one increment is lost.
Lost update under No isolationTwo users increment a counter by reading it, adding one, and writing it back.
| # | User 1 | User 2 |
|---|---|---|
| 1 | reads counter → 42 | |
| 2 | reads counter → 42 | |
| 3 | writes counter = 43 | |
| 4 | commits | |
| 5 | writes counter = 43 | |
| 6 | commits |
Anomaly Counter 43: 2 increments committed, only 1 counted.
How the column works A read only sees committed data, so there are no dirty reads. A write takes a lock on its row and holds it until commit, so a second writer to the same row waits: no dirty writes. But each read sees whatever is committed at that moment, so two reads in one transaction can disagree, and two read-modify-write cycles can overwrite each other.
In miniatureBoth read x, add one and write it back. Does x go up by two?
No. Both read 1 and both write 2: one increment is lost.
Lost update under Read committedTwo users increment a counter by reading it, adding one, and writing it back.
| # | User 1 | User 2 |
|---|---|---|
| 1 | reads counter → 42 | |
| 2 | reads counter → 42 | |
| 3 | writes counter = 43 | |
| 4 | commits | |
| 5 | writes counter = 43 | |
| 6 | commits |
Anomaly Counter 43: 2 increments committed, only 1 counted.
How the column works Read committed, with every read written as SELECT … FOR UPDATE: the read takes an exclusive lock on each row it returns and holds it until commit, so anyone else who touches those rows waits. The application does this by hand. It can only lock rows that exist, so a query that finds nothing locks nothing, and a phantom insert gets through.
In miniatureBoth read x, add one and write it back. Does x go up by two?
Yes. T1’s read locked x, so T2 waits, then reads 2 and writes 3.
Lost update under Read committed + FOR UPDATETwo users increment a counter by reading it, adding one, and writing it back.
| # | User 1 | User 2 |
|---|---|---|
| 1 | reads counter → 42 (locked) | |
| 2 | waits: User 1 holds a write lock on counter | |
| 3 | writes counter = 43 | |
| 4 | commits | |
| 5 | reads counter → 43 (locked) | |
| 6 | writes counter = 44 | |
| 7 | commits |
Correct, because it waits Counter 44: 2 increments committed, 2 counted.
How the column works Each transaction reads from a snapshot of what was committed when it started, kept as multiple versions of each row (MVCC). Reads never wait for writes, and every read in a transaction sees the same moment. Writes still lock their row. But two transactions can read the same old value and both write back a result based on it, so lost updates and write skew get through.
In miniatureBoth read x, add one and write it back. Does x go up by two?
No. Both read 1 and both write 2: one increment is lost.
Lost update under Snapshot isolationTwo users increment a counter by reading it, adding one, and writing it back.
| # | User 1 | User 2 |
|---|---|---|
| 1 | reads counter → 42 | |
| 2 | reads counter → 42 | |
| 3 | writes counter = 43 | |
| 4 | commits | |
| 5 | writes counter = 43 | |
| 6 | commits |
Anomaly Counter 43: 2 increments committed, only 1 counted.
How the column works Snapshot isolation plus “first updater wins”: if a transaction writes a row that someone else changed and committed after its snapshot was taken, it aborts and can retry. That catches lost updates. It does not catch write skew, where the two transactions read the same rows but write different ones.
In miniatureBoth read x, add one and write it back. Does x go up by two?
No: T2 aborts, because T1 changed x after T2’s snapshot was taken. T2 can retry.
Lost update under Snapshot + lost-update detectionTwo users increment a counter by reading it, adding one, and writing it back.
| # | User 1 | User 2 |
|---|---|---|
| 1 | reads counter → 42 | |
| 2 | reads counter → 42 | |
| 3 | writes counter = 43 | |
| 4 | commits | |
| 5 | aborts: User 1 committed a concurrent update to counter |
Correct, because it aborts User 2 Counter 43: 1 increment committed, 1 counted. The aborted one is safe to retry.
How the column works A read takes a shared lock and a write takes an exclusive lock, and every lock is held until commit. Writers wait for readers and readers wait for writers. A query also locks its search condition (a predicate lock), which covers rows that do not exist yet. When two transactions end up waiting for each other, the deadlock detector aborts one.
In miniatureBoth read x, add one and write it back. Does x go up by two?
Each holds a shared lock the other needs for its write. Neither can move, so the database aborts T2. T2 can retry.
Lost update under Two-phase lockingTwo users increment a counter by reading it, adding one, and writing it back.
| # | User 1 | User 2 |
|---|---|---|
| 1 | reads counter → 42 (shared lock) | |
| 2 | reads counter → 42 (shared lock) | |
| 3 | waits: User 2 holds a shared lock on counter | |
| 4 | waits: User 1 holds a shared lock on counter | |
| 5 | aborts: deadlock, both transactions are waiting for each other | |
| 6 | writes counter = 43 | |
| 7 | commits |
Correct, because it aborts User 2 Counter 43: 1 increment committed, 1 counted. The aborted one is safe to retry.
How the column works Snapshot isolation that also remembers what each transaction read. Nobody waits. When a transaction that wrote something tries to commit, the database checks whether another transaction has since committed a write to data it read. If so, a premise of its decision may be out of date, and it aborts. First updater wins still applies to the same row.
In miniatureBoth read x, add one and write it back. Does x go up by two?
No: T2 aborts, because T1 changed x after T2’s snapshot was taken. T2 can retry.
Lost update under Serializable snapshot isolationTwo users increment a counter by reading it, adding one, and writing it back.
| # | User 1 | User 2 |
|---|---|---|
| 1 | reads counter → 42 | |
| 2 | reads counter → 42 | |
| 3 | writes counter = 43 | |
| 4 | commits | |
| 5 | aborts: User 1 committed a concurrent update to counter |
Correct, because it aborts User 2 Counter 43: 1 increment committed, 1 counted. The aborted one is safe to retry.
How the column works One transaction at a time, start to finish, on a single thread. No locks, no snapshots, nothing to detect: the races cannot happen because nothing interleaves. The cost is that every transaction must be short, and throughput is limited to one CPU core per partition.
In miniatureBoth read x, add one and write it back. Does x go up by two?
Yes. T2 starts after T1 commits, reads 2 and writes 3.
Lost update under Actual serial executionTwo users increment a counter by reading it, adding one, and writing it back.
| # | User 1 | User 2 |
|---|---|---|
| 1 | reads counter → 42 | |
| 2 | writes counter = 43 | |
| 3 | commits | |
| 4 | reads counter → 43 | |
| 5 | writes counter = 44 | |
| 6 | commits |
Correct Counter 44: 2 increments committed, 2 counted.
How the column works A read returns the newest version of a row, even one another transaction has not committed yet. A write overwrites whatever is there. Nothing ever waits or aborts, so every race gets through. This is the baseline the other seven are measured against.
In miniatureRule: x + y must stay at least 1. Both see 2, then each sets a different row to 0.
Both commit. They wrote different rows, so nothing clashed, yet x + y is now 0.
Write skew under No isolationAlice and Bob are both on call, both feel unwell, and both ask to go off call at once. At least one doctor must stay on call.
| # | Alice | Bob |
|---|---|---|
| 1 | count doctors on call → 2 (alice, bob) | |
| 2 | count doctors on call → 2 (alice, bob) | |
| 3 | writes alice = false | |
| 4 | writes bob = false | |
| 5 | commits | |
| 6 | commits |
Anomaly Nobody is on call. Each request checked the rule, and the rule is broken.
How the column works A read only sees committed data, so there are no dirty reads. A write takes a lock on its row and holds it until commit, so a second writer to the same row waits: no dirty writes. But each read sees whatever is committed at that moment, so two reads in one transaction can disagree, and two read-modify-write cycles can overwrite each other.
In miniatureRule: x + y must stay at least 1. Both see 2, then each sets a different row to 0.
Both commit. They wrote different rows, so nothing clashed, yet x + y is now 0.
Write skew under Read committedAlice and Bob are both on call, both feel unwell, and both ask to go off call at once. At least one doctor must stay on call.
| # | Alice | Bob |
|---|---|---|
| 1 | count doctors on call → 2 (alice, bob) | |
| 2 | count doctors on call → 2 (alice, bob) | |
| 3 | writes alice = false | |
| 4 | writes bob = false | |
| 5 | commits | |
| 6 | commits |
Anomaly Nobody is on call. Each request checked the rule, and the rule is broken.
How the column works Read committed, with every read written as SELECT … FOR UPDATE: the read takes an exclusive lock on each row it returns and holds it until commit, so anyone else who touches those rows waits. The application does this by hand. It can only lock rows that exist, so a query that finds nothing locks nothing, and a phantom insert gets through.
In miniatureRule: x + y must stay at least 1. Both see 2, then each sets a different row to 0.
T1’s reads locked both rows, so T2 waits, then sees x = 0 and refuses.
Write skew under Read committed + FOR UPDATEAlice and Bob are both on call, both feel unwell, and both ask to go off call at once. At least one doctor must stay on call.
| # | Alice | Bob |
|---|---|---|
| 1 | count doctors on call → 2 (alice, bob), locked | |
| 2 | waits: Alice holds a write lock on a row the query returns | |
| 3 | writes alice = false | |
| 4 | commits | |
| 5 | count doctors on call → 1 (bob), locked | |
| 6 | sees only one doctor on call: request refused |
Correct, because it waits 1 doctor still on call.
How the column works Each transaction reads from a snapshot of what was committed when it started, kept as multiple versions of each row (MVCC). Reads never wait for writes, and every read in a transaction sees the same moment. Writes still lock their row. But two transactions can read the same old value and both write back a result based on it, so lost updates and write skew get through.
In miniatureRule: x + y must stay at least 1. Both see 2, then each sets a different row to 0.
Both commit. They wrote different rows, so nothing clashed, yet x + y is now 0.
Write skew under Snapshot isolationAlice and Bob are both on call, both feel unwell, and both ask to go off call at once. At least one doctor must stay on call.
| # | Alice | Bob |
|---|---|---|
| 1 | count doctors on call → 2 (alice, bob) | |
| 2 | count doctors on call → 2 (alice, bob) | |
| 3 | writes alice = false | |
| 4 | writes bob = false | |
| 5 | commits | |
| 6 | commits |
Anomaly Nobody is on call. Each request checked the rule, and the rule is broken.
How the column works Snapshot isolation plus “first updater wins”: if a transaction writes a row that someone else changed and committed after its snapshot was taken, it aborts and can retry. That catches lost updates. It does not catch write skew, where the two transactions read the same rows but write different ones.
In miniatureRule: x + y must stay at least 1. Both see 2, then each sets a different row to 0.
Both commit. They wrote different rows, so nothing clashed, yet x + y is now 0.
Write skew under Snapshot + lost-update detectionAlice and Bob are both on call, both feel unwell, and both ask to go off call at once. At least one doctor must stay on call.
| # | Alice | Bob |
|---|---|---|
| 1 | count doctors on call → 2 (alice, bob) | |
| 2 | count doctors on call → 2 (alice, bob) | |
| 3 | writes alice = false | |
| 4 | writes bob = false | |
| 5 | commits | |
| 6 | commits |
Anomaly Nobody is on call. Each request checked the rule, and the rule is broken.
How the column works A read takes a shared lock and a write takes an exclusive lock, and every lock is held until commit. Writers wait for readers and readers wait for writers. A query also locks its search condition (a predicate lock), which covers rows that do not exist yet. When two transactions end up waiting for each other, the deadlock detector aborts one.
In miniatureRule: x + y must stay at least 1. Both see 2, then each sets a different row to 0.
Each holds a shared lock on the row the other writes. Neither can move, so the database aborts T2.
Write skew under Two-phase lockingAlice and Bob are both on call, both feel unwell, and both ask to go off call at once. At least one doctor must stay on call.
| # | Alice | Bob |
|---|---|---|
| 1 | count doctors on call → 2 (alice, bob), predicate lock taken | |
| 2 | count doctors on call → 2 (alice, bob), predicate lock taken | |
| 3 | waits: Bob holds a shared lock on alice | |
| 4 | waits: Alice holds a shared lock on bob | |
| 5 | aborts: deadlock, both transactions are waiting for each other | |
| 6 | writes alice = false | |
| 7 | commits |
Correct, because it aborts Bob 1 doctor still on call.
How the column works Snapshot isolation that also remembers what each transaction read. Nobody waits. When a transaction that wrote something tries to commit, the database checks whether another transaction has since committed a write to data it read. If so, a premise of its decision may be out of date, and it aborts. First updater wins still applies to the same row.
In miniatureRule: x + y must stay at least 1. Both see 2, then each sets a different row to 0.
T2 aborts at commit: T1 changed a row T2 had read. T2 can retry.
Write skew under Serializable snapshot isolationAlice and Bob are both on call, both feel unwell, and both ask to go off call at once. At least one doctor must stay on call.
| # | Alice | Bob |
|---|---|---|
| 1 | count doctors on call → 2 (alice, bob) | |
| 2 | count doctors on call → 2 (alice, bob) | |
| 3 | writes alice = false | |
| 4 | writes bob = false | |
| 5 | commits | |
| 6 | aborts at commit: Alice committed a write to data it read |
Correct, because it aborts Bob 1 doctor still on call.
How the column works One transaction at a time, start to finish, on a single thread. No locks, no snapshots, nothing to detect: the races cannot happen because nothing interleaves. The cost is that every transaction must be short, and throughput is limited to one CPU core per partition.
In miniatureRule: x + y must stay at least 1. Both see 2, then each sets a different row to 0.
They never overlap: T2 starts after T1 commits, sees x = 0 and refuses.
Write skew under Actual serial executionAlice and Bob are both on call, both feel unwell, and both ask to go off call at once. At least one doctor must stay on call.
| # | Alice | Bob |
|---|---|---|
| 1 | count doctors on call → 2 (alice, bob) | |
| 2 | writes alice = false | |
| 3 | commits | |
| 4 | count doctors on call → 1 (bob) | |
| 5 | sees only one doctor on call: request refused |
Correct 1 doctor still on call.
How the column works A read returns the newest version of a row, even one another transaction has not committed yet. A write overwrites whatever is there. Nothing ever waits or aborts, so every race gets through. This is the baseline the other seven are measured against.
In miniatureBoth count rows in the slot, see 0, and insert one. Two rows?
Yes. The rows did not exist yet, so there was nothing to lock or to clash on.
Phantom under No isolationTwo users book room 123 for noon. Each checks that no booking overlaps, then inserts one.
| # | User 1 | User 2 |
|---|---|---|
| 1 | count bookings for room 123 at noon → 0 | |
| 2 | count bookings for room 123 at noon → 0 | |
| 3 | writes booking 41 = ‘room 123, 12:00–13:00’ | |
| 4 | writes booking 42 = ‘room 123, 12:00–13:00’ | |
| 5 | commits | |
| 6 | commits |
Anomaly 2 bookings for room 123 at noon: the room is double-booked.
How the column works A read only sees committed data, so there are no dirty reads. A write takes a lock on its row and holds it until commit, so a second writer to the same row waits: no dirty writes. But each read sees whatever is committed at that moment, so two reads in one transaction can disagree, and two read-modify-write cycles can overwrite each other.
In miniatureBoth count rows in the slot, see 0, and insert one. Two rows?
Yes. The rows did not exist yet, so there was nothing to lock or to clash on.
Phantom under Read committedTwo users book room 123 for noon. Each checks that no booking overlaps, then inserts one.
| # | User 1 | User 2 |
|---|---|---|
| 1 | count bookings for room 123 at noon → 0 | |
| 2 | count bookings for room 123 at noon → 0 | |
| 3 | writes booking 41 = ‘room 123, 12:00–13:00’ | |
| 4 | writes booking 42 = ‘room 123, 12:00–13:00’ | |
| 5 | commits | |
| 6 | commits |
Anomaly 2 bookings for room 123 at noon: the room is double-booked.
How the column works Read committed, with every read written as SELECT … FOR UPDATE: the read takes an exclusive lock on each row it returns and holds it until commit, so anyone else who touches those rows waits. The application does this by hand. It can only lock rows that exist, so a query that finds nothing locks nothing, and a phantom insert gets through.
In miniatureBoth count rows in the slot, see 0, and insert one. Two rows?
Yes. The rows did not exist yet, so there was nothing to lock or to clash on.
Phantom under Read committed + FOR UPDATETwo users book room 123 for noon. Each checks that no booking overlaps, then inserts one.
| # | User 1 | User 2 |
|---|---|---|
| 1 | count bookings for room 123 at noon → 0, nothing to lock | |
| 2 | count bookings for room 123 at noon → 0, nothing to lock | |
| 3 | writes booking 41 = ‘room 123, 12:00–13:00’ | |
| 4 | writes booking 42 = ‘room 123, 12:00–13:00’ | |
| 5 | commits | |
| 6 | commits |
Anomaly 2 bookings for room 123 at noon: the room is double-booked.
How the column works Each transaction reads from a snapshot of what was committed when it started, kept as multiple versions of each row (MVCC). Reads never wait for writes, and every read in a transaction sees the same moment. Writes still lock their row. But two transactions can read the same old value and both write back a result based on it, so lost updates and write skew get through.
In miniatureBoth count rows in the slot, see 0, and insert one. Two rows?
Yes. The rows did not exist yet, so there was nothing to lock or to clash on.
Phantom under Snapshot isolationTwo users book room 123 for noon. Each checks that no booking overlaps, then inserts one.
| # | User 1 | User 2 |
|---|---|---|
| 1 | count bookings for room 123 at noon → 0 | |
| 2 | count bookings for room 123 at noon → 0 | |
| 3 | writes booking 41 = ‘room 123, 12:00–13:00’ | |
| 4 | writes booking 42 = ‘room 123, 12:00–13:00’ | |
| 5 | commits | |
| 6 | commits |
Anomaly 2 bookings for room 123 at noon: the room is double-booked.
How the column works Snapshot isolation plus “first updater wins”: if a transaction writes a row that someone else changed and committed after its snapshot was taken, it aborts and can retry. That catches lost updates. It does not catch write skew, where the two transactions read the same rows but write different ones.
In miniatureBoth count rows in the slot, see 0, and insert one. Two rows?
Yes. The rows did not exist yet, so there was nothing to lock or to clash on.
Phantom under Snapshot + lost-update detectionTwo users book room 123 for noon. Each checks that no booking overlaps, then inserts one.
| # | User 1 | User 2 |
|---|---|---|
| 1 | count bookings for room 123 at noon → 0 | |
| 2 | count bookings for room 123 at noon → 0 | |
| 3 | writes booking 41 = ‘room 123, 12:00–13:00’ | |
| 4 | writes booking 42 = ‘room 123, 12:00–13:00’ | |
| 5 | commits | |
| 6 | commits |
Anomaly 2 bookings for room 123 at noon: the room is double-booked.
How the column works A read takes a shared lock and a write takes an exclusive lock, and every lock is held until commit. Writers wait for readers and readers wait for writers. A query also locks its search condition (a predicate lock), which covers rows that do not exist yet. When two transactions end up waiting for each other, the deadlock detector aborts one.
In miniatureBoth count rows in the slot, see 0, and insert one. Two rows?
Each holds a predicate lock on the slot, which covers the row the other inserts. The database aborts T2.
Phantom under Two-phase lockingTwo users book room 123 for noon. Each checks that no booking overlaps, then inserts one.
| # | User 1 | User 2 |
|---|---|---|
| 1 | count bookings for room 123 at noon → 0, predicate lock taken | |
| 2 | count bookings for room 123 at noon → 0, predicate lock taken | |
| 3 | waits: User 2’s predicate lock covers booking 41 | |
| 4 | waits: User 1’s predicate lock covers booking 42 | |
| 5 | aborts: deadlock, both transactions are waiting for each other | |
| 6 | writes booking 41 = ‘room 123, 12:00–13:00’ | |
| 7 | commits |
Correct, because it aborts User 2 1 booking for room 123 at noon.
How the column works Snapshot isolation that also remembers what each transaction read. Nobody waits. When a transaction that wrote something tries to commit, the database checks whether another transaction has since committed a write to data it read. If so, a premise of its decision may be out of date, and it aborts. First updater wins still applies to the same row.
In miniatureBoth count rows in the slot, see 0, and insert one. Two rows?
No. T2 aborts at commit: T1 inserted a row T2’s count should have seen.
Phantom under Serializable snapshot isolationTwo users book room 123 for noon. Each checks that no booking overlaps, then inserts one.
| # | User 1 | User 2 |
|---|---|---|
| 1 | count bookings for room 123 at noon → 0 | |
| 2 | count bookings for room 123 at noon → 0 | |
| 3 | writes booking 41 = ‘room 123, 12:00–13:00’ | |
| 4 | writes booking 42 = ‘room 123, 12:00–13:00’ | |
| 5 | commits | |
| 6 | aborts at commit: User 1 committed a write to data it read |
Correct, because it aborts User 2 1 booking for room 123 at noon.
How the column works One transaction at a time, start to finish, on a single thread. No locks, no snapshots, nothing to detect: the races cannot happen because nothing interleaves. The cost is that every transaction must be short, and throughput is limited to one CPU core per partition.
In miniatureBoth count rows in the slot, see 0, and insert one. Two rows?
No. T2 counts after T1 commits, finds T1’s row and refuses.
Phantom under Actual serial executionTwo users book room 123 for noon. Each checks that no booking overlaps, then inserts one.
| # | User 1 | User 2 |
|---|---|---|
| 1 | count bookings for room 123 at noon → 0 | |
| 2 | writes booking 41 = ‘room 123, 12:00–13:00’ | |
| 3 | commits | |
| 4 | count bookings for room 123 at noon → 1 (booking 41) | |
| 5 | finds the room taken: booking refused |
Correct 1 booking for room 123 at noon.
Read down a column and the levels sort themselves. Read committed lets 4 of the 6 through
(read skew, lost update, write skew, phantom). Snapshot isolation without lost-update detection, which is MySQL InnoDB’s
“repeatable read”, lets 3 through; with detection, as in PostgreSQL’s repeatable read,
2. Locking every row you read with SELECT … FOR UPDATE stops all but
1: phantom. Only the three serializable strategies, two-phase locking,
serializable snapshot isolation and plain serial execution, let none through, and they do it in
three different ways: by waiting, by aborting, and by never interleaving at all.
Only see, and only overwrite, committed data
The most basic level of transaction isolation makes two guarantees. No dirty reads: when reading, you only see data that has been committed. No dirty writes: when writing, you only overwrite data that has been committed. It is the default in Oracle 11g, PostgreSQL, SQL Server 2012, MemSQL and many others.
Why no dirty reads
If a transaction updates several objects, a dirty read lets another see some of the updates and not others: the new email without the counter. And if the transaction aborts, a dirty read has seen data that was never committed. Most databases prevent it without making readers wait: they remember the old committed value next to the new one, and hand readers the old value until the writer commits. A read lock would let one long write stall every read-only transaction.
Why no dirty writes
In the car sale, buying takes two writes, the listing and the invoice. With dirty writes, the car goes to Bob and the invoice to Alice, as the matrix’s first column shows. Databases prevent it with row-level locks: a transaction must take the lock on an object to modify it and hold it until it commits or aborts. Note what that does not prevent: in the counter increment, the second write comes after the first commits, so it is not a dirty write, and an update is still lost.
Each transaction sees the database as of its start
Read committed still allows read skew. Alice has $1,000 split across two accounts and looks at both while $100 moves between them: she sees account 1 before the incoming payment and account 2 after the outgoing one, and $100 seems to have vanished. Reloading fixes it, but some work cannot tolerate it: a backup, which takes hours and would capture parts of the database at different times, making the inconsistency permanent on restore; and analytic queries and integrity checks, which return nonsense if they read data from different points in time.
Snapshot isolation is the common solution: each transaction reads from a consistent snapshot, seeing all the data committed when it started, and nothing committed later. PostgreSQL, MySQL’s InnoDB, Oracle and SQL Server support it. The implementation is a generalization of how read committed avoids dirty reads: keep several committed versions of each object, because different in-progress transactions may need to see the state at different points in time. That is multi-version concurrency control (MVCC). Here is PostgreSQL’s version, row by row, with the book’s four visibility rules applied to each one.
MVCC rows and the four visibility rules, figure 7-7
| created_by | deleted_by | account | balance | visible to txid 12? |
|---|---|---|---|---|
| 3 | 1 | $500 | yes, created by txid 3 committed before 12 began | |
| 3 | 2 | $500 | yes, created by txid 3 committed before 12 began |
| created_by | deleted_by | account | balance | visible to txid 12? |
|---|---|---|---|---|
| 3 | 13 | 1 | $500 | yes, deletion ignored: txid 13 started after 12 (rule 3) |
| 3 | 2 | $500 | yes, created by txid 3 committed before 12 began | |
| 13 | 1 | $600 | no, created by txid 13 started after 12 (rule 3) |
| created_by | deleted_by | account | balance | visible to txid 12? |
|---|---|---|---|---|
| 3 | 13 | 1 | $500 | yes, deletion ignored: txid 13 started after 12 (rule 3) |
| 3 | 13 | 2 | $500 | yes, deletion ignored: txid 13 started after 12 (rule 3) |
| 13 | 1 | $600 | no, created by txid 13 started after 12 (rule 3) | |
| 13 | 2 | $400 | no, created by txid 13 started after 12 (rule 3) |
| created_by | deleted_by | account | balance | visible to txid 12? |
|---|---|---|---|---|
| 3 | 13 | 1 | $500 | yes, deletion ignored: txid 13 started after 12 (rule 3) |
| 3 | 13 | 2 | $500 | yes, deletion ignored: txid 13 started after 12 (rule 3) |
| 13 | 1 | $600 | no, created by txid 13 started after 12 (rule 3) | |
| 13 | 2 | $400 | no, created by txid 13 started after 12 (rule 3) |
| created_by | deleted_by | account | balance | visible to txid 14? |
|---|---|---|---|---|
| 3 | 13 | 1 | $500 | no, deleted by txid 13 committed before 14 began |
| 3 | 13 | 2 | $500 | no, deleted by txid 13 committed before 14 began |
| 13 | 1 | $600 | yes, created by txid 13 committed before 14 began | |
| 13 | 2 | $400 | yes, created by txid 13 committed before 14 began |
Indexes over versions
One option is for the index to point to all versions of an object and filter out the invisible ones at query time; garbage collection removes old versions and their entries. CouchDB, Datomic and LMDB use an append-only, copy-on-write B-tree instead: a write never changes a page but copies it, and every parent up to the root, so each write transaction creates a new root, and a root is a consistent snapshot.
Repeatable read, and nobody knows what it means
The SQL standard’s isolation levels come from System R in 1975, before snapshot isolation existed, so the standard has no name for it. PostgreSQL and MySQL call their snapshot isolation repeatable read, Oracle calls its serializable, and IBM DB2 uses repeatable read to mean serializability. The standard’s own definition is ambiguous and imprecise. Nobody really knows what repeatable read means.
Read, modify, write, and race
Read committed and snapshot isolation are mostly about what a read-only transaction can see. When two transactions write concurrently, the best-known problem is the lost update: an application reads a value, modifies it and writes it back, a read-modify-write cycle, and two of those running at once lose one modification. Incrementing a counter, updating an account balance, adding an element to a list in a JSON document, two people saving the same wiki page.
The matrix’s lost-update row is the counter from figure 7-1: both users read 42 and both write 43. Read committed, and snapshot isolation as MySQL implements it, end with the counter at 43 after two committed increments. The fixes, in rough order of preference:
Atomic write operations
UPDATE counters SET value = value + 1
WHERE key = 'foo';Safe in most relational databases; MongoDB and Redis have equivalents for documents and data structures. Usually implemented with an exclusive lock held while the update applies (cursor stability) or by running all atomic operations on one thread. ORMs make it easy to write a read-modify-write cycle by accident instead. A wiki page edit cannot be expressed this way.
Explicit locking
BEGIN TRANSACTION;
SELECT * FROM figures
WHERE name = 'robot' AND game_id = 222
FOR UPDATE;
-- check the move is valid, then:
UPDATE figures SET position = 'c4'
WHERE id = 1234;
COMMIT;The book’s multiplayer game: FOR UPDATE locks every row the query returns. It works, and it is
easy to forget a lock somewhere. That is the matrix’s third column.
Automatic lost-update detection
Let the read-modify-write cycles run in parallel, and if the transaction manager detects a lost update, abort the offending transaction and force it to retry. It fits snapshot isolation naturally. PostgreSQL’s repeatable read, Oracle’s serializable and SQL Server’s snapshot isolation do it; MySQL InnoDB’s repeatable read does not, which by some definitions means it does not provide snapshot isolation at all. The application needs no special code.
Compare-and-set
UPDATE wiki_pages SET content = 'new content'
WHERE id = 1234 AND content = 'old content';For databases without transactions: only update if the value is still what you read, and retry
if not. Beware a database that evaluates the WHERE clause against an old snapshot, which defeats
the check.
Replicated databases need a different answer. Locks and compare-and-set assume one up-to-date copy, which multi-leader and leaderless replication do not have (chapter 5). The usual approach is to keep concurrent versions as siblings and merge them. Commutative atomic operations, like incrementing a counter or adding to a set, work well there; Riak 2.0’s datatypes prevent lost updates across replicas. Last write wins, the default in many replicated databases, is prone to them.
Two transactions, two different rows, one broken rule
A hospital needs at least one doctor on call. Alice and Bob are both on call for a shift, both feel unwell, and both click “go off call” at about the same time. Each transaction checks that at least two doctors are on call, sees two, and takes its own doctor off. Both commit. Nobody is on call. It is not a dirty write or a lost update, because the two transactions updated different objects. It is write skew.
Write skew is a generalization of the lost update: two transactions read the same objects, then update some of them. Updating the same object would give a dirty write or a lost update; updating different ones defeats every single-object defence. In the matrix it gets past 4 of the 8 strategies, including lost-update detection, and nothing short of serializable isolation catches it automatically. The second-best option is to lock the rows the decision depends on:
BEGIN TRANSACTION;
SELECT * FROM doctors
WHERE on_call = true AND shift_id = 1234
FOR UPDATE;
UPDATE doctors SET on_call = false
WHERE name = 'Alice' AND shift_id = 1234;
COMMIT;The same pattern turns up everywhere: a meeting room booked twice; two players moving
different figures to the same square; two users claiming the same username (a unique
constraint is the simple fix there); double-spending points by inserting two spending items that
each pass the balance check. All follow three steps: a SELECT checks a condition, the application
decides, and a write changes the condition the check depended on.
Phantoms
In the doctors’ case, the row the write changes is one the SELECT returned, so FOR UPDATE has
something to lock. The meeting room is different: the check looks for the absence of rows, and
the write adds one. When the query returns nothing, SELECT FOR UPDATE cannot attach locks to
anything, and the matrix’s phantom row shows it failing (2 bookings for room 123 at noon: the room is double-booked).
A write in one transaction changing the result of a search query in another is a phantom.
Snapshot isolation avoids phantoms in read-only queries; in read-write transactions they lead to
write skew.
Materializing conflicts is the workaround: create a table of rooms and 15-minute time slots for
the next six months, rows that exist purely to be locked, so a booking can SELECT FOR UPDATE the
slots it needs. It turns a phantom into a lock on concrete rows. It is also hard to get right, and
ugly to let concurrency control leak into the data model. A last resort; serializable isolation is
much preferable.
Remove the concurrency entirely
Isolation levels are hard to understand and inconsistently implemented, and there are no good tools for spotting race conditions in application code. The researchers’ answer has always been the same: serializable isolation, the guarantee that the result is the same as if the transactions had run one at a time. There are three ways to provide it, and the simplest is to do exactly that: run one transaction at a time, in serial order, on a single thread.
It only became feasible around 2007, for two reasons: RAM became cheap enough to keep the entire active dataset in memory, and OLTP transactions turned out to be short, while long analytic queries are read-only and can run on a snapshot outside the serial loop. VoltDB (H-Store), Redis and Datomic work this way. A single thread can even beat a concurrent system, because it pays nothing for locks. It does demand a different shape of transaction:
An interactive transaction against a stored procedure, figure 7-9
Stored procedures have a bad reputation: each vendor’s own archaic language (PL/SQL, T-SQL, PL/pgSQL), code in the database that is harder to debug, version, test and monitor, and a badly written procedure in a shared database hurts every application. Modern implementations use general-purpose languages instead. VoltDB also replicates by running the same stored procedure on every replica, which requires it to be deterministic.
A single thread is limited to one CPU core. To scale further, partition the data so each transaction touches one partition, and give each core its own partition and its own thread. A transaction that has to touch several partitions must run in lock-step across all of them:
Cores against cross-partition transactions
When serial execution is viable
Every transaction is small and fast, because one slow transaction stalls them all. The active dataset fits in memory; if a transaction needs data on disk, some systems abort it, fetch the data asynchronously and restart it (anti-caching). Write throughput is low enough for one CPU core, or the transactions partition cleanly. Cross-partition transactions are possible, within a hard limit, here 1,000 a second.
Readers block writers, and writers block readers
For about 30 years, two-phase locking was the only widely used algorithm for serializability. (It is not two-phase commit, chapter 9’s subject, despite the name.) Several transactions may read the same object concurrently, but as soon as anyone wants to write it, they need exclusive access: a writer waits for readers to finish, and a reader waits for a writer to finish. That is the exact opposite of snapshot isolation’s rule, and it is what protects against every race condition, including lost updates and write skew.
How it is implemented
A lock on each object, in shared or exclusive mode. Reading takes a shared lock, which several transactions may hold at once, but not alongside an exclusive one. Writing takes an exclusive lock, which nobody else may hold in any mode. Locks are kept until the transaction ends: acquired while it runs, all released at the end, hence two phases. When two transactions each wait for the other, that is a deadlock; the database detects it and aborts one. The matrix’s lost update under 2PL is exactly that, and so is its write skew.
Why it is slow
Throughput and response times are significantly worse than under weak isolation: the overhead of the locks, and above all reduced concurrency. A queue forms behind any contended object, and one slow transaction, or one that touches a lot of data, can bring the rest to a halt, so latency is unstable at the high percentiles. Deadlocks are far more frequent, and an aborted transaction redoes all its work.
Predicate locks
The phantom needs a lock on rows that do not exist yet. A predicate lock belongs to all objects matching a search condition, such as bookings of room 123 overlapping noon to one. A read takes one in shared mode; any insert, update or delete must check its old and new values against every predicate lock held by others, and wait if one matches. With them, 2PL prevents all write skew, and the matrix’s phantom row says so.
Index-range locks
Checking every predicate lock is slow, so most databases approximate it: lock more than the predicate, through an index. Lock the index entry for room 123 (all its bookings, at any time), or a range of the time index (every room at noon). Any write matching the real predicate must touch that part of the index and hits the lock. Also called next-key locking. Without a suitable index, it falls back to locking the whole table.
Don’t block; check at commit
So far serializability either performs badly (2PL) or does not scale (serial execution), and weak isolation performs well and lets race conditions through. Serializable snapshot isolation offers full serializability for a small penalty over snapshot isolation. It is new: first described in 2008 in Michael Cahill’s PhD thesis, used in PostgreSQL’s serializable level since 9.1, and in FoundationDB as a distributed algorithm.
Pessimistic
2PL waits whenever something might go wrong, like mutual exclusion in multithreaded code. Serial execution is pessimistic to the extreme, an exclusive lock on the whole database, and compensates by making each transaction very fast.
Optimistic
SSI lets transactions continue and hopes it turns out fine. At commit, the database checks whether isolation was violated, and aborts if so. Under high contention many transactions abort, and the retries add load to a system that is already near its limit. With spare capacity and little contention it tends to beat pessimistic approaches. Commutative operations, like concurrent increments of a counter that is not read, do not conflict at all.
SSI runs every transaction on a snapshot, exactly as snapshot isolation does, and adds one thing: it detects when a transaction acted on an outdated premise. Write skew always has the same shape: a transaction reads something, decides based on what it read, and writes; by commit time, what it read may no longer be true. The database tracks two cases.
Reads of a stale version
When a transaction’s snapshot ignores another’s uncommitted write, the database remembers it. At commit, if any of those ignored writes have since committed, the transaction aborts. It waits until commit rather than aborting at the read, because the reader may turn out to be read-only, or the writer may abort.
Writes that affect prior reads
Like an index-range lock, except it does not block: the database records which transactions read a part of an index, and when a transaction writes there, it notifies the readers that their reads may be outdated. A tripwire, not a barrier. In the doctors’ case both transactions trip each other’s wire; the first to commit wins, and the second is aborted at its commit.
Open the matrix’s write-skew row under SSI to watch exactly that. Compared with 2PL, nobody waits for anybody’s locks, so latency is predictable and read-only queries never need a lock at all. Compared with serial execution, it is not limited to one core, and FoundationDB spreads the conflict detection across machines. The price is aborts: a long read-write transaction is likely to conflict, so SSI wants read-write transactions to be short, though it is probably less sensitive to slow transactions than either alternative. Precise tracking aborts fewer transactions and costs more bookkeeping; PostgreSQL uses theory to skip aborts it can prove unnecessary.
Did it stick?
1. What does atomicity in ACID describe?
2. Why does the chapter say the C in ACID does not really belong there?
3. Read committed makes two guarantees. Which?
4. How do most databases prevent dirty reads without making readers wait?
5. Alice reads account 1 ($500) and then account 2 ($400) while $100 moves between them. What is this, and what prevents it?
6. Under MVCC snapshot isolation, which writes does a transaction ignore?
7. What does “repeatable read” mean?
8. Which of these prevents the lost update in a counter increment?
9. Two doctors on call each check that two are on call, then each takes themself off. Why doesn’t lost-update detection catch it?
10. Why does SELECT … FOR UPDATE not stop two users booking the same meeting room?
11. In two-phase locking, what blocks what?
12. How does serializable snapshot isolation differ from two-phase locking?
Answered 0 of 12 · 0 correct
The terms this chapter installs
Chapter 7 in one breath. Transactions are an abstraction layer that lets an application pretend certain concurrency problems and certain hardware and software faults do not exist: a large class of errors reduces to a simple abort, and the application tries again. Without them, crashing processes, network interruptions, power outages, full disks and unexpected concurrency leave data inconsistent in many ways, and denormalized data drifts out of sync with its source.
The isolation levels, and the races they leave open: dirty reads and dirty writes, prevented
by read committed and almost everything above it; read skew, prevented by snapshot isolation,
usually with MVCC; lost updates, which some snapshot isolation implementations detect and others
leave to SELECT FOR UPDATE; write skew, where a premise goes stale before the write lands, which
only serializable isolation prevents; and phantoms, the write-skew case where there is no row to
lock, which needs predicate or index-range locks. Across the 6 races in the matrix,
only the serializable columns are clean.
Serializable isolation comes three ways. Serial execution, if each transaction is fast and the throughput fits on one core. Two-phase locking, the standard for decades, avoided by many for its performance. Serializable snapshot isolation, optimistic, letting transactions run without blocking and checking at commit whether they ran serializably. The examples here used a relational model, but transactions are valuable whatever the data model, and the next two chapters take them across machines.
Study aid built for recall practice. Concepts, examples, figures and named systems are Martin
Kleppmann’s, from Designing Data-Intensive Applications, chapter 7. Go back to the book for his
wording and the full reference list. The matrix is not quoted from the book: src/lib/ddia7.ts
holds a small transaction engine and runs his examples through it, and its outcomes agree with his
account of each level. The engine is a teaching model with two transactions and a handful of keys,
not a database; the throughput dial’s per-core figure is illustrative, and its cross-partition
ceiling is VoltDB’s, as he reports it. The MVCC reel uses the txids of his figure 7-7.