Sina Vafadar

Transactions

Nov 9, 2026 · 30 min

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.

The vocabulary § The Meaning of ACID

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.

What a transaction covers § Single-Object and Multi-Object Operations

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

  1. INSERT INTO emails … · ok
  2. UPDATE mailboxes SET unread = unread + 1 · fails: the connection drops
emails1unread counter0
Half-done, and nobody knowsThe email is stored and the counter never moved: 1 email, 0 unread. The application cannot tell which writes took effect, and retrying would store the email twice.

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.

The chapter as an experiment § Weak Isolation Levels · Serializability

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 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.

T1read x → 1read y → 1write x=0commitT2read x → 1read y → 1write y=0commit

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.

#AliceBob
1count doctors on call → 2 (alice, bob)
2count doctors on call → 2 (alice, bob)
3writes alice = false
4writes bob = false
5commits
6commits

Anomaly Nobody is on call. Each request checked the rule, and the rule is broken.

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.

The weakest useful level § Read Committed

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.

A consistent view § Snapshot Isolation and Repeatable Read

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_bydeleted_byaccountbalancevisible to txid 12?
31$500yes, created by txid 3 committed before 12 began
32$500yes, created by txid 3 committed before 12 began
Txid 12 begins, and reads account 1Every transaction gets a unique, always-increasing transaction ID. Each row records the txid that created it in created_by. At the start, txid 12 notes which transactions are in progress (none) and reads account 1: $500.

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.

Two writers § Preventing Lost Updates

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.

The subtle ones § Write Skew and Phantoms

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.

Serializable, way one § Actual Serial Execution

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

ApplicationDatabasetransaction opencheck availabilityrowsreserve seatcharge cardissue ticket
4 statements, 4 round tripsThe application sends a query, reads the result, decides what to send next. Most of the time the transaction is open, the database is waiting on the network. Fine when other transactions can run meanwhile. With one thread and no concurrency, that waiting is all of the throughput.

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

20k1 core34k2 cores50k4 cores67k8 cores80k16 cores89k32 cores
1% of transactions cross partitions32 cores manage 89k a second, 11% of the linear ideal (the faint bars). No number of cores gets past 100k, because a cross-partition transaction runs in lock-step across every partition, and VoltDB reports about 1,000 of those a second however many machines you add.

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.

Serializable, way two § Two-Phase Locking (2PL)

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.

Serializable, way three § Serializable Snapshot Isolation (SSI)

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.

Recall check 12 questions

Did it stick?

One attempt per question; the explanation appears either way.

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

Vocabulary Click to flip

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.

← all lab notes