DatabasesVol. 4 · Part IV
0 / 0

Shelves / Databases

DB·59

Transactions and Concurrency Control

What ACID really promises, isolation levels and the anomalies they allow (dirty reads, non-repeatable reads, phantoms, lost updates, read skew, write skew), and how engines implement them: MVCC snapshots, snapshot isolation, serializable snapshot isolation, two-phase locking, gap and next-key locks. Also row and table locks, SELECT FOR UPDATE and SKIP LOCKED, advisory locks, deadlocks, optimistic versus pessimistic concurrency, and retry loops for serialization failures in Java, Go, Rust and Python. PostgreSQL, MySQL/InnoDB, SQL Server and Oracle are compared.

27 topics · ~27 min read · 31-question quiz
Updated Suggest a correction

Start here: many users, one truth

Transactions: all or nothing

A transaction groups statements so that they succeed or fail as one. Moving ₹300 from Asha's account to the café's is two updates; if the second step can't happen, the first must be undone:

Python
with conn.transaction():
    conn.execute("UPDATE acct SET balance = balance - 300 WHERE name = 'asha'")
    conn.execute("UPDATE acct SET balance = balance + 300 WHERE name = 'cafe'")
    raise RuntimeError("payment gateway timeout")          # something fails before commit
Text
1) transfer failed half-way and rolled back: [('asha', 1000), ('cafe', 0)]

That's atomicity. The harder problem is isolation: what each transaction sees and may do while others run at the same time. Running every transaction one after another would be perfectly safe and hopelessly slow, so databases run them concurrently and offer isolation levels that trade strictness for concurrency.

What does the other session see?

Session B reads Asha's balance; A changes it, then commits; B reads again within the same transaction:

Text
READ COMMITTED : B reads 1000, A updates to 700 → B reads 1000 (uncommitted change invisible), A commits → B reads 700
REPEATABLE READ: B reads 1000, A updates to 700 → B reads 1000 (uncommitted change invisible), A commits → B reads 1000

At every level PostgreSQL offers, B never sees A's uncommitted change (no "dirty reads"). The difference is what happens after A commits. Read Committed (PostgreSQL's default) takes a fresh snapshot for each statement, so B's second read sees the new value: the same query returned different answers in one transaction (a non-repeatable read). Repeatable Read takes one snapshot for the whole transaction, so B keeps seeing the world as it was when it started. Both are MVCC at work (chapter 57): old row versions serve old snapshots.

The lost update

The most common concurrency bug in applications: two requests read a balance, compute in code, and write back.

Python
va = a.execute("SELECT balance …").fetchone()[0]          # A reads 1000
vb = b.execute("SELECT balance …").fetchone()[0]          # B reads 1000
a.execute("UPDATE acct SET balance = %s …", (va - 100,)); a.commit()    # Asha spends ₹100
b.execute("UPDATE acct SET balance = %s …", (vb - 200,)); b.commit()    # and, at the same moment, ₹200
Text
READ COMMITTED : two spends of 100 and 200 from 1000 → balance 800 | B's write overwrote A's
REPEATABLE READ: two spends of 100 and 200 from 1000 → balance 900 | B failed: could not serialize access due to concurrent update

Under Read Committed, B's write silently replaced A's: ₹300 was spent and only ₹200 deducted. Under Repeatable Read, PostgreSQL noticed that B was updating a row changed since B's snapshot and refused with a serialization failure; the application must retry B's transaction, which will then read 900 and correctly end at 700. The simplest fix at any level is to not compute in the application at all:

Text
UPDATE acct SET balance = balance - 100 …   (A)
UPDATE acct SET balance = balance - 200 …   (B, waits for A's row lock)
4) atomic UPDATE balance = balance - x: B is waiting for A's row lock: True
   after both commit: 700

Writers to the same row lock it until commit, so B waited, then applied its change to A's committed result. Other options are SELECT … FOR UPDATE (lock the row when reading it) and optimistic version checks (Volume 3 chapter 49).

The levels

Level Snapshot Prevents Allows PostgreSQL notes
Read Uncommitted (as Read Committed) — — Treated as Read Committed
Read Committed Per statement Dirty reads Non-repeatable reads, lost updates in read-then-write code, write skew The default
Repeatable Read Per transaction Above, plus non-repeatable reads, phantoms, lost updates (by failing) Write skew Implemented as snapshot isolation
Serializable Per transaction + conflict tracking Every anomaly: results equal some serial order Nothing (but transactions may fail and need retry) Serializable Snapshot Isolation (SSI)

The lab shows the anomaly that only Serializable catches, write skew: two cooks each check "is someone else on duty?" and both go home.

How deep to go in transactions

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain ACID, transactions and isolation levels
L2 Use transactions, choose isolation levels, write atomic updates and handle retries
L3 Explain anomalies (dirty, non-repeatable, phantom, lost update, write skew), MVCC snapshots, 2PL, SSI, lock modes
L4 Diagnose lost updates, deadlocks, lock queues, serialization failure storms and long transactions
L5 Design concurrency control for a domain (optimistic vs pessimistic, constraints, queues)
L6 Set transaction and migration practices (timeouts, retries, safe DDL) across services

ACID

What a transaction is

A transaction groups operations into one logical unit of work: transfer money (debit one account, credit another), place an order (insert order, insert lines, decrement stock). Either all of it happens or none of it does, and concurrent transactions don't see each other's half-finished work.

SQL
BEGIN;
UPDATE accounts SET balance_cents = balance_cents - 5000 WHERE id = 1;
UPDATE accounts SET balance_cents = balance_cents + 5000 WHERE id = 2;
INSERT INTO transfers (from_id, to_id, amount_cents) VALUES (1, 2, 5000);
COMMIT;            -- or ROLLBACK; on any error

ACID, the guarantees:

Property Meaning Mechanism
Atomicity All or nothing. A failure (an error, a crash, ROLLBACK) leaves no partial effects Undo logs (InnoDB, Oracle, SQL Server), or MVCC visibility plus never-overwrite (PostgreSQL: aborted versions are invisible), and WAL for crash recovery
Consistency A transaction takes the database from one valid state to another: constraints (PK, FK, unique, check) hold at commit Constraint checking. Application invariants that constraints can't express are the application's job, which depends on isolation
Isolation Concurrent transactions don't interfere. Ideally the result is as if they ran one after another (serially) Locking and/or MVCC, at a configurable isolation level
Durability Once committed, data survives crashes and power loss WAL flushed at commit (chapter 58), plus replication and backups for media loss

Atomicity is not about concurrency. It's about failure: a crash halfway through doesn't leave half a transfer. Isolation is the concurrency property, and the most misunderstood, because the default isolation levels of most databases are weaker than serializable.

Consistency in ACID means something different from "consistency" in distributed systems (the C of CAP, which is linearizability, Vol. 5). Martin Kleppmann notes the C was arguably added to make the acronym work, since it's mostly a property of the application.

Transaction boundaries in code

Every language's database API exposes the same primitives: begin, commit, rollback, and a way to set the isolation level.

// Plain JDBC
try (Connection c = ds.getConnection()) {
    c.setAutoCommit(false);                                     // JDBC is auto-commit by default: every statement is its own transaction
    c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
    try {
        transfer(c, 1, 2, 5000);
        c.commit();
    } catch (SQLException e) {
        c.rollback();
        throw e;
    }
}
// Spring: @Transactional(isolation = Isolation.SERIALIZABLE) on a service method (Vol. 3 ch. 49)

Rules that apply everywhere:

  • Keep transactions short: no user think-time and no remote calls inside them (Vol. 3 ch. 49). Locks and old snapshots are held for the whole duration.
  • All statements of a transaction must use the same connection (Go's tx, Spring's thread-bound connection, an explicit &mut tx in Rust).
  • Handle errors by rolling back. In PostgreSQL, after any error the transaction is aborted: every further statement fails with current transaction is aborted, commands ignored until end of transaction block until you roll back (or use a SAVEPOINT to recover part of it).

Isolation levels

The anomalies

Isolation levels are defined by which anomalies (read phenomena) they permit. Each can be shown with two concurrent transactions T1 and T2:

Anomaly What happens Example
Dirty read T1 reads T2's uncommitted change; T2 then rolls back T1 sees a balance that never existed
Dirty write T1 overwrites T2's uncommitted change Interleaved writes leave a mix of both. Prevented at every practical level
Non-repeatable read (fuzzy read) T1 reads a row twice; T2 updates and commits in between; T1 sees different values A report sums an account twice and gets different numbers
Phantom read T1 runs a query twice; T2 inserts or deletes matching rows in between; the set of rows changes SELECT count(*) … WHERE status='PENDING' changes between two reads
Read skew T1 reads related data at two different moments and sees an inconsistent combination Reading account A before a transfer and account B after it: the total seems to be missing money
Lost update T1 and T2 both read, modify and write the same value; one write overwrites the other Two counter = read + 1 operations produce +1 instead of +2
Write skew T1 and T2 read an overlapping set, make disjoint writes based on what they read, and together violate an invariant neither violated alone The on-call example below
time → T1 read stock = 10 write 10 − 3 = 7 commit T2 read stock = 10 write 10 − 4 = 6 commit final stock = 6 (should be 3): T1's sale is lost fixes: atomic UPDATE stock = stock − 4 · SELECT … FOR UPDATE version column · PostgreSQL RR/SERIALIZABLE aborts T2 (MySQL REPEATABLE READ does not)
The lost update anomaly. Both transactions read stock 10, each subtracts its quantity in application code, and the later write overwrites the earlier one, so one sale disappears.

Write skew, the anomaly snapshot isolation allows (Alan Fekete's classic doctors example):

SQL
-- Invariant: at least one doctor must be on call. Alice and Bob are both on call.
-- T1 (Alice)                                        -- T2 (Bob), concurrently
BEGIN ISOLATION LEVEL REPEATABLE READ;               BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM on_call WHERE shift = 7;  -- 2  SELECT count(*) FROM on_call WHERE shift = 7;  -- 2
-- "2 ≥ 2, so I can leave"                           -- "2 ≥ 2, so I can leave"
DELETE FROM on_call WHERE shift=7 AND doc='alice';   DELETE FROM on_call WHERE shift=7 AND doc='bob';
COMMIT;                                              COMMIT;
-- Both commit under snapshot isolation (they wrote DIFFERENT rows). Nobody is on call.
-- SERIALIZABLE (PostgreSQL SSI) aborts one of them; or lock the rows read with SELECT … FOR UPDATE.

Other write-skew shapes: double-booking a meeting room ("check no overlap, then insert"; exclusion constraints in chapter 55 fix it at the schema level), usernames claimed concurrently (unique constraints fix that), and overspending a budget across several rows.

The standard levels

The SQL standard defines four levels by which phenomena they prevent. Real engines differ in important ways:

Level Dirty read Non-repeatable read Phantom Lost update Write skew
Read uncommitted Possible (standard); PostgreSQL treats it as Read committed Possible Possible Possible Possible
Read committed (default in PostgreSQL, Oracle, SQL Server) No Possible Possible Possible Possible
Repeatable read (default in MySQL InnoDB) No No Standard: possible. PostgreSQL: no (snapshot). InnoDB: no for plain reads PostgreSQL: prevented (aborts). InnoDB: possible Possible
Serializable No No No No No

How each engine implements them:

Engine Read committed Repeatable read Serializable
PostgreSQL New MVCC snapshot per statement Snapshot isolation (one snapshot per transaction). Concurrent update of the same row → ERROR: could not serialize access due to concurrent update (SQLSTATE 40001) SSI (serializable snapshot isolation, since 9.1): snapshot isolation plus tracking of read/write dependencies. Aborts transactions that could form a non-serializable cycle
MySQL InnoDB Per-statement consistent reads (MVCC) Per-transaction snapshot for plain SELECTs, but locking reads and writes see the latest committed data and use next-key (gap) locks against phantoms. That's a hybrid: lost updates are possible with read-then-write in the application Turns plain SELECTs into SELECT … FOR SHARE (strict two-phase locking): correct but more blocking and deadlocks
SQL Server Locking (shared locks held only while reading) by default; RCSI (read committed snapshot) optional, which is MVCC with row versions Locks held until commit Range locks (2PL). Separately, SNAPSHOT isolation (SI)
Oracle Per-statement snapshot from undo — (not offered) "Serializable" is actually snapshot isolation (write skew possible)

The lesson: "repeatable read" means different things in different databases, and the defaults (read committed) allow lost updates and write skew. Know your engine, and choose isolation per transaction based on the invariants at stake.

Implementation mechanisms

MVCC

Multi-version concurrency control keeps several versions of each row, so readers don't block writers and writers don't block readers:

version A: balance 500xmin 100 (committed) · xmax 205 version B: balance 300xmin 205 · xmax — T200's snapshot (205 in progress)sees version A → 500 T210's snapshot (205 committed)sees version B → 300 snapshot = {committed horizon, in-progress XIDs} at start A version is visible if its creator committed before the snapshot and its deleter (xmax) did not. old versions linger until unneeded → VACUUM / undo purge
MVCC snapshot visibility. Each row version records the transaction that created it and the one that deleted it; a snapshot sees exactly the versions created by transactions committed before it started and not deleted by such transactions.
  • Each transaction or statement gets a snapshot: which transactions had committed when it started.
  • Reads return, for each row, the newest version visible to that snapshot. No read locks are needed.
  • Writers still conflict with writers on the same row. The second writer waits for the first to commit or abort, then (depending on the level) re-evaluates (read committed) or fails (repeatable read and serializable in PostgreSQL).
  • Storage of versions differs: in the table (PostgreSQL: VACUUM cleans up), in undo logs (InnoDB, Oracle: purge cleans up), or in tempdb / a version store (SQL Server).

Snapshot isolation (SI), each transaction reading from one consistent snapshot, prevents dirty reads, non-repeatable reads, read skew and (with first-updater-wins) lost updates. But it allows write skew, because two transactions can each read a state, write different rows, and both commit.

Serializable snapshot isolation (SSI), from Cahill, Röhm and Fekete (2008), used in PostgreSQL's SERIALIZABLE: keep SI's non-blocking reads, but track read-write dependencies (rw-antidependencies: T1 read something T2 later wrote). If the dependency graph could contain a dangerous structure (two consecutive rw-edges in a potential cycle), abort one transaction with SQLSTATE 40001 could not serialize access due to read/write dependencies among transactions. Properties:

  • No blocking reads, unlike two-phase locking, so throughput stays high.
  • False positives: some aborted transactions would actually have been fine. That's the price of tracking dependencies at page or relation granularity under memory pressure.
  • Applications must retry serialization failures, which is mandatory at this level.
  • Read-only transactions can be declared READ ONLY DEFERRABLE to wait for a safe snapshot and then never abort.

CockroachDB runs serializable by default (and offers read committed as an option since 2023), and Google Spanner provides strict serializability. Distributed SQL systems made serializable-by-default practical, which shows the cost is often lower than people assume.

Two-phase locking

The classic way to achieve serializability is two-phase locking (2PL):

  1. Growing phase: acquire locks: shared (S) to read, exclusive (X) to write. S is compatible with S, and X conflicts with everything.
  2. Shrinking phase: release locks. Strict 2PL holds all locks until commit or abort.

Readers block writers and writers block readers. 2PL prevents all anomalies, including phantoms, if you also lock ranges (predicate or index-range locks). Costs: blocking, lower concurrency, and deadlocks. SQL Server's default (non-RCSI) mode and InnoDB's SERIALIZABLE work this way.

InnoDB's gap and next-key locks protect ranges in an index: a record lock locks an index entry, a gap lock locks the gap between entries (preventing inserts there), and a next-key lock combines the two (a record plus the gap before it). They prevent phantoms for locking reads and writes, but they surprise people:

SQL
-- InnoDB, REPEATABLE READ: this locks the matching rows AND the gaps around them in the index used
SELECT * FROM orders WHERE customer_id BETWEEN 100 AND 200 FOR UPDATE;
-- Concurrent INSERT of customer_id 150 now BLOCKS, even though no row with 150 existed.
-- Without a suitable index, the scan locks... every row and gap it scans (effectively the table).

Locks in practice

Row locks: FOR UPDATE, FOR SHARE, NOWAIT, SKIP LOCKED

Explicit row locking is the tool for pessimistic concurrency:

SQL
BEGIN;
SELECT qty FROM inventory WHERE sku = 'A1' FOR UPDATE;    -- lock the row: other writers and FOR UPDATE readers wait
-- … decide in application code …
UPDATE inventory SET qty = qty - 4 WHERE sku = 'A1';
COMMIT;

-- Variants (PostgreSQL)
SELECT … FOR UPDATE NOWAIT;          -- error immediately if locked (55P03) instead of waiting
SELECT … FOR UPDATE SKIP LOCKED;     -- skip rows locked by others: the basis of DB-backed job queues
SELECT … FOR NO KEY UPDATE;          -- weaker: doesn't block FK checks from child inserts (UPDATE uses this by default)
SELECT … FOR SHARE;                  -- others may also share-lock; blocks writers
SELECT … FOR KEY SHARE;              -- what FK checks take: only blocks key changes and deletes

-- Work queue: many workers claim jobs without contention
WITH next AS (
    SELECT id FROM jobs WHERE status = 'READY' AND run_at <= now()
    ORDER BY priority DESC, id
    FOR UPDATE SKIP LOCKED
    LIMIT 10
)
UPDATE jobs j SET status = 'RUNNING', locked_by = $1, locked_at = now()
FROM next WHERE j.id = next.id
RETURNING j.*;

PostgreSQL stores row locks in the tuple header (xmax plus infomask bits, with a "multixact" structure when several transactions share-lock a row), so locking millions of rows uses no lock-table memory, but it does dirty the pages. InnoDB keeps row locks in an in-memory lock system attached to index records. SQL Server keeps a lock table, with lock escalation (many row locks become a table lock), which can cause surprise blocking. Oracle stores locks in the block, like PostgreSQL.

Table locks and DDL

Every statement takes a table-level lock too, normally a weak one that conflicts only with schema changes:

PostgreSQL lock mode Taken by Conflicts with (notably)
ACCESS SHARE SELECT Only ACCESS EXCLUSIVE
ROW EXCLUSIVE INSERT/UPDATE/DELETE SHARE and stronger
SHARE UPDATE EXCLUSIVE VACUUM, CREATE INDEX CONCURRENTLY, ANALYZE Itself (one at a time)
SHARE CREATE INDEX (non-concurrent) Writes
ACCESS EXCLUSIVE Most ALTER TABLE, DROP, TRUNCATE, VACUUM FULL Everything, including SELECT

The DDL lock-queue trap: an ALTER TABLE needing ACCESS EXCLUSIVE waits behind one long-running SELECT, and every new query on that table queues behind the waiting ALTER. A one-second migration becomes a full outage. Defence: run DDL with a short lock_timeout (SET lock_timeout = '2s') and retry, kill or avoid long transactions during migrations, and prefer online operations (CONCURRENTLY, NOT VALID, adding nullable columns or constant defaults, which are metadata-only). Online schema change tools exist for other engines: gh-ost and pt-online-schema-change for MySQL (InnoDB's online DDL covers many cases), and online index operations in SQL Server Enterprise.

Advisory locks

Advisory locks are application-defined locks on arbitrary numbers. The database only arbitrates them:

SQL
SELECT pg_try_advisory_lock(hashtext('nightly-report'));     -- session-level: true if acquired
SELECT pg_advisory_xact_lock(42);                            -- transaction-level: released at commit or rollback

Uses: ensuring one instance runs a job (an alternative to ShedLock tables, Vol. 3 ch. 51), serialising work per entity (pg_advisory_xact_lock(account_id)), and migration tools that prevent concurrent runs (Flyway and Liquibase use locks for this). Caveat: session-level advisory locks don't work through transaction-mode poolers (the session may change between transactions), so use transaction-level locks there. MySQL has GET_LOCK(), SQL Server sp_getapplock, and Oracle DBMS_LOCK.

Deadlocks

A deadlock happens when transactions wait for each other's locks in a cycle (Vol. 3 ch. 38 covers the concept). Databases detect cycles and abort one victim:

Text
T1: UPDATE accounts … WHERE id = 1;   (locks row 1)
T2: UPDATE accounts … WHERE id = 2;   (locks row 2)
T1: UPDATE accounts … WHERE id = 2;   (waits for T2)
T2: UPDATE accounts … WHERE id = 1;   (waits for T1) → cycle
PostgreSQL (after deadlock_timeout, 1 s by default): ERROR: deadlock detected (SQLSTATE 40P01) for one of them

Prevention and handling:

  • Lock in a consistent order: update accounts in ascending ID order (ORDER BY id … FOR UPDATE, then update). Bulk updates should also touch rows in a deterministic order.
  • Keep transactions short and avoid user interaction inside them.
  • Index foreign keys and lookup columns, so statements lock only the rows they need, not scanned ranges (especially in InnoDB, where scans take next-key locks).
  • Retry the victim transaction: deadlocks are an expected, retryable condition, like serialization failures.
  • Diagnose: PostgreSQL logs both statements (log_lock_waits too). InnoDB's SHOW ENGINE INNODB STATUS shows the latest deadlock (innodb_print_all_deadlocks logs all of them). SQL Server has deadlock graphs in Extended Events.

Optimistic versus pessimistic concurrency

Pessimistic Optimistic
Assumption Conflicts are likely, so prevent them Conflicts are rare, so detect them at write time
Mechanism Locks (SELECT … FOR UPDATE, 2PL) Version columns or timestamps checked on write (UPDATE … WHERE id = ? AND version = ?), compare-and-set, or SSI aborts
Under contention Blocking, queueing, possible deadlocks; throughput degrades gracefully Retries: wasted work grows with contention and can livelock without backoff
Spanning user think-time Impossible (you can't hold a lock while a user edits a form for 10 minutes) Natural: carry the version to the client (an ETag, Vol. 3 ch. 45), check it on save
Best for Short, high-contention critical sections (inventory counters, seat allocation, queue claiming) Low-contention entities, long edit sessions, distributed systems

There's often a third option that needs neither: make the operation atomic in one statement.

SQL
UPDATE inventory SET qty = qty - 4 WHERE sku = 'A1' AND qty >= 4;   -- check and act atomically; 0 rows → insufficient stock
UPDATE counters SET n = n + 1 WHERE id = $1 RETURNING n;            -- no lost update at any isolation level
INSERT … ON CONFLICT DO NOTHING / DO UPDATE;                        -- race-free upsert

Retry loops

Serializable and repeatable-read transactions, deadlock victims and optimistic-lock failures all produce retryable errors. Retry the whole transaction, re-reading the data, not just the failed statement:

SQLSTATE Meaning Retry?
40001 serialization_failure (PostgreSQL RR/SERIALIZABLE, CockroachDB, SQL Server snapshot conflicts map similarly) Yes
40P01 deadlock_detected (PostgreSQL); MySQL error 1213 Yes
55P03 lock_not_available (NOWAIT, lock_timeout) Usually, with backoff
23505 unique_violation Usually not. It's a business result (or the idempotency signal)
// Spring: retry the whole @Transactional method from OUTSIDE the transaction (Vol. 3 ch. 52)
@Retryable(includes = { CannotAcquireLockException.class, PessimisticLockingFailureException.class,
                        ConcurrencyFailureException.class }, maxRetries = 4, delay = 20, multiplier = 2, jitter = 10)
public Receipt transfer(TransferCommand cmd) { return txTemplate.execute(s -> doTransfer(cmd)); }
// Spring translates SQLSTATE 40001/40P01 to subclasses of ConcurrencyFailureException / PessimisticLockingFailureException.

Retrying requires that the transaction body be free of external side effects (no emails sent or HTTP calls made inside it), or that they be idempotent. Use the outbox pattern (Vol. 3 ch. 51) for effects that must follow a commit.

Choosing an isolation strategy

  1. Default (read committed) is fine for single-statement operations and reads that don't need a consistent multi-statement view.
  2. Single-row read-modify-write: use an atomic UPDATE, or SELECT … FOR UPDATE, or optimistic versioning. Read committed allows lost updates if you read and write separately in application code.
  3. Consistent multi-statement reads (reports, exports): REPEATABLE READ (a snapshot), ideally READ ONLY, on a replica.
  4. Invariants across rows ("at least one on call", "no overlapping bookings", "budget not exceeded"): SERIALIZABLE with retries, or constraints (unique, exclusion) that make the invariant structural, or explicit locks on a parent row that serialises the decision (lock the shift row before modifying its doctors).
  5. Distributed SQL (CockroachDB, Spanner): serializable is typically the default. Design for retries from day one.

Lab: concurrency anomalies and lock trouble

PostgreSQL 16, with sessions driven from Python so interleavings are exact; experiment 2 uses 8 concurrent threads.

Experiment 1: write skew

Rule: at least one cook must stay on duty. Ravi and Meena are both on duty; each, in their own transaction, checks how many cooks are on duty and, seeing two, signs off:

Python
n = conn.execute("SELECT count(*) FROM shift WHERE on_duty").fetchone()[0]
if n >= 2: conn.execute("UPDATE shift SET on_duty = false WHERE cook = %s", (me,))
Text
READ COMMITTED : ravi committed, meena committed → cooks on duty: 0
REPEATABLE READ: ravi committed, meena committed → cooks on duty: 0
SERIALIZABLE   : ravi committed, meena got a serialization failure → cooks on duty: 1

Neither transaction changed a row the other changed, so row locks and Repeatable Read's update check had nothing to catch: each decision was based on a snapshot the other made false. This is write skew, and it breaks any rule spanning several rows (at least one on duty, no double-booked tables, total withdrawals within a limit). Serializable (SSI) tracks which rows each transaction read and detects the dangerous read-write cycle, aborting one transaction. Alternatives below Serializable: lock what you read (SELECT … FOR UPDATE on both rows), or turn the rule into a constraint the database enforces (an exclusion constraint for bookings).

Experiment 2: the cost of Serializable

Eight clients each place 300 orders that read a dish's stock and write it back (the read-then-write pattern) at Serializable, retrying on failure:

Text
over 1000 dishes: retries  217 (8% of attempts),  stock decremented 2400 (expected 2400), 0.9 s
over   10 dishes: retries  981 (29% of attempts), stock decremented 2400 (expected 2400), 1.6 s

Every order was counted exactly once in both runs: Serializable plus retries is correct. The cost is aborted work, rising with contention: 29% of attempts failed when everyone fought over 10 dishes. Even with 1,000 dishes and little real conflict, 8% failed, because SSI tracks reads at page granularity once many rows are involved, producing some false positives. Serializable is a good default for complex business logic if every transaction is wrapped in a retry loop and kept short; for hot counters, an atomic UPDATE … SET qty = qty - 1 avoids conflicts entirely.

Experiment 3: a deadlock

Two transfers in opposite directions: A locks Asha's row then wants Ravi's; B locks Ravi's then wants Asha's.

Text
A (asha→ravi): DeadlockDetected after 1001 ms | B (ravi→asha): committed after 901 ms | deadlock_timeout = 1s

Each waited for a lock the other held. PostgreSQL checks for cycles after a lock wait reaches deadlock_timeout (1 s by default), then aborts one transaction so the other can proceed. Deadlocks aren't data corruption, but each costs a second of blocked transactions and an error to retry. Prevent them by locking rows in a consistent order (always the lower account id first: SELECT … WHERE name IN (…) ORDER BY name FOR UPDATE), keeping transactions short, and retrying 40P01 errors.

Experiment 4: a migration that stops the world

A report holds a transaction open on menu (it ran one SELECT and is still going). A deployment runs ALTER TABLE menu ADD COLUMN veg boolean. Five ordinary reads arrive while it waits:

Text
ALTER TABLE queued behind a 2.3 s report transaction: migration waited 2309 ms;
5 simple SELECTs arriving meanwhile waited 2001–2004 ms
with lock_timeout = 100ms the migration gave up after 101 ms (canceling statement due to lock timeout), so readers were never blocked

ALTER TABLE needs an ACCESS EXCLUSIVE lock, which conflicts with the report's lock, so it queued. Lock requests are granted in order, and the simple SELECTs (which only need ACCESS SHARE, compatible with the report) queued behind the waiting ALTER. Adding a column is instant once it has the lock, yet the whole table was unreadable for as long as the report ran; with a 30-minute report, that's a 30-minute outage caused by a "zero-downtime" migration. Always set lock_timeout (a few seconds at most) for migrations and retry, keep application transactions short, and kill long idle transactions before deploying.

Try it yourself

  1. Fix experiment 1 at Read Committed using SELECT … FOR UPDATE on all on-duty rows. How does the second transaction behave now?
  2. Re-run experiment 2 with the atomic UPDATE stock SET qty = qty - 1 at Read Committed and compare throughput and retries.
  3. Reproduce experiment 3 with three accounts in a cycle, and then fix it with ordered locking.
  4. Use pg_locks joined to pg_stat_activity (or pg_blocking_pids()) during experiment 4 to print the waiting chain.

Revision sheet: transactions and concurrency control

Key ideas

  • ACID: atomicity (all or nothing, via WAL/undo), consistency (constraints), isolation (concurrency control), durability (flushed log).
  • Anomalies: dirty read, non-repeatable read, phantom, lost update, read skew, write skew, serialization anomalies.
  • Levels: Read Committed (snapshot per statement; PostgreSQL default), Repeatable Read (snapshot isolation; detects write-write conflicts), Serializable (SSI; detects read-write dependency cycles); MySQL InnoDB defaults to Repeatable Read with gap locks.
  • Mechanisms: two-phase locking, MVCC snapshots, first-committer/updater-wins, SSI predicate (SIREAD) locks, optimistic concurrency with version columns.
  • Locks: row locks (FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, SKIP LOCKED, NOWAIT), table lock modes (ACCESS SHARE … ACCESS EXCLUSIVE), lock queues, advisory locks, deadlock detection.
  • Practice: atomic updates, consistent lock ordering, short transactions, retries for 40001/40P01, lock_timeout and statement_timeout, idle_in_transaction_session_timeout, safe migrations.
  • Distributed transactions: two-phase commit, sagas (Volume 5).

Numbers to remember

  • Lab: write skew left zero cooks on duty at Read Committed and Repeatable Read, one at Serializable; Serializable retried 8–29% of attempts depending on contention; a deadlock cost about deadlock_timeout (1 s); an ALTER TABLE waiting behind a 2.3 s transaction blocked all readers for 2 s.
  • SQLSTATE: 40001 serialization failure, 40P01 deadlock, 55P03 lock not available.

Pitfalls

  • Read-modify-write in application code without locks or versions.
  • Assuming Repeatable Read prevents write skew.
  • Serializable without retry loops; long transactions under Serializable.
  • Inconsistent lock order; user interaction or remote calls inside transactions.
  • Migrations without lock_timeout; long-running reports on the primary during deploys.

Glossary

  • Snapshot: the set of committed transactions a statement or transaction can see.
  • Write skew: two transactions read overlapping data and write disjoint rows, jointly violating a rule.
  • Serialization failure: an abort raised to preserve the isolation guarantee.
  • Deadlock: a cycle of transactions waiting for each other's locks.
  • Lock queue: waiting lock requests, granted in order.
  • SSI: serializable snapshot isolation.