Skip to main content

Transactions & Isolation Levels

Learning objectives
  • State each ACID property precisely, including what the database does not guarantee
  • Recognize dirty reads, non-repeatable reads, phantoms, lost updates and write skew in a real money flow
  • Explain what Read Committed, Repeatable Read and Serializable mean in Postgres versus MySQL/InnoDB
  • Prevent double-spends and overdrafts with the right mix of isolation level, locking and constraint design
  • Write a correct retry loop for serialization failures in Go

TL;DR​

  • Atomicity means abortability (all or nothing); consistency is your invariants, which the database helps enforce via constraints; isolation is how much concurrent transactions can see of each other; durability means committed data survives a crash, given correct fsync settings.
  • The SQL standard levels are defined by anomalies; real engines implement MVCC snapshots, so their behavior differs from the textbook table. Always ask "which database, which version?"
  • Postgres: default Read Committed (new snapshot per statement); Repeatable Read is snapshot isolation and detects lost updates; Serializable is SSI, which also prevents write skew by aborting transactions with SQLSTATE 40001.
  • MySQL/InnoDB: default Repeatable Read, but locking reads and UPDATE read the latest committed row, so read-then-write in the application can still lose updates. Serializable turns plain reads into shared-lock reads.
  • Write skew (two transactions read the same data, update different rows, and together break an invariant) is the classic bank bug: snapshot isolation allows it.
  • Fixes, from simplest: a single conditional UPDATE, lock the rows you read (FOR UPDATE) or a common parent row, or run Serializable and retry. Retries require idempotent transaction bodies.

Why it matters​

Every money movement is a read-check-write: read the balance, check it covers the amount, write the debit. Under concurrency, the gap between the check and the write is where double-spends live. A wallet that loses one update per million transactions at 2,000 TPS loses money several times per day, and each case is an investigation, a customer complaint, and potentially a regulatory report. On the e-commerce side, the same pattern oversells the last unit of a flash-sale item.

Isolation also has a cost: stronger levels mean more aborts or more blocking, which you pay at peak load. An architect has to choose deliberately, per transaction type, and explain the choice.

Core concepts​

ACID, precisely​

PropertyWhat it actually guaranteesWhat it does not
AtomicityAll writes of a transaction become visible together or not at all; on error or crash, partial work is rolled backAtomicity across two databases or a database plus a message broker (see Distributed Transactions)
ConsistencyTransactions move the database from one valid state to another, as defined by constraints you declared and logic you wroteInvariants you never told the database about
IsolationConcurrent transactions are protected from each other's intermediate state, to the degree the isolation level promisesSerializability, unless you asked for it (and even then, only within one database)
DurabilityOnce commit returns, data survives a process or OS crashSurvival of disk loss without replication or backups; durability if you turned off fsync

Durability knobs that change the guarantee:

  • Postgres synchronous_commit = on (default) waits for the WAL flush; off can lose the last few hundred milliseconds of commits on a crash (no corruption, just lost recent transactions). With synchronous replicas, remote_apply/on also wait for standbys.
  • InnoDB innodb_flush_log_at_trx_commit = 1 (default) flushes the redo log at each commit; 2 writes to the OS cache and flushes about once per second; sync_binlog = 1 makes the binlog equally durable.

For a ledger, keep the safe defaults. Relaxing them is reasonable for derived data you can rebuild.

The anomalies​

Using a wallet table account(id, customer_id, balance_minor):

AnomalyWhat happensMoney example
Dirty writeT2 overwrites a value T1 wrote but has not committedTwo transfers interleave writes on the same row; rollback restores the wrong value
Dirty readT2 reads T1's uncommitted writeA risk check sees a deposit that later rolls back and approves a withdrawal
Non-repeatable readT1 reads a row twice and gets different values because T2 committed in betweenA statement job prints a balance that does not match the sum of entries it read a moment later
PhantomT1 re-runs a range query and sees new rows inserted by T2A daily limit check counts today's transfers, a concurrent transfer is inserted, the count is now stale
Lost updateT1 and T2 both read a value, compute a new value, and write; one write is silently lostTwo payments of 80 from a balance of 100 both succeed; final balance 20 instead of one being declined
Read skewT1 reads part of the data before and part after T2's commitA transfer report sees the debit of a transfer but not its credit
Write skewT1 and T2 read overlapping data, each updates a different row based on what it read, together breaking an invariantCombined balance of two linked accounts must stay non-negative; two withdrawals from different accounts both pass the check

The ANSI SQL-92 definitions only cover dirty reads, non-repeatable reads and phantoms. Berenson et al.'s 1995 critique showed this is incomplete: snapshot isolation prevents all three yet still allows write skew. That gap is why "Repeatable Read" in two products can mean different things.

MVCC and snapshots​

Both Postgres and InnoDB use multi-version concurrency control: writers create new row versions, readers read the version that was committed as of their snapshot, and readers never block writers (or vice versa).

  • Postgres stores versions in the heap. Each tuple has xmin (creating transaction) and xmax (deleting or updating transaction). A snapshot records which transactions were in progress; a tuple is visible if its creator committed before the snapshot and its deleter did not. Old versions are removed by VACUUM (see PostgreSQL Deep Dive).
  • InnoDB updates rows in place in the clustered index and keeps previous versions in the undo log. A read view decides which version a consistent read reconstructs. Purge threads remove undo records no longer needed.

The crucial difference is when a snapshot is taken and which operations use it:

Engine and levelSnapshot for plain SELECTWhat UPDATE/SELECT … FOR UPDATE see
Postgres Read CommittedNew snapshot per statementLatest committed version; if the row changed while waiting for a lock, re-check the WHERE on the new version and proceed
Postgres Repeatable ReadOne snapshot from the first statementSnapshot; if the row was changed by a transaction that committed after the snapshot, fail with 40001
Postgres SerializableOne snapshotSame as RR, plus SSI tracks read/write dependencies and aborts dangerous patterns
InnoDB Read CommittedNew snapshot per statementLatest committed version; gap locks mostly disabled
InnoDB Repeatable ReadOne snapshot from the first consistent readLatest committed version ("current read") with record and next-key locks
InnoDB SerializablePlain SELECT becomes SELECT … FOR SHARE (when not autocommit)Locks, as in RR

Isolation levels in practice​

AnomalyPG RCPG RRPG SerializableMySQL RCMySQL RRMySQL Serializable
Dirty readNoNoNoNoNoNo
Non-repeatable readYesNoNoYesNo (plain reads)No
PhantomYesNoNoYesNo for plain reads; locking reads block inserts with next-key locksNo
Lost update (app read-modify-write)YesNo (40001)NoYesYesNo (deadlock instead)
Write skewYesYesNo (40001)YesYesNo (lock conflicts or deadlock)

Notes:

  • Postgres accepts READ UNCOMMITTED but treats it as Read Committed. MySQL's Read Uncommitted really allows dirty reads; never use it for money.
  • Oracle's SERIALIZABLE is snapshot isolation, so it allows write skew. Distributed SQL databases vary (CockroachDB defaults to serializable; others default to snapshot or read committed). Check the documentation and, ideally, independent tests such as Jepsen reports.
  • A single UPDATE account SET balance_minor = balance_minor - 80 WHERE id = 1 is safe from lost updates at every level in both engines, because the read and the write happen inside one statement on the locked latest version. The lost-update problem appears when the application reads in one statement and writes a computed value in another.

Serializable Snapshot Isolation (Postgres)​

SSI (Postgres 9.1+, based on Cahill, Röhm and Fekete's work) runs transactions on snapshots as in RR, and additionally records SIREAD locks on what each transaction read (rows, index pages, or whole relations). These "locks" never block; they let the engine detect read-write antidependencies: T1 read something T2 later wrote. When two such edges form a dangerous structure (a pivot transaction with both an incoming and an outgoing rw-edge), one transaction is aborted with 40001 could not serialize access due to read/write dependencies among transactions.

Implications:

  • No blocking, but aborts: you must retry the whole transaction.
  • False positives exist: aborts can happen even if the actual interleaving was harmless, especially when predicate locks are coarse (sequential scans lock the whole relation). Good indexes reduce aborts.
  • Every transaction touching the data must run at Serializable for the guarantee to hold.
  • SET TRANSACTION READ ONLY DEFERRABLE lets long reports run serializably without risk of being aborted, at the cost of waiting for a safe snapshot.

Worked example: overdraft through write skew​

A bank lets a customer's checking account go negative as long as checking plus savings stays non-negative. Checking (id 1) holds 60, savings (id 2) holds 40. Two withdrawals arrive at the same moment from different channels: 80 from checking (ATM) and 70 from savings (mobile app). Both run this logic:

  1. SELECT SUM(balance_minor) FROM account WHERE customer_id = 7 → 100
  2. If 100 - amount >= 0, debit the chosen account.

Under Read Committed or Repeatable Read (snapshot isolation) in Postgres, and under Repeatable Read in MySQL, both commit. The invariant is broken without any single row being touched twice.

The simpler double-spend is a lost update on one row: balance 100, two payments of 80 each, both read 100 with a plain SELECT, both write balance = 20. Postgres RR aborts the second writer with 40001; Postgres RC and MySQL RR both lose an update.

Four ways to prevent it​

1. Make the check and the write one atomic statement (when the invariant is on one row):

UPDATE account
SET balance_minor = balance_minor - $2
WHERE id = $1 AND balance_minor >= $2
RETURNING balance_minor;
-- 0 rows returned => insufficient funds

This works at Read Committed in both engines because the WHERE is evaluated against the latest committed version while holding the row lock. For the two-account rule, redesign so the invariant lives on one row, for example a customer_limit(customer_id, available_minor) row that every withdrawal decrements conditionally.

2. Lock what you read (pessimistic):

BEGIN;
SELECT balance_minor FROM account WHERE customer_id = 7 FOR UPDATE; -- locks both rows
-- check in application
UPDATE account SET balance_minor = balance_minor - 80 WHERE id = 1;
COMMIT;

T2's FOR UPDATE waits until T1 commits, then (in Read Committed) sees the new balances and declines. If new accounts can be inserted concurrently, rows that do not exist yet cannot be locked (a phantom); lock a parent row such as customer instead. This is called materializing the conflict. Details in Locking & Concurrency Control.

3. Use Serializable and retry. Run both withdrawals at SERIALIZABLE in Postgres. One fails with 40001; on retry it sees the other's debit and declines. You get correctness without reasoning about every lock, at the cost of retries and the requirement that all participating transactions are serializable.

4. Enforce it as a constraint. Some invariants can be declared (CHECK (balance_minor >= -overdraft_limit_minor) on a single row). Cross-row invariants via triggers still need locking or Serializable to be race-free, because the trigger runs on the transaction's own snapshot.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Read Committed + atomic conditional updatesHighest throughput, no retries, simpleOnly protects invariants expressible on one row per statementBalance debits, stock decrements, idempotency inserts
Read Committed + SELECT … FOR UPDATEExplicit, predictable, works in both enginesBlocking, deadlock risk, must remember to lock every read that mattersMulti-row checks with a clear lock target
Repeatable Read (Postgres)Consistent snapshot, lost updates detectedWrite skew still possible; retries needed on 40001Reports, multi-statement reads, read-modify-write on single rows
Repeatable Read (MySQL default)Consistent plain reads, phantoms blocked for locking readsLost updates possible; gap locks cause surprising blocking and deadlocksDefault OLTP in MySQL, combined with locking reads for money
Serializable (Postgres SSI)Full serializability without reasoning about locksAborts under contention, retries, every transaction must opt inComplex invariants, moderate contention, correctness first
Serializable (MySQL)Serializability via locksReads take shared locks: more blocking and deadlocksRarely; prefer explicit locking

In practice​

  • Pick isolation per transaction type, not globally. A typical bank service runs most work at Read Committed with conditional updates and FOR UPDATE, and uses Serializable for a few complex invariants.
  • Keep transactions short. No HTTP calls, no message publishing, no user think-time inside a transaction. Long transactions hold locks, pin old snapshots (blocking vacuum in Postgres, growing undo history in InnoDB), and increase abort rates.
  • Set guardrails: Postgres idle_in_transaction_session_timeout, statement_timeout, lock_timeout; MySQL innodb_lock_wait_timeout (default 50 s, far too long for an API).
  • Retry only retryable errors: 40001 serialization failure and 40P01 deadlock in Postgres; error 1213 (deadlock) and sometimes 1205 (lock wait timeout) in MySQL. Retry the entire transaction from BEGIN, with backoff and jitter, and a small attempt limit.
  • The body must be safe to repeat. Any side effect outside the database (card network call, email, Kafka publish) must happen after commit, via an outbox (see Transactional Outbox & CDC) and with idempotency keys (see Idempotency & Exactly-Once).

A Go retry wrapper for Postgres with pgx:

package wallet

import (
"context"
"errors"
"fmt"
"math/rand/v2"
"time"

"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)

var ErrInsufficientFunds = errors.New("insufficient funds")

func isRetryable(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && (pgErr.Code == "40001" || pgErr.Code == "40P01")
}

func runTx(ctx context.Context, pool *pgxpool.Pool, opts pgx.TxOptions, fn func(pgx.Tx) error) error {
tx, err := pool.BeginTx(ctx, opts)
if err != nil {
return err
}
defer tx.Rollback(ctx) // no-op after a successful commit

if err := fn(tx); err != nil {
return err
}
return tx.Commit(ctx) // SSI can also fail here with 40001
}

// WithRetry runs fn in a serializable transaction, retrying serialization failures.
func WithRetry(ctx context.Context, pool *pgxpool.Pool, fn func(pgx.Tx) error) error {
const maxAttempts = 5
opts := pgx.TxOptions{IsoLevel: pgx.Serializable}

var err error
for attempt := 1; attempt <= maxAttempts; attempt++ {
if err = runTx(ctx, pool, opts, fn); err == nil || !isRetryable(err) {
return err
}
backoff := time.Duration(attempt*attempt)*5*time.Millisecond + rand.N(5*time.Millisecond)
select {
case <-time.After(backoff):
case <-ctx.Done():
return ctx.Err()
}
}
return fmt.Errorf("giving up after %d attempts: %w", maxAttempts, err)
}

// Withdraw enforces "sum of the customer's balances stays >= 0" under SSI.
func Withdraw(ctx context.Context, pool *pgxpool.Pool, customerID, accountID, amount int64) error {
return WithRetry(ctx, pool, func(tx pgx.Tx) error {
var total int64
err := tx.QueryRow(ctx,
`SELECT COALESCE(SUM(balance_minor), 0)::bigint FROM account WHERE customer_id = $1`,
customerID).Scan(&total)
if err != nil {
return err
}
if total < amount {
return ErrInsufficientFunds
}
_, err = tx.Exec(ctx,
`UPDATE account SET balance_minor = balance_minor - $2 WHERE id = $1 AND customer_id = $3`,
accountID, amount, customerID)
return err
})
}

Measure the abort rate (pg_stat_database.xact_rollback and your own retry counter). If retries exceed a few percent at peak, the contention is structural, and you should redesign (single-row invariant, queueing per account) rather than add attempts.

Common pitfalls​

  • Assuming "Repeatable Read" means the same thing everywhere. Code that is safe on Postgres RR (lost updates detected) loses money on MySQL RR.
  • Read-then-write in application code without a lock. Symptom: rare negative balances or oversold stock that never reproduce in tests.
  • Retrying only the failed statement instead of the whole transaction. The snapshot is gone; the retry runs on inconsistent assumptions.
  • Side effects inside a retried transaction. Symptom: duplicate emails, duplicate card captures after serialization failures.
  • Mixing isolation levels under SSI. One Read Committed writer bypasses the protection for everyone.
  • Long-running transactions. Symptom: Postgres table bloat and vacuum unable to clean up; InnoDB "history list length" growing; lock waits.
  • Believing SELECT inside a transaction is "locked". Plain MVCC reads take no row locks in either engine.
  • Ignoring commit errors. Under SSI, COMMIT itself can fail; code that ignores its error reports success for a rolled-back transfer.

Interview angle​

  • Expect: "Two requests withdraw from the same wallet at the same time. What happens and how do you prevent it?" A strong answer names the anomaly (lost update or write skew), states the database's actual default behavior, and offers the conditional UPDATE first, then locking, then Serializable with retries, with costs.
  • Be precise about vocabulary: "snapshot isolation allows write skew", "Postgres RR is snapshot isolation", "InnoDB RR uses current reads for writes".
  • Follow-ups: "Why not just use Serializable everywhere?" (abort rate, retries, performance under contention), "How do you make retries safe?" (idempotent body, outbox), "What does durability depend on?" (fsync, replication, synchronous_commit).
  • For distributed scenarios, connect to Consistency Models and Distributed Transactions: isolation inside one database does not extend across services.
  • Red flags: "ACID means my data is always correct", "we use transactions so there are no race conditions", not knowing the default isolation level of the database you claim to use.

Self-check​

1. What does the C in ACID really mean, and who is responsible for it?

It means each transaction preserves the application's invariants, moving the database from one valid state to another. The database enforces the invariants you declared (constraints, FKs) and gives you atomicity and isolation as tools; any rule you did not express is the application's responsibility. Kleppmann notes it is the odd one out: a property of the application, not the database.

2. Explain write skew with a non-banking example and say which isolation level prevents it in Postgres.

Two doctors on call each check "at least one other doctor is on call", see yes, and each removes themselves from the rota; both updates touch different rows, so snapshot isolation sees no conflict and nobody is on call. In e-commerce: two admins each disable a different payment method after checking that at least one remains enabled. Postgres prevents it only at SERIALIZABLE (SSI), or with explicit locks that materialize the conflict.

3. Why is UPDATE … SET balance = balance - 80 WHERE id = 1 AND balance >= 80 safe at Read Committed?

The statement locks the row before modifying it. If another transaction changed the row concurrently, the second updater waits for the lock, and then (Postgres) re-evaluates the WHERE against the newly committed version, or (InnoDB) performs a current read of the latest version. The check and the write happen on the same up-to-date version while the lock is held, so no update can be lost and the balance cannot go negative.

4. A service on MySQL reads the balance with SELECT, computes the new balance in Go, and writes it with UPDATE at the default isolation level. What can go wrong and what are two fixes?

MySQL's default Repeatable Read does not detect lost updates: two concurrent requests can read the same balance and each write their computed value, losing one debit. Fixes: read with SELECT … FOR UPDATE so the second request waits and reads the latest value, or replace the read-compute-write with a single conditional UPDATE … WHERE balance >= ?, checking rows affected.

5. What does SSI do that snapshot isolation does not, and what does it cost?

SSI tracks which data each transaction read (SIREAD predicate locks) and detects read-write dependency patterns that could produce a non-serializable outcome, aborting one transaction with 40001. Costs: tracking overhead, aborts (including false positives) that require retrying whole transactions, the need for all relevant transactions to run serializably, and higher abort rates under contention or with sequential scans.

6. Why must external side effects not happen inside a transaction that may be retried?

The transaction may be rolled back and re-run (serialization failure, deadlock, timeout), but the side effect already happened: the email was sent, the card was charged. Record the intent in the database (outbox row) within the transaction and perform side effects after commit with idempotency keys, so retries and redeliveries are harmless.

7. Scenario: a daily transfer limit of 50 million VND is enforced by summing today's transfers before inserting a new one. Which anomaly threatens this and how would you fix it?

Phantom-driven write skew: two concurrent transfers each sum today's rows, each sees room under the limit, and each inserts a new row; the inserts do not conflict. Fixes: lock a per-customer row (SELECT … FROM customer_limit WHERE customer_id = ? FOR UPDATE) before summing; keep a running used_today counter on one row and update it conditionally; or run both transactions at Serializable in Postgres and retry.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Reproduce write skew, then prevent it, with two terminals.

docker run --name pg-tx -e POSTGRES_PASSWORD=pg -p 5432:5432 -d postgres:17
docker exec -it pg-tx psql -U postgres # terminal A
docker exec -it pg-tx psql -U postgres # terminal B
CREATE TABLE account (id bigint PRIMARY KEY, customer_id bigint NOT NULL, balance_minor bigint NOT NULL);
INSERT INTO account VALUES (1, 7, 60), (2, 7, 40);
  1. Write skew at Repeatable Read. In A: BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT SUM(balance_minor) FROM account WHERE customer_id = 7;. In B: the same BEGIN and SELECT, then UPDATE account SET balance_minor = balance_minor - 70 WHERE id = 2; COMMIT;. In A: UPDATE account SET balance_minor = balance_minor - 80 WHERE id = 1; COMMIT;. Check the sum: it is negative.
  2. Reset the balances and repeat with ISOLATION LEVEL SERIALIZABLE. Record which statement fails and the exact error message.
  3. Reset and repeat at Read Committed, but with SELECT … FOR UPDATE in both sessions. Observe B blocking and seeing the updated sum after A commits.
  4. Lost update. With one account at 100, run read-then-write (SELECT, then UPDATE … SET balance_minor = 20) in both sessions at Read Committed, then at Repeatable Read. Compare outcomes.
  5. Optional: run step 4 against mysql:8.4 at its default level and confirm the update is lost.

Done when you have a table of (level, technique, outcome, error code) and can explain every row.

Further reading​

  • Martin Kleppmann, Designing Data-Intensive Applications, ch. 7 "Transactions".
  • Hal Berenson et al., "A Critique of ANSI SQL Isolation Levels" (SIGMOD 1995).
  • Atul Adya, "Weak Consistency: A Generalized Theory and Optimistic Implementations for Distributed Transactions" (PhD thesis, MIT, 1999).
  • Dan R. K. Ports and Kevin Grittner, "Serializable Snapshot Isolation in PostgreSQL" (VLDB 2012).
  • PostgreSQL documentation, "Transaction Isolation": postgresql.org/docs/current/transaction-iso.html.
  • MySQL Reference Manual, "Transaction Isolation Levels" and "Consistent Nonlocking Reads".
  • Martin Kleppmann's Hermitage project (tests of isolation levels across databases): github.com/ept/hermitage.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).