Transactions
What safety guarantees transactions give, what they cost, and how databases implement isolation levels: read committed, snapshot isolation and serializability, on single-node and distributed databases.
Key takeaways
- A transaction groups reads and writes into one unit that either commits or aborts; an aborted transaction can be safely retried.
- ACID atomicity really means abortability; consistency is an application property, not a database one.
- Most databases default to weak isolation (read committed or snapshot isolation), which leaves some race conditions to the application.
- Read committed prevents dirty reads and dirty writes; snapshot isolation (MVCC) also prevents read skew.
- Lost updates are fixed by atomic operations, explicit locks, automatic detection or compare-and-set; write skew and phantoms generally need serializability.
- Serializability has three implementations: actual serial execution, two-phase locking (pessimistic, slow at high percentiles) and serializable snapshot isolation (optimistic, aborts at commit).
- "Repeatable read" and "serializable" mean different things in different databases; check what your database actually does.
The Slippery Concept of a Transaction
Many things go wrong in data systems: database or hardware crashes mid-write, the application crashes mid-sequence, the network cuts off clients or nodes, concurrent clients overwrite each other, clients read partially updated data, and race conditions cause odd bugs.
- For decades, transactions have been the main tool for simplifying these problems. All reads and writes in a transaction run as one logical operation: it commits or it aborts (rolls back).
- On abort the application can retry safely, with no partial failure to reason about. The database takes care of these cases: its safety guarantees.
- Transactions are not a law of nature. They exist to simplify the programming model. Some applications do not need them, and weakening or dropping them can buy performance or availability.
- Almost all relational databases (MySQL, PostgreSQL, Oracle, SQL Server) follow the style of IBM System R (1975), largely unchanged for 40 years.
- Late-2000s NoSQL databases often abandoned transactions or redefined the word to mean much weaker guarantees. The belief that transactions kill scalability, and the opposite claim that "serious" apps need them, are both hyperbole: transactions have advantages and limits like any design choice.
The Meaning of ACID
ACID = Atomicity, Consistency, Isolation, Durability (Härder and Reuter, 1983). In practice implementations differ, especially on isolation, so "ACID compliant" has become mostly a marketing term. BASE (Basically Available, Soft state, Eventual consistency) is vaguer still; it effectively means "not ACID".
Atomicity
- In multi-threaded programming, "atomic" means no other thread sees a half-finished result. In ACID it is not about concurrency; that is the I.
- ACID atomicity: if a fault (crash, network cut, full disk, constraint violation) stops a group of writes from committing, the transaction is aborted and the database discards every write it made.
- Without it, the app cannot tell which changes took effect, and retrying risks duplicates. With it, an aborted transaction changed nothing, so a retry is safe.
- The book suggests abortability would have been the better term.
Consistency
"Consistency" has at least four meanings:
- Replica consistency and eventual consistency (Chapter 5).
- Consistent hashing, a rebalancing approach (Chapter 6).
- In the CAP theorem, it means linearizability (Chapter 9).
- In ACID, an application-specific notion of the database being in a "good state".
- ACID consistency means invariants always hold (e.g. credits and debits balance). If each transaction starts valid and preserves validity, invariants stay satisfied.
- The application defines the invariants and writes transactions that keep them; the database cannot stop bad data. It can check some kinds (foreign key, uniqueness constraints).
- A, I and D are database properties; C is an application property that relies on A and I. "The letter C doesn't really belong in ACID."
Isolation
- Clients touching the same records concurrently hit race conditions. Example (Figure 7-1): two clients each read a counter, add 1 and write back. It should go 42 → 44 but ends at 43.
- ACID isolation: concurrent transactions cannot step on each other. Textbooks formalize it as serializability: the result is the same as if transactions had run one after another.
- In practice serializable isolation is rarely used because of its performance cost. Oracle 11g's "serializable" is actually snapshot isolation, a weaker guarantee.
Durability
- Durability: once committed, data is not forgotten despite hardware faults or crashes.
- Single node: written to nonvolatile storage (disk/SSD), usually with a write-ahead log for recovery. Replicated: copied to some number of nodes. The database must wait for these before reporting commit.
- Perfect durability does not exist: if all disks and backups are destroyed together, nothing can save you.
Replication and durability. Durability once meant archive tape, then disk, now replication. Neither is perfect:
- Disk-only: a dead machine keeps data but makes it inaccessible; replicas stay available.
- Correlated faults (power outage, a bug that crashes every node on one input) can take out all replicas, losing in-memory data, so disk still matters for in-memory databases.
- Asynchronous replication can lose recent writes when the leader fails.
- SSDs can violate guarantees on sudden power loss; even
fsyncmay not work. Disk firmware has bugs. - Storage engine and filesystem interactions can corrupt files after a crash.
- Undetected gradual corruption can spread to replicas and recent backups; restore from a historical backup.
- One study: 30%–80% of SSDs develop at least one bad block in four years. HDDs have fewer bad sectors but more complete failures.
- An unpowered SSD can start losing data within a few weeks, depending on temperature.
Single-Object and Multi-Object Operations
- Atomicity: all-or-nothing; an error halfway discards earlier writes.
- Isolation: another transaction sees all or none of a transaction's writes, never a subset.
- Both assume multi-object transactions, needed when several pieces of data must stay in sync.
- Email example: instead of counting unread emails with a slow query, store an unread counter (denormalization). Inserting an email and incrementing the counter must happen together.
- Figure 7-2: user 2 sees the new email but a counter of 0, because the increment has not happened yet. Isolation would show both or neither.
- Figure 7-3: if the counter update fails, atomicity rolls back the inserted email.
- Relational databases group a transaction by the client's TCP connection: everything between
BEGIN TRANSACTIONandCOMMIT. (If the connection drops after the commit request but before the acknowledgment, the client does not know whether it committed; a transaction ID not tied to the connection can solve this.) - Many nonrelational databases cannot group operations. A multi-put API may succeed for some keys and fail for others.
Single-object writes
- Atomicity and isolation also matter for one object. Writing a 20 KB JSON document: does an interrupted write leave a 10 KB fragment? Does a power cut splice old and new values? Does a concurrent reader see a partial value?
- Storage engines almost always give single-object atomicity (via a crash-recovery log) and isolation (via a per-object lock) on one node.
- Some offer an increment operation (no read-modify-write) or compare-and-set (write only if the value is unchanged). These prevent lost updates.
- They are not transactions in the usual sense. Calling them "lightweight transactions" or "ACID" is misleading; a transaction groups operations on multiple objects.
The need for multi-object transactions
Many distributed datastores dropped multi-object transactions because they are hard across partitions and can hurt very high availability or performance. Nothing fundamentally prevents them (Chapter 9). Cases needing coordinated writes:
- Foreign keys (or graph edges): records that refer to each other must stay valid.
- Document databases: one document needs no multi-object transaction, but lack of joins encourages denormalization, and updating denormalized data touches several documents.
- Secondary indexes are separate objects; without isolation a record can appear in one index but not another.
You can build such apps without transactions, but error handling gets much harder without atomicity, and missing isolation causes concurrency problems.
Handling errors and aborts
- ACID databases would rather abandon a transaction than leave it half-finished.
- Leaderless-replication datastores work on a best effort basis: they do not undo what is done, so recovery falls on the application.
- ORMs such as Rails's ActiveRecord and Django do not retry aborted transactions; the exception bubbles up and user input is lost. That wastes the point of aborts: safe retries.
Retrying is simple and effective but not perfect:
- If the commit succeeded but the acknowledgment was lost, a retry runs it twice unless the app deduplicates.
- If the error is overload, retries make it worse. Limit retries, use exponential backoff, and treat overload errors differently.
- Retry only transient errors (deadlock, isolation violation, network blip, failover), not permanent ones (constraint violation).
- Side effects outside the database (e.g. sending an email) may happen even if the transaction aborts. Two-phase commit can make several systems commit or abort together.
- If the client fails while retrying, the data it was writing is lost.
Weak Isolation Levels
- Race conditions only arise when one transaction reads data another is modifying, or two modify the same data.
- Concurrency bugs are timing-dependent, rare, hard to reproduce by testing and hard to reason about in large apps.
- Serializable isolation lets you pretend there is no concurrency, but costs performance, so many systems use weaker, nonserializable levels that protect against some issues only.
- Weak isolation bugs have caused loss of money, auditor investigations and corrupted customer data. "Use an ACID database" misses the point: many popular relational databases use weak isolation too.
- So understand the kinds of concurrency problems and how to prevent them, rather than blindly trusting tools.
Read Committed
The most basic level. Two guarantees:
- No dirty reads: you only see committed data.
- No dirty writes: you only overwrite committed data.
(An even weaker level, read uncommitted, prevents dirty writes but not dirty reads.)
No dirty reads
- A dirty read is seeing another transaction's uncommitted writes. Under read committed, a transaction's writes become visible only when it commits, all at once.
- Why it matters: seeing a partial multi-object update (Figure 7-2) confuses users and can mislead other transactions; and seeing writes later rolled back (Figure 7-3) is mind-bending to reason about.
No dirty writes
- A dirty write overwrites a value written by a transaction that has not yet committed. Read committed prevents it, usually by delaying the second write until the first transaction commits or aborts.
- Figure 7-5: Alice and Bob buy the same car. Each must update the listing and the invoice. With dirty writes, Bob wins the listing and Alice wins the invoice.
- Read committed does not stop the counter race of Figure 7-1: the second write comes after the first commits, so it is not dirty, just wrong in another way (lost update).
Implementing read committed
- Very popular: default in Oracle 11g, PostgreSQL, SQL Server 2012, MemSQL and others.
- Dirty writes: row-level locks. A writer acquires the object's lock and holds it until commit or abort; other writers wait. Done automatically.
- Dirty reads could use the same lock briefly for reads, but one long write transaction would then block many readers, hurting response time and spreading slowdowns across the app.
- So most databases remember the old committed value and the new uncommitted value; readers get the old value until commit. (Only IBM DB2 and SQL Server with
read_committed_snapshot=offuse read locks.)
Snapshot Isolation and Repeatable Read
- Read committed allows aborts, hides incomplete results and stops intermingled writes, yet still allows bugs.
- Figure 7-6: Alice has $1,000 split as $500 in two accounts. A transfer moves $100. Reading mid-transfer she sees $500 and $400: $100 seems to vanish.
- This is nonrepeatable read or read skew; re-reading account 1 would give $600. It is acceptable under read committed, since each value was committed when read. ("Skew" here means a timing anomaly, not a hot spot.)
Alice can reload and see consistent balances, but some cases cannot tolerate temporary inconsistency:
- Backups take hours while writes continue; a backup mixing old and new versions makes inconsistencies permanent on restore.
- Analytic queries and integrity checks scan much of the database; seeing parts at different times gives nonsensical results.
Snapshot isolation is the common fix: each transaction reads a consistent snapshot of everything committed at its start, even if data later changes. It suits long read-only queries. Supported by PostgreSQL, MySQL/InnoDB, Oracle, SQL Server and others.
Implementing snapshot isolation
- Write locks prevent dirty writes as in read committed; reads take no locks.
- Key principle: readers never block writers, and writers never block readers.
- The database keeps several committed versions of each object, because in-progress transactions may need different points in time: multi-version concurrency control (MVCC).
- Read committed only needs two versions (committed and uncommitted), but MVCC engines typically use it for read committed too: a new snapshot per query, versus one snapshot per transaction for snapshot isolation.
- PostgreSQL (Figure 7-7): each transaction gets a unique, always-increasing transaction ID (
txid, 32-bit; vacuum handles overflow). Writes are tagged with the writer's txid. - Each row has
created_byanddeleted_by. Delete setsdeleted_by; garbage collection removes the row once no transaction can see it. - An update becomes a delete plus a create. Transaction 13 deducting $100 from account 2 leaves a $500 row deleted by 13 and a $400 row created by 13.
Visibility rules for observing a consistent snapshot
- At transaction start, list all in-progress transactions; ignore their writes even if they later commit.
- Ignore writes by aborted transactions.
- Ignore writes by transactions with a later txid, committed or not.
- All other writes are visible.
- Rules apply to creation and deletion. In Figure 7-7, transaction 12 sees $500 because 13's delete and create are both invisible under rule 3.
- Equivalently, an object is visible if its creator had committed when the reader started, and it is not deleted, or its deleter had not committed when the reader started.
- Never updating in place, but always creating a new version, gives consistent snapshots at small overhead, even for long-running readers.
Indexes and snapshot isolation
- Option 1: the index points to all versions and queries filter out invisible ones; garbage collection removes index entries with old versions. PostgreSQL avoids index updates when versions of an object fit on the same page.
- Option 2 (CouchDB, Datomic, LMDB): append-only / copy-on-write B-trees. A write copies each modified page and its parents up to the root; unaffected pages stay immutable and shared.
- Each write transaction (or batch) creates a new root, which is a consistent snapshot. No txid filtering needed, but background compaction and garbage collection are.
Repeatable read and naming confusion
- Snapshot isolation is called serializable in Oracle and repeatable read in PostgreSQL and MySQL.
- The SQL standard follows System R's 1975 isolation levels, before snapshot isolation existed. It defines repeatable read, which looks similar, so PostgreSQL and MySQL use that name to claim compliance.
- The standard's definitions are ambiguous, imprecise and not implementation-independent. Implementations of repeatable read differ widely; most do not meet the research literature's formal definition; IBM DB2 uses "repeatable read" for serializability.
- "Nobody really knows what repeatable read means."
Preventing Lost Updates
- Read committed and snapshot isolation are mostly about what readers see under concurrent writes. Dirty writes are just one kind of write-write conflict.
- The best known other one is the lost update: two concurrent read-modify-write cycles; the later write clobbers the earlier one.
- Occurs when incrementing a counter or balance, making a local change to a complex value (adding to a list in a JSON document), or two users saving whole wiki pages at once.
Atomic write operations
- Database-provided atomic updates remove the read-modify-write cycle from app code and are usually the best choice when they fit. E.g.
UPDATE counters SET value = value + 1 WHERE key = 'foo';is concurrency-safe in most relational databases. - MongoDB offers atomic local changes to JSON documents; Redis offers atomic changes to data structures like priority queues. Arbitrary text edits (wiki pages) do not fit.
- Implemented with an exclusive lock on read until the update is applied (cursor stability), or by running all atomic operations on one thread.
- ORMs make it easy to write unsafe read-modify-write cycles by accident, a source of bugs hard to find by testing.
Explicit locking
- The application locks the objects it will update; concurrent readers wait until the cycle completes.
- Example 7-1, a multiplayer game: a move must obey game rules that a query cannot express, so lock the piece with
SELECT ... FOR UPDATE, check the move, thenUPDATEits position. FOR UPDATElocks every returned row. It works, but it is easy to forget a lock and create a race.
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;
Automatically detecting lost updates
- Alternative: let cycles run in parallel; if the transaction manager detects a lost update, abort and retry.
- Efficient alongside snapshot isolation. PostgreSQL's repeatable read, Oracle's serializable and SQL Server's snapshot isolation detect it; MySQL/InnoDB's repeatable read does not. Some authors say that disqualifies MySQL from snapshot isolation.
- Needs no special app code, so it is less error-prone than remembering locks or atomic operations.
Compare-and-set
- In databases without transactions: update only if the value is unchanged since you read it; otherwise do nothing and retry.
- Wiki example:
UPDATE wiki_pages SET content = 'new content' WHERE id = 1234 AND content = 'old content';then check whether it took effect. - If the
WHEREclause can read from an old snapshot, this may not prevent lost updates. Check that your database's compare-and-set is safe.
Conflict resolution and replication
- Locks and compare-and-set assume a single up-to-date copy. Multi-leader and leaderless replication allow concurrent writes replicated asynchronously, so those techniques do not apply.
- Common approach: allow conflicting versions (siblings) and merge them afterward with app code or special data structures.
- Commutative atomic operations (increment a counter, add to a set) work well across replicas. Riak 2.0 datatypes merge concurrent updates without losing any.
- Last write wins (LWW) is prone to lost updates and is the default in many replicated databases.
| Technique | How it prevents lost updates | Caveat |
|---|---|---|
| Atomic write operation | Database does the read-modify-write (lock or single thread) | Only for operations it supports; ORMs bypass it |
Explicit lock (FOR UPDATE) | App forces cycles to run sequentially | Easy to forget a lock |
| Automatic detection | Abort and retry the losing transaction | Not in MySQL/InnoDB repeatable read |
| Compare-and-set | Write only if value unchanged | Unsafe if WHERE reads an old snapshot |
| Replicated: siblings / commutative ops | Merge concurrent versions | LWW (common default) loses updates |
Write Skew and Phantoms
- Dirty writes and lost updates involve concurrent writes to the same object. Subtler conflicts exist.
- Hospital on-call example: there must be at least one doctor on call per shift. Alice and Bob are both on call, both sick, and both click "go off call" at about the same time (Figure 7-8).
- Each transaction checks that two or more doctors are on call. Under snapshot isolation both see 2, both remove themselves, both commit: zero doctors on call.
Characterizing write skew
- Write skew is neither a dirty write nor a lost update: the transactions update different objects. Run serially, the second doctor would have been refused.
- It generalizes lost update: two transactions read the same objects, then update some of them (possibly different ones). If they update the same object, you get a dirty write or lost update.
Options are more limited than for lost updates:
- Atomic single-object operations do not help: several objects are involved.
- Automatic lost-update detection does not help: PostgreSQL repeatable read, MySQL/InnoDB repeatable read, Oracle serializable and SQL Server snapshot isolation do not detect write skew. Automatic prevention needs true serializable isolation.
- Multi-object constraints ("at least one doctor on call") are rarely built in; triggers or materialized views may work, depending on the database.
- Without serializable isolation, the second-best option is to explicitly lock the rows the transaction 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;
More examples of write skew
- Meeting room booking (Example 7-2): check for overlapping bookings for the room, then insert if none. Snapshot isolation does not stop a concurrent conflicting insert; serializable isolation is needed. (PostgreSQL range types help, but are not widely supported.)
- Multiplayer game: the Example 7-1 lock stops two players moving the same figure, but not moving two figures to the same square or other rule violations. A unique constraint may work for some rules.
- Claiming a username: check-then-create is unsafe under snapshot isolation; a unique constraint is a simple fix (the second insert aborts).
- Preventing double-spending: insert a tentative spending item, sum the account, check it is positive. Two concurrent items can together push the balance negative unseen.
-- Example 7-2 (unsafe under snapshot isolation)
SELECT COUNT(*) FROM bookings WHERE room_id = 123
AND end_time > '2015-01-01 12:00' AND start_time < '2015-01-01 13:00';
-- if zero:
INSERT INTO bookings (room_id, start_time, end_time, user_id)
VALUES (123, '2015-01-01 12:00', '2015-01-01 13:00', 666);
Phantoms causing write skew
All examples share one pattern:
- A
SELECTchecks a requirement by searching for matching rows. - The app decides, based on the result, whether to proceed.
- If so, it writes (
INSERT/UPDATE/DELETE) and commits. The write changes the precondition: repeating step 1 would now give a different result.
- The steps may be reordered (write, then query, then commit or abort).
- In the doctors case, step 3 modifies rows returned in step 1, so
SELECT FOR UPDATEfixes it. The other four check for the absence of rows and then add one; with no rows returned, there is nothing to lock. - A phantom is a write in one transaction changing the result of a search query in another. Snapshot isolation avoids phantoms in read-only queries, but in read-write transactions phantoms cause tricky write skew.
Materializing conflicts
- Introduce lock objects artificially. Booking example: a table of rooms × time slots (say 15 minutes), pre-created e.g. for the next six months.
- A booking transaction locks (
SELECT FOR UPDATE) the relevant slot rows, then checks for overlaps and inserts. The table holds no booking data; it is purely locks. - Materializing conflicts turns a phantom into a lock conflict on concrete rows.
- It is hard and error-prone, and leaks concurrency control into the data model. Use it as a last resort; serializable isolation is much preferable.
Serializability
The state of weak isolation is sad:
- Isolation levels are hard to understand and inconsistently implemented (e.g. "repeatable read").
- It is hard to tell from app code whether it is safe at a given level, especially in large apps.
- No good tools detect race conditions; static analysis research has not reached practice, and nondeterministic bugs are hard to test.
Researchers' answer since the 1970s: use serializable isolation, usually regarded as the strongest level. Even with parallel execution the result equals some serial order, so if transactions are correct alone they are correct concurrently: the database prevents all race conditions. Three implementation techniques (single-node here; distributed in Chapter 9):
- Literally executing transactions in serial order.
- Two-phase locking, for decades the only viable option.
- Optimistic concurrency control such as serializable snapshot isolation.
Actual Serial Execution
- Remove concurrency: run one transaction at a time on a single thread. Isolation is serializable by definition.
- Only around 2007 did designers decide a single-threaded loop was feasible. Two changes made it so:
- RAM became cheap enough to keep the whole active dataset in memory, so transactions run much faster without waiting for disk.
- OLTP transactions are usually short with few reads and writes; long analytic queries are read-only and can run on a snapshot outside the serial loop.
- Used by VoltDB/H-Store, Redis and Datomic. Avoiding lock coordination can make it faster than concurrent systems, but throughput is capped at one CPU core, and transactions must be structured differently.
Encapsulating transactions in stored procedures
- Early databases imagined one transaction spanning a whole user flow (e.g. an airline booking: search, choose, book seats, enter details, pay).
- Humans are slow, so that means huge numbers of mostly idle transactions. Most OLTP apps instead commit within one HTTP request; a new request starts a new transaction.
- Transactions still run interactively, one statement at a time, with network round trips between app and database. Serial execution would leave the database waiting most of the time, so such databases need concurrency.
- Hence serial systems forbid interactive multi-statement transactions. The app submits the whole transaction ahead of time as a stored procedure. With data in memory, it runs very fast with no network or disk wait (Figure 7-9).
Pros and cons of stored procedures
Part of the SQL standard (SQL/PSM) since 1999, but with a bad reputation:
- Each vendor has its own language (Oracle PL/SQL, SQL Server T-SQL, PostgreSQL PL/pgSQL): archaic, few libraries.
- Code in the database is harder to debug, version-control, deploy, test and monitor.
- A database is shared by many app servers and is more performance-sensitive; one bad procedure can cause much more trouble.
- Modern systems use general-purpose languages: VoltDB uses Java or Groovy, Datomic Java or Clojure, Redis Lua.
- With stored procedures and in-memory data, single-threaded execution gets good throughput: no I/O waits, no concurrency-control overhead.
- VoltDB replicates by executing the same procedure on each replica, so procedures must be deterministic (e.g. current time via special deterministic APIs).
Partitioning
- Serial execution limits write throughput to one core on one machine; high-write apps hit a bottleneck.
- If each transaction touches one partition only, each partition gets its own thread; give each core a partition and throughput scales linearly with cores (VoltDB supports this).
- Cross-partition transactions need lock-step coordination across all partitions touched and are vastly slower. VoltDB reports about 1,000 cross-partition writes per second, orders of magnitude below single-partition, and not improvable by adding machines.
- Key-value data partitions easily; data with multiple secondary indexes likely needs much cross-partition coordination.
Summary of serial execution
- Every transaction must be small and fast: one slow one stalls everything.
- The active dataset must fit in memory. Rarely used data can live on disk, but touching it in a transaction is very slow. (Anti-caching: abort, fetch the data asynchronously, restart the transaction.)
- Write throughput must fit one core, or transactions must be partitioned without cross-partition coordination.
- Cross-partition transactions are possible but hard-limited.
Two-Phase Locking (2PL)
- For about 30 years the only widely used serializability algorithm. Sometimes called strong strict two-phase locking (SS2PL).
- 2PL is not 2PC (two-phase commit, Chapter 9); they are completely different.
- Readers may share an object as long as nobody writes it. Writing requires exclusive access:
- If A has read an object and B wants to write it, B waits until A commits or aborts.
- If A has written an object and B wants to read it, B waits. Reading an old version is not allowed.
- Writers block readers and readers block writers, the opposite of snapshot isolation's mantra. In exchange, 2PL prevents all earlier races, including lost updates and write skew.
Implementation of two-phase locking
- Used by serializable in MySQL (InnoDB) and SQL Server, and repeatable read in DB2.
- Each object has a lock in shared mode or exclusive mode:
- Read: acquire shared. Many may hold shared; wait if someone holds exclusive.
- Write: acquire exclusive. Wait if anyone holds any lock.
- Read then write: upgrade shared to exclusive (same as acquiring exclusive).
- Hold every lock until commit or abort.
- "Two-phase": phase 1 acquires locks while executing; phase 2 releases them all at the end.
- Deadlock: A waits for B and B for A. The database detects it and aborts one; the app must retry.
Performance of two-phase locking
- The big downside: throughput and query response times are significantly worse than under weak isolation. Partly lock overhead, mostly reduced concurrency: any potential race makes one transaction wait.
- Traditional databases do not limit transaction duration (built for human-paced interactive apps), so waits are unbounded; queues form on hot objects.
- Latencies are unstable and very slow at high percentiles under contention. One slow transaction, or one that locks a lot of data, can grind the system to a halt.
- Deadlocks happen with lock-based read committed too, but far more often under 2PL; each retried deadlock victim redoes its work.
Predicate locks
- Serializable isolation must prevent phantoms. In the booking example, after one transaction searches a room and time window, no other may insert or update a booking for the same room and overlapping time (other rooms or times are fine).
- A predicate lock belongs to all objects matching a search condition (e.g.
room_id = 123and the noon–1 p.m. window), not to one row. - Reading by condition: acquire a shared predicate lock; wait if another transaction holds an exclusive lock on any matching object.
- Insert/update/delete: check whether the old or new value matches any existing predicate lock; if another transaction holds one, wait for it to finish.
- Key idea: it covers objects that do not exist yet (phantoms). 2PL plus predicate locks prevents all write skew and races, making it serializable.
Index-range locks
- Predicate locks perform badly: checking many active locks is slow. Most 2PL databases use index-range locking (next-key locking), an approximation.
- It is safe to broaden a predicate: lock room 123 at any time, or all rooms from noon to 1 p.m. Any write matching the original also matches the broader version.
- With an index on
room_id, attach a shared lock to the index entry for room 123. With a time index, lock a range of values in it. - A conflicting write must update the same part of the index, hits the lock and waits. This protects against phantoms and write skew.
- Less precise than predicate locks (may lock more than needed) but much cheaper: a good compromise.
- With no suitable index, fall back to a shared lock on the whole table: safe, but stops all other writers.
Serializable Snapshot Isolation (SSI)
- So far: serializability that performs badly (2PL) or does not scale (serial execution), versus weak isolation that is fast but racy.
- Serializable snapshot isolation (SSI) gives full serializability with only a small penalty over snapshot isolation. First described in 2008 (Michael Cahill's PhD thesis).
- Used in PostgreSQL's serializable level since 9.1, and a similar algorithm in FoundationDB (distributed). Still proving itself, but could become the new default.
Pessimistic versus optimistic concurrency control
- 2PL is pessimistic: if anything might go wrong, wait until safe, like mutual exclusion.
- Serial execution is pessimistic to the extreme: an exclusive lock on the whole database (or partition) per transaction, made tolerable by very fast transactions.
- SSI is optimistic: proceed without blocking; at commit, check whether isolation was violated and abort if so. Only serializable executions commit.
- Optimistic control is an old idea. It performs badly under high contention (many aborts), and retries add load near maximum throughput.
- With spare capacity and low contention it tends to beat pessimistic control. Commutative atomic operations (e.g. concurrent counter increments, if the counter is not read in the same transaction) reduce contention.
- Unlike earlier optimistic techniques, SSI reads from a consistent snapshot, and adds an algorithm to detect serialization conflicts and choose which transactions to abort.
Decisions based on an outdated premise
- Write skew pattern: read, examine, act on the result. Under snapshot isolation the read may be out of date by commit time.
- The transaction acts on a premise (e.g. "two doctors are on call") that may no longer be true at commit.
- The database does not know how the app uses a query result, so it must assume a causal dependency: any change in the premise may invalidate the writes. It must detect transactions that acted on an outdated premise and abort them.
- Two cases:
- Reads of a stale MVCC version (an uncommitted write happened before the read).
- Writes that affect prior reads (the write happens after the read).
Detecting stale MVCC reads
- Figure 7-10: transaction 43 sees Alice as
on_call = truebecause 42's change was uncommitted at snapshot time. By 43's commit, 42 has committed, so 43's premise is false. - The database tracks when a transaction ignores another's writes due to MVCC visibility. At commit, if any ignored write has since committed, abort.
- Why wait until commit? A read-only transaction needs no abort (no write skew risk), and the database does not yet know whether 43 will write. Also 42 may still abort or be uncommitted. Avoiding unneeded aborts keeps snapshot isolation's support for long-running reads.
Detecting writes that affect prior reads
- Case 2: another transaction modifies data after it was read (Figure 7-11).
- Like index-range locks, but SSI locks do not block. Both 42 and 43 search on-call doctors for shift 1234; the index entry for
shift_id = 1234records that they read it (or the table, if no index). - This record is kept only until the transaction and all concurrent ones have finished.
- A writer looks in the index for recent readers of the affected data. The lock acts as a tripwire: it notifies readers that their read may be outdated, rather than blocking.
- 43 notifies 42 and vice versa. 42 commits first and succeeds (43's write has not taken effect). When 43 commits, 42's conflicting write is committed, so 43 aborts.
Performance of serializable snapshot isolation
- Tracking granularity is a trade-off: detailed tracking aborts precisely but costs bookkeeping; coarse tracking is faster but aborts more than necessary.
- Reading overwritten data is sometimes provably still serializable; PostgreSQL uses this theory to cut unnecessary aborts.
- Versus 2PL: no blocking on other transactions' locks; writers do not block readers and vice versa, so latency is more predictable. Read-only queries need no locks, good for read-heavy workloads.
- Versus serial execution: not limited to one core. FoundationDB distributes conflict detection across machines for very high throughput, with serializable multi-partition reads and writes.
- Abort rate drives overall performance. Long read-write transactions likely conflict and abort, so read-write transactions should be short (long read-only ones may be fine). SSI is probably less sensitive to slow transactions than 2PL or serial execution.
| Approach | Style | Strength | Limit |
|---|---|---|---|
| Actual serial execution | Pessimistic (extreme) | Simple; no lock overhead | One core per partition; in-memory; short transactions; ~1,000 cross-partition writes/s in VoltDB |
| Two-phase locking | Pessimistic | Prevents all races (with predicate / index-range locks) | Readers and writers block; unstable high-percentile latency; deadlocks |
| Serializable snapshot isolation | Optimistic | No blocking; scales across machines (FoundationDB) | Aborts under high contention; read-write transactions must be short |
Summary
- Transactions are an abstraction that lets apps pretend some concurrency problems and hardware/software faults do not exist; many errors reduce to an abort and a retry.
- Apps with very simple access patterns (one record) can probably do without; for complex patterns, transactions greatly reduce the error cases to think about.
- Without them, crashes, network cuts, power loss, full disks and unexpected concurrency make data inconsistent (e.g. denormalized data out of sync), and complex interactions become very hard to reason about.
Race conditions that characterize isolation levels:
- Dirty reads: reading uncommitted writes. Prevented by read committed and stronger.
- Dirty writes: overwriting uncommitted writes. Prevented by almost all implementations.
- Read skew (nonrepeatable reads): seeing parts of the database at different times. Usually prevented by snapshot isolation via MVCC.
- Lost updates: concurrent read-modify-write cycles clobber each other. Some snapshot isolation implementations prevent it automatically; others need
SELECT FOR UPDATE. - Write skew: a decision based on a read whose premise is false by write time. Only serializable isolation prevents it.
- Phantom reads: another write changes a search's results. Snapshot isolation prevents simple phantom reads; phantoms in write skew need e.g. index-range locks.
| Anomaly | Read committed | Snapshot isolation | Serializable |
|---|---|---|---|
| Dirty read | prevented | prevented | prevented |
| Dirty write | prevented | prevented | prevented |
| Read skew | possible | prevented | prevented |
| Lost update | possible | depends on implementation | prevented |
| Write skew / phantoms in write skew | possible | possible | prevented |
- Weak levels leave some anomalies to the developer (e.g. explicit locks); only serializable isolation protects against all.
- Serial execution: simple and effective if transactions are very fast and throughput fits one core.
- Two-phase locking: the standard for decades, but many apps avoid it for performance reasons.
- SSI: a fairly new optimistic algorithm that avoids most downsides; transactions proceed without blocking and are checked and aborted at commit if not serializable.
- Examples used the relational model, but transactions are valuable in any data model. Distributed transactions bring new challenges (next two chapters).
Condensed from Designing Data-Intensive Applications by Martin Kleppmann (O'Reilly, 2017). Parts I-III (complete book), 12 chapters.