Transactions & Isolation Levels
- 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
UPDATEread 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
| Property | What it actually guarantees | What it does not |
|---|---|---|
| Atomicity | All writes of a transaction become visible together or not at all; on error or crash, partial work is rolled back | Atomicity across two databases or a database plus a message broker (see Distributed Transactions) |
| Consistency | Transactions move the database from one valid state to another, as defined by constraints you declared and logic you wrote | Invariants you never told the database about |
| Isolation | Concurrent transactions are protected from each other's intermediate state, to the degree the isolation level promises | Serializability, unless you asked for it (and even then, only within one database) |
| Durability | Once commit returns, data survives a process or OS crash | Survival 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;offcan lose the last few hundred milliseconds of commits on a crash (no corruption, just lost recent transactions). With synchronous replicas,remote_apply/onalso wait for standbys. - InnoDB
innodb_flush_log_at_trx_commit = 1(default) flushes the redo log at each commit;2writes to the OS cache and flushes about once per second;sync_binlog = 1makes 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):
| Anomaly | What happens | Money example |
|---|---|---|
| Dirty write | T2 overwrites a value T1 wrote but has not committed | Two transfers interleave writes on the same row; rollback restores the wrong value |
| Dirty read | T2 reads T1's uncommitted write | A risk check sees a deposit that later rolls back and approves a withdrawal |
| Non-repeatable read | T1 reads a row twice and gets different values because T2 committed in between | A statement job prints a balance that does not match the sum of entries it read a moment later |
| Phantom | T1 re-runs a range query and sees new rows inserted by T2 | A daily limit check counts today's transfers, a concurrent transfer is inserted, the count is now stale |
| Lost update | T1 and T2 both read a value, compute a new value, and write; one write is silently lost | Two payments of 80 from a balance of 100 both succeed; final balance 20 instead of one being declined |
| Read skew | T1 reads part of the data before and part after T2's commit | A transfer report sees the debit of a transfer but not its credit |
| Write skew | T1 and T2 read overlapping data, each updates a different row based on what it read, together breaking an invariant | Combined 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) andxmax(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 byVACUUM(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 level | Snapshot for plain SELECT | What UPDATE/SELECT … FOR UPDATE see |
|---|---|---|
| Postgres Read Committed | New snapshot per statement | Latest committed version; if the row changed while waiting for a lock, re-check the WHERE on the new version and proceed |
| Postgres Repeatable Read | One snapshot from the first statement | Snapshot; if the row was changed by a transaction that committed after the snapshot, fail with 40001 |
| Postgres Serializable | One snapshot | Same as RR, plus SSI tracks read/write dependencies and aborts dangerous patterns |
| InnoDB Read Committed | New snapshot per statement | Latest committed version; gap locks mostly disabled |
| InnoDB Repeatable Read | One snapshot from the first consistent read | Latest committed version ("current read") with record and next-key locks |
| InnoDB Serializable | Plain SELECT becomes SELECT … FOR SHARE (when not autocommit) | Locks, as in RR |
Isolation levels in practice
| Anomaly | PG RC | PG RR | PG Serializable | MySQL RC | MySQL RR | MySQL Serializable |
|---|---|---|---|---|---|---|
| Dirty read | No | No | No | No | No | No |
| Non-repeatable read | Yes | No | No | Yes | No (plain reads) | No |
| Phantom | Yes | No | No | Yes | No for plain reads; locking reads block inserts with next-key locks | No |
| Lost update (app read-modify-write) | Yes | No (40001) | No | Yes | Yes | No (deadlock instead) |
| Write skew | Yes | Yes | No (40001) | Yes | Yes | No (lock conflicts or deadlock) |
Notes:
- Postgres accepts
READ UNCOMMITTEDbut treats it as Read Committed. MySQL's Read Uncommitted really allows dirty reads; never use it for money. - Oracle's
SERIALIZABLEis 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 = 1is 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 DEFERRABLElets 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:
SELECT SUM(balance_minor) FROM account WHERE customer_id = 7→ 100- 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
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Read Committed + atomic conditional updates | Highest throughput, no retries, simple | Only protects invariants expressible on one row per statement | Balance debits, stock decrements, idempotency inserts |
Read Committed + SELECT … FOR UPDATE | Explicit, predictable, works in both engines | Blocking, deadlock risk, must remember to lock every read that matters | Multi-row checks with a clear lock target |
| Repeatable Read (Postgres) | Consistent snapshot, lost updates detected | Write skew still possible; retries needed on 40001 | Reports, multi-statement reads, read-modify-write on single rows |
| Repeatable Read (MySQL default) | Consistent plain reads, phantoms blocked for locking reads | Lost updates possible; gap locks cause surprising blocking and deadlocks | Default OLTP in MySQL, combined with locking reads for money |
| Serializable (Postgres SSI) | Full serializability without reasoning about locks | Aborts under contention, retries, every transaction must opt in | Complex invariants, moderate contention, correctness first |
| Serializable (MySQL) | Serializability via locks | Reads take shared locks: more blocking and deadlocks | Rarely; 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; MySQLinnodb_lock_wait_timeout(default 50 s, far too long for an API). - Retry only retryable errors:
40001serialization failure and40P01deadlock in Postgres; error 1213 (deadlock) and sometimes 1205 (lock wait timeout) in MySQL. Retry the entire transaction fromBEGIN, 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
SELECTinside a transaction is "locked". Plain MVCC reads take no row locks in either engine. - Ignoring commit errors. Under SSI,
COMMITitself 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
UPDATEfirst, 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.
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);
- 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 sameBEGINandSELECT, thenUPDATE 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. - Reset the balances and repeat with
ISOLATION LEVEL SERIALIZABLE. Record which statement fails and the exact error message. - Reset and repeat at Read Committed, but with
SELECT … FOR UPDATEin both sessions. Observe B blocking and seeing the updated sum after A commits. - Lost update. With one account at 100, run read-then-write (
SELECT, thenUPDATE … SET balance_minor = 20) in both sessions at Read Committed, then at Repeatable Read. Compare outcomes. - Optional: run step 4 against
mysql:8.4at 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.
Related
- Locking & Concurrency Control — the locking tools used to prevent these anomalies.
- PostgreSQL Deep Dive — MVCC tuples, snapshots and vacuum.
- Consistency Models — serializability vs linearizability and weaker models.
- Distributed Transactions: 2PC, TCC, Saga — when one database transaction is not enough.
- Digital Wallet — balance updates at scale.
- Bank Transfer System — end-to-end transfer design.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).