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.
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:
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
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:
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.
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
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:
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.
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)
// Go database/sql: a tx object; all statements must use it (not the db pool)
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil { return err }
defer tx.Rollback() // no-op if already committed
if _, err := tx.ExecContext(ctx, `UPDATE accounts SET balance_cents = balance_cents - $1 WHERE id = $2`, amt, from); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `UPDATE accounts SET balance_cents = balance_cents + $1 WHERE id = $2`, amt, to); err != nil {
return err
}
return tx.Commit()
// Rust sqlx: dropping a Transaction without commit rolls it back (RAII)
let mut tx = pool.begin().await?;
sqlx::query("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE").execute(&mut *tx).await?;
sqlx::query("UPDATE accounts SET balance_cents = balance_cents - $1 WHERE id = $2").bind(amt).bind(from).execute(&mut *tx).await?;
sqlx::query("UPDATE accounts SET balance_cents = balance_cents + $1 WHERE id = $2").bind(amt).bind(to).execute(&mut *tx).await?;
tx.commit().await?;
# psycopg 3: the connection context manager commits on success and rolls back on exception
with psycopg.connect(dsn) as conn:
conn.isolation_level = psycopg.IsolationLevel.SERIALIZABLE
with conn.transaction():
conn.execute("UPDATE accounts SET balance_cents = balance_cents - %s WHERE id = %s", (amt, src))
conn.execute("UPDATE accounts SET balance_cents = balance_cents + %s WHERE id = %s", (amt, dst))
# Elixir Ecto: Repo.transaction (or Ecto.Multi for composable, named steps)
Repo.transaction(fn ->
Repo.update_all(from(a in Account, where: a.id == ^src), inc: [balance_cents: -amt])
Repo.update_all(from(a in Account, where: a.id == ^dst), inc: [balance_cents: amt])
end)
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 txin 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 blockuntil you roll back (or use aSAVEPOINTto 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 |
Write skew, the anomaly snapshot isolation allows (Alan Fekete's classic doctors example):
-- 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:
- 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 DEFERRABLEto 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):
- Growing phase: acquire locks: shared (S) to read, exclusive (X) to write. S is compatible with S, and X conflicts with everything.
- 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:
-- 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:
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:
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:
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_waitstoo). InnoDB'sSHOW ENGINE INNODB STATUSshows the latest deadlock (innodb_print_all_deadlockslogs 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.
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.
func WithSerializableRetry(ctx context.Context, db *sql.DB, fn func(*sql.Tx) error) error {
for attempt := 0; ; attempt++ {
err := func() error {
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil { return err }
defer tx.Rollback()
if err := fn(tx); err != nil { return err }
return tx.Commit() // serialization failures can surface at COMMIT
}()
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && (pgErr.Code == "40001" || pgErr.Code == "40P01") && attempt < 5 {
time.Sleep(time.Duration(rand.IntN(10<<attempt)) * time.Millisecond) // jittered backoff
continue
}
return err
}
}
// Rust + sqlx: inspect the SQLSTATE and loop
loop {
match transfer_tx(&pool, &cmd).await {
Err(sqlx::Error::Database(e)) if matches!(e.code().as_deref(), Some("40001" | "40P01")) && attempts < 5 => {
attempts += 1;
tokio::time::sleep(jittered_backoff(attempts)).await;
}
other => break other,
}
}
# Python: tenacity retrying on psycopg serialization and deadlock errors
@retry(retry=retry_if_exception_type((errors.SerializationFailure, errors.DeadlockDetected)),
wait=wait_random_exponential(multiplier=0.01, max=0.5), stop=stop_after_attempt(5))
def transfer(conn, src, dst, amt):
with conn.transaction():
…
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
- Default (read committed) is fine for single-statement operations and reads that don't need a consistent multi-statement view.
- Single-row read-modify-write: use an atomic
UPDATE, orSELECT … FOR UPDATE, or optimistic versioning. Read committed allows lost updates if you read and write separately in application code. - Consistent multi-statement reads (reports, exports): REPEATABLE READ (a snapshot), ideally
READ ONLY, on a replica. - 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
shiftrow before modifying its doctors). - 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:
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,))
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:
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.
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:
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
- Fix experiment 1 at Read Committed using
SELECT … FOR UPDATEon all on-duty rows. How does the second transaction behave now? - Re-run experiment 2 with the atomic
UPDATE stock SET qty = qty - 1at Read Committed and compare throughput and retries. - Reproduce experiment 3 with three accounts in a cycle, and then fix it with ordered locking.
- Use
pg_locksjoined topg_stat_activity(orpg_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_timeoutandstatement_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); anALTER TABLEwaiting 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.