Skip to main content

ACID and Isolation Levels

1. Executive Summary​

ACID—Atomicity, Consistency, Isolation, and Durability—is the foundational contract between application developers and transactional storage systems. Atomicity ensures a transaction's effects are all-or-nothing. Consistency (in the database sense) means each transaction preserves application-defined integrity constraints when executed alone. Isolation governs how concurrent transactions' intermediate states are visible to one another. Durability guarantees committed data survives process crashes and media failures within the system's stated recovery model.

Isolation levels are standardized (primarily via SQL and the ANSI SQL isolation definitions, with known ambiguities) as a ladder from weak to strong: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and SERIALIZABLE. Each level prevents specific anomalies: dirty reads, non-repeatable reads, phantoms, and serialization anomalies. Serializability is the gold standard for isolation: the concurrent execution must be equivalent to some serial order of transactions.

This chapter covers ACID semantics, isolation level definitions, anomaly catalogs, the difference between pessimistic locking and multi-version concurrency control (MVCC), how production databases map SQL isolation names to actual behavior, failure modes when isolation is mis-specified, and principal-level interview framing. Understanding ACID and isolation is prerequisite to MVCC, distributed transactions, sagas, and the transactional outbox pattern.

2. Why This Topic Matters​

Principal architect interviews use transactions as a correctness precision test:

  • Can you define each ACID property without conflating database "consistency" with CAP consistency?
  • Can you name which anomalies each isolation level prevents—and which it does not?
  • Do you know that REPEATABLE READ in PostgreSQL prevents phantoms but REPEATABLE READ in MySQL InnoDB (historically) may not?
  • Can you explain when snapshot isolation is weaker than serializability (write skew)?

Production incidents from weak isolation include double-spend windows, inventory oversell, incorrect audit trails, and "impossible" balances visible to concurrent readers. Architects who default every service to READ COMMITTED without analyzing invariants design subtle data corruption that surfaces only under concurrent load.

Conversely, architects who demand SERIALIZABLE everywhere pay latency and deadlock costs without quantifying which invariants actually require it. Principal-level judgment is matching isolation to invariants, not reciting ACID mnemonics.

3. Problems Being Solved​

ProblemWithout transactionsWith ACID + appropriate isolation
Partial updatesMoney debited but not creditedAtomicity rolls back entire transaction
Concurrent lost updatesTwo writers overwrite each otherIsolation + locking or MVCC prevents or detects
Dirty readsRead uncommitted data that rolls backREAD COMMITTED+ hides uncommitted writes
Non-repeatable readsSame query returns different rowsREPEATABLE READ+ stabilizes read set
Phantom readsNew rows appear in repeated range scanSERIALIZABLE or predicate locking
Constraint violationsConcurrent txs break invariantsSerializable execution or explicit constraints
Crash mid-writeTorn pages, unknown stateDurability + WAL recovery

Transactions solve local (single-database) atomicity and concurrent correctness for a defined set of operations. They do not automatically solve distributed atomicity across services—that requires 2PC, sagas, or outbox patterns covered in later chapters.

4. Assumptions and System Model​

Assume a single logical database with crash-recovery storage unless stated otherwise:

  • Transactions are sequences of reads and writes with BEGIN/COMMIT/ROLLBACK boundaries.
  • Concurrency arises from multiple transactions interleaving operations on shared data.
  • Storage uses a write-ahead log (WAL) or equivalent for durability—implementation detail varies by engine.
  • Isolation is defined over histories of transaction operations; a history is serializable if equivalent to some serial execution.
  • Failures: Process crash (recoverable via WAL); not Byzantine unless discussing BFT databases.

Not assumed: Distributed consensus across nodes (that is replication/consensus territory). Synchronized clocks for ordering (logical transaction IDs or MVCC timestamps are typical). That SQL standard isolation names map identically across vendors—they do not; always verify engine behavior.

Scope: ACID applies within one database instance or one shard's transactional boundary. Cross-shard transactions are a separate coordination problem.

5. Essential Terminology​

TermDefinition
AtomicityAll operations in a transaction succeed together or none persist.
Consistency (C in ACID)Transaction preserves integrity constraints; database moves between valid states.
IsolationDegree to which concurrent transactions' effects are separated.
DurabilityCommitted data survives crashes per recovery guarantees.
Isolation levelNamed policy (READ UNCOMMITTED … SERIALIZABLE) defining allowed anomalies.
Dirty readReading uncommitted data from another transaction.
Non-repeatable readRe-reading a row sees a different value within one transaction.
Phantom readRe-running a range query sees new rows inserted by another transaction.
Write skewTwo transactions read overlapping data, write disjoint rows, violating an invariant serial execution would prevent.
SerializabilityConcurrent history equivalent to some serial order of transactions.
Snapshot isolation (SI)Each transaction reads from a consistent snapshot; writes conflict on commit.
Predicate lockLock on a logical condition (range), not just a row.
Two-phase locking (2PL)Acquire locks before access; release after commit—basis of many serializable implementations.

Mnemonic: ACID = All or nothing, Correct invariants, Invisible intermediate states (isolation), Durable after commit.

6. Core Mechanism​

ACID properties in depth​

PropertyMechanism (typical)What it does not guarantee
AtomicityUndo log / WAL rollbackCross-service atomicity
ConsistencyCHECK constraints, FK, app logicCAP "consistency"
IsolationLocks, MVCC snapshots, SSIGlobal linearizability across shards
DurabilityWAL fsync, replicationSurvival of total datacenter loss without DR

Isolation level anomaly matrix​

LevelDirty readNon-repeatable readPhantomSerialization anomalies
READ UNCOMMITTEDAllowedAllowedAllowedAllowed
READ COMMITTEDPreventedAllowedAllowedAllowed
REPEATABLE READPreventedPreventedVaries by engineOften allowed (write skew)
SERIALIZABLEPreventedPreventedPreventedPrevented

ANSI note: The SQL standard definitions are incomplete; Berenson et al. (1995) and subsequent work (Adya, 1999) formalized anomaly phenomena (P0–P4, G0–G3). Interview answers should cite phenomena, not only level names.

Figure 1: Lost update anomaly—both transactions read the same value and both write, losing one debit unless prevented by isolation or explicit locking.

Pessimistic vs optimistic concurrency​

Figure 2: Pessimistic locking serializes access early; MVCC allows concurrent reads and detects write conflicts at commit.

Serializable execution equivalence​

Figure 3: Serializability requires existence of a serial order producing the same final state and read results—not a specific real-time order.

7. Step-by-Step Walkthrough​

Scenario: Bank transfer between accounts A and B; invariant: total balance unchanged.

StepActorActionIsolation note
1T1BEGIN—
2T1SELECT balance FROM accounts WHERE id=A FOR UPDATEPessimistic: locks row A
3T1SELECT balance FROM accounts WHERE id=B FOR UPDATELocks row B
4T2BEGIN; try UPDATE accounts SET balance=balance-10 WHERE id=ABlocks on T1's lock
5T1UPDATE A, UPDATE B; COMMITReleases locks
6T2Proceeds with updated balanceSees T1's commit

Walkthrough with READ COMMITTED + no explicit lock:

StepEffect
T1 reads A=100, T2 reads A=100 concurrentlyBoth see same snapshot moment
Both debit 50 and commitFinal A=50, lost one debit—invariant violated

Mitigation: SELECT FOR UPDATE, SERIALIZABLE isolation, or UPDATE accounts SET balance = balance - 50 WHERE id=A AND balance >= 50 with row-count check.

Phantom walkthrough (shift scheduling):

StepT1 (count on-call doctors)T2 (insert doctor)
1BEGIN—
2SELECT COUNT(*) WHERE on_call=true → 1—
3—INSERT on_call=true; COMMIT
4SELECT COUNT(*) → 2Phantom—violates "at least one on call" decision

Mitigation: SERIALIZABLE or predicate locking (PostgreSQL SSI).

8. Invariants and Guarantees​

PropertyTypeStatement
AtomicitySafetyNo partial transaction effects visible after crash or abort
DurabilitySafetyCommitted data recoverable from WAL after crash
Isolation (per level)SafetyAnomalies per level table are prevented
SerializabilitySafetyHistory equivalent to serial execution
ProgressLivenessNot guaranteed—deadlocks may require abort
Bounded commit timeLivenessNot implied—lock wait unbounded

Distinction: Serializability is a safety property on histories. Deadlock freedom and wait-free progress are separate liveness concerns—databases typically abort one transaction to break deadlock.

9. Failure Scenarios​

Scenario 1: Lost update at READ COMMITTED​

Setup: Two concurrent inventory decrements without locking.

Effect: Oversell—stock goes negative or count wrong.

Mitigation: Optimistic versioning (UPDATE ... WHERE version = ?), FOR UPDATE, or SERIALIZABLE.

Scenario 2: Write skew under snapshot isolation​

Setup: Two transactions read "at least one on-call doctor," both see one, both assign current doctor off-call.

Effect: Zero on-call doctors—serializable execution would have blocked one transaction.

Mitigation: PostgreSQL Serializable Snapshot Isolation (SSI); explicit locking; materialize constraint.

Scenario 3: Long-running transaction + bloat​

Setup: REPEATABLE READ holds snapshot; prevents vacuum of dead tuples (PostgreSQL).

Effect: Table bloat, transaction ID wraparound risk—operational failure.

Mitigation: Short transactions, monitor age(datfrozenxid), connection pool timeouts.

Scenario 4: Dirty read in reporting​

Setup: Analytics job at READ UNCOMMITTED reads uncommitted order totals.

Effect: Reports include rolled-back orders—downstream bad decisions.

Mitigation: Never use READ UNCOMMITTED for business reports; READ COMMITTED minimum.

Scenario 5: ORM default isolation mismatch​

Setup: App assumes serializable; connection pool uses READ COMMITTED.

Effect: Latent bugs under production concurrency only.

Mitigation: Explicit SET TRANSACTION ISOLATION LEVEL; integration tests with concurrent load.

10. Performance Characteristics​

FactorImpact
Lock contentionSERIALIZABLE and FOR UPDATE serialize hot rows—latency tails grow
MVCC readsNo read locks—readers don't block writers (snapshot isolation)
Abort/retry rateOptimistic serializable (SSI) aborts on conflict—app must retry
Index range locksPhantom prevention (next-key locks in InnoDB) widens lock scope
WAL fsyncDurability cost per commit—group commit amortizes

Qualitative rule: Stronger isolation on hot keys is a serialization bottleneck. Measure lock waits (pg_locks, InnoDB innodb_lock_waits) before upgrading isolation globally.

READ COMMITTED is the default in PostgreSQL and many systems—good default for low-contention OLTP with explicit locking on critical paths.

11. Scalability Limits​

  • Single-node serializable throughput bounded by lock manager or SSI conflict detection.
  • Hot row updates (global counter, seat map) don't scale with SERIALIZABLE—shard or relax invariant.
  • Long transactions block vacuum, hold locks, increase deadlock probability.
  • Cross-shard transactions don't scale linearly—each shard serializes; 2PC adds coordination latency.

When SERIALIZABLE doesn't scale: Global inventory counter, viral event ticket sales, real-time bidding without partitioning.

12. Operational Considerations​

  • Document isolation per service in ADRs—not just "we use Postgres."
  • Monitor: deadlocks/sec, lock wait time, serialization failures (SQLSTATE 40001), oldest xmin.
  • Connection pool: reset session state (DISCARD ALL or isolation level on checkout).
  • Migrations: changing isolation on live traffic—load test concurrent paths.
  • Read replicas: replication lag means replicas are not part of the same transactional isolation guarantee for reads routed to standbys.

13. Security Considerations​

  • TOCTOU in authorization: Check permission at READ COMMITTED, act later—role may change. Re-check or use serializable scope.
  • Multi-tenant row leakage: Weak isolation doesn't cause cross-tenant reads if RLS is correct—but app bugs in session variable setting are orthogonal.
  • Audit integrity: Dirty reads in misconfigured replicas undermine audit trails.
  • SQL injection + elevated isolation: Attacker holding locks longer—DoS via lock contention.

Isolation is correctness, not authorization—both required.

14. Cost Considerations​

  • Latency tax: SERIALIZABLE on contested rows vs READ COMMITTED.
  • Engineering tax: Retry logic for serialization failures, deadlock handling.
  • Incident tax: Weak isolation bugs are expensive—hard to reproduce, reputational damage on financial paths.
  • Opportunity cost: Over-strong isolation blocks throughput features (high-concurrency counters).

Decision criterion: Pay for SERIALIZABLE where invariant violation cost exceeds retry + latency cost—inventory, balances, seat assignment—not for idempotent analytics aggregates.

15. Production Implementations​

PostgreSQL​

Default READ COMMITTED; REPEATABLE READ and SERIALIZABLE use MVCC snapshots. SERIALIZABLE implemented via Serializable Snapshot Isolation (SSI)—detects rw-conflicts, may abort with 40001. REPEATABLE READ prevents non-repeatable reads and phantoms for standard SQL but not all serialization anomalies without SERIALIZABLE.

MySQL InnoDB​

Default REPEATABLE READ with next-key locking preventing phantoms for standard statements. Gap locks can cause unexpected deadlocks. READ COMMITTED reduces gap locks—common in high-contention workloads.

Oracle​

Default READ COMMITTED; SERIALIZABLE uses snapshot isolation semantics (SI, not full SSI)—write skew possible unless locking used.

SQL Server​

Supports all standard levels plus snapshot isolation as separate setting. Read committed snapshot (RCSI) uses row versioning without holding read locks.

CockroachDB / Spanner​

Default SERIALIZABLE globally—distributed optimistic concurrency with retry on write conflicts.

Distinction: Always separate SQL level name from engine implementation (Berenson/Adya phenomena).

16. Alternatives and Tradeoffs​

ApproachStrengthCostUse when
READ COMMITTED + explicit locksPredictable hot-path controlDeadlock managementKnown contention points
REPEATABLE READ (MVCC)Stable reads in transactionSnapshot bloat, write skewReporting in one txn
SERIALIZABLEFull anomaly preventionAborts, latencyFinancial invariants
Snapshot isolationGood read concurrencyWeaker than serializableMany OLTP workloads accept write skew risk
Application-level locking (Redis)Cross-service coordinationNot ACID with DB—fencing neededSee distributed chapters
Event sourcingSerialize via logComplexity, replayAudit-heavy domains

PACELC reminder: Stronger isolation often trades normal-case latency for correctness even without network partition.

17. Common Misconceptions​

MisconceptionReality
"ACID consistency = CAP consistency"ACID C is application integrity; CAP C is linearizability.
"REPEATABLE READ = serializable"Write skew and other anomalies may remain.
"MVCC means no locking"Writers still lock; DDL locks exist; SSI tracks dependencies.
"READ UNCOMMITTED is faster"Many engines implement it as READ COMMITTED anyway.
"Transactions fix distributed consistency"Single-node only; microservices need sagas/2PC/outbox.
"Isolation level is per database"Usually per session/transaction—pools can leak state.
"Serializable means no deadlocks"Deadlocks still occur; one victim aborted.

18. Principal Architect Perspective​

  1. Inventory invariants before choosing isolation—"transfer money" vs "increment view count" differ.
  2. Name engine-specific behavior—PostgreSQL SERIALIZABLE ≠ Oracle SERIALIZABLE.
  3. Design for retries on serialization failure—idempotent operations, exponential backoff.
  4. Bound transaction duration—long txs are operational debt (bloat, locks, replication lag).
  5. Test concurrency—unit tests miss isolation bugs; use parallel integration tests or Jepsen-style workloads.

Interview signal: explaining write skew with the on-call doctor example separates principal candidates from ACID acronym recitation.

19. Architecture Review Exercise​

Scenario: E-commerce checkout: READ COMMITTED, SELECT stock FROM inventory WHERE sku=?, if stock>0 then UPDATE inventory SET stock=stock-1, insert order row—in one transaction.

Review prompts:

  1. What anomaly under concurrent checkouts for last item?
  2. Does wrapping in a transaction fix it at READ COMMITTED?
  3. Options: SELECT FOR UPDATE, UPDATE ... WHERE stock>0 with row count, SERIALIZABLE?
  4. Cost of SERIALIZABLE on hot SKU during flash sale?
  5. Alternative: partition inventory per warehouse shard?

Expected findings: Lost update possible; transaction alone insufficient without locking or atomic conditional update; hot-key sharding or queue may be needed at scale.

20. Whiteboard Explanation​

90-second version:

"ACID: transactions are all-or-nothing, preserve app constraints, hide concurrent intermediate states, and survive crashes after commit. Isolation levels trade concurrency for safety—READ COMMITTED stops dirty reads but allows lost updates unless you lock or use conditional updates. REPEATABLE READ stabilizes row reads but snapshot isolation can still have write skew. SERIALIZABLE means the concurrent run equals some serial order—PostgreSQL uses SSI and may abort transactions on conflict. Default READ COMMITTED is fine for many paths; money, inventory, and seat maps need explicit analysis. Always check your engine—SQL level names aren't portable. And ACID is single-database—microservices need sagas or outbox for cross-service atomicity."

21. Interview Questions​

  1. Define each ACID property.

    • Signals: Atomicity all-or-nothing; C is constraints; isolation concurrency; durability post-commit survival.
    • Red flags: Conflating consistency with CAP.
  2. What anomalies does READ COMMITTED prevent?

    • Signals: Dirty reads prevented; non-repeatable and phantoms allowed.
  3. Explain lost update. How do you prevent it?

    • Signals: Concurrent read-modify-write; FOR UPDATE, optimistic version, atomic UPDATE.
  4. What is write skew?

    • Signals: Two txs read overlapping state, write disjoint rows, violate invariant; SI allows it.
  5. REPEATABLE READ vs SERIALIZABLE in PostgreSQL?

    • Signals: RR is snapshot without full SSI; SERIALIZABLE detects rw-dependencies, aborts.
  6. Does a transaction guarantee no lost updates?

    • Signals: No—isolation level and explicit locking matter.
  7. What is a phantom read?

    • Signals: Range query returns different row set; prevented by serializable or predicate locks.
  8. Pessimistic vs optimistic concurrency?

    • Signals: Lock early vs detect conflict at commit; retry on abort.
  9. Why are long transactions bad in MVCC systems?

    • Signals: Block vacuum, hold xmin, bloat, increase conflict window.
  10. How does InnoDB REPEATABLE READ differ from PostgreSQL?

    • Signals: Next-key/gap locks vs MVCC snapshot; phantom handling differences.
  11. When would you choose READ COMMITTED over SERIALIZABLE?

    • Signals: Low contention, idempotent ops, explicit locks on critical sections.
  12. What happens on serialization failure?

    • Signals: SQLSTATE 40001; app must retry whole transaction.
  13. Is snapshot isolation serializable?

    • Signals: No—write skew counterexample.
  14. How do you test isolation in production?

    • Signals: Concurrent integration tests, formal checkers, metrics on abort rate—not usually full Jepsen on prod.

22. Interview Follow-Ups​

  1. Design ticket sales for 100k concurrent users.

    • Signals: Hot row, SERIALIZABLE won't scale; queue, sharded counters, or reservation holds.
  2. ORM hides isolation—what do you mandate?

    • Signals: Explicit level on connection, pool reset, ADR per bounded context.
  3. Compare serializability to linearizability.

    • Signals: Transaction histories vs single-object real-time order.
  4. Financial transfer across two databases?

    • Signals: ACID doesn't span; 2PC or saga; outbox for events.
  5. Executive wants strongest isolation everywhere—response?

    • Signals: Latency, deadlock, throughput; risk-based per use case.

22A. Production Low-Level Design (Interview + Game Day)​

Isolation level per bounded context—payments ≠ analytics. Production LLD and Game Day Standard.

Transaction API​

ServiceIsolationRationale
Payment ledgerSERIALIZABLE or explicit row locksNo lost updates
Order read APIREAD COMMITTEDThroughput
Inventory holdSELECT FOR UPDATE + short txnHot row control

Step-by-step flow:

StepAnomaly preventedOps note
1Chooses isolation contractPool must reset level
2–3Phantom / skew on balanceRetry on serialization failure
4Atomicity + durabilityAlert on abort rate spike

SLO​

Payment path: 0 balance anomalies; serialization abort p99 < 2% or queue fallback.


22B. Game Day Playbooks​

#DrillInjectDetectMitigateVerify
GD-1RC on paymentsRun transfer under RCDouble-spend in testUpgrade to SERIALIZABLEBalances match
GD-2Hot row deadlockFlash sale on one SKUTxn timeout ↑Queue + shard inventoryThroughput recovers
GD-3ORM default levelAudit connection poolWrong isolation in prodMandate level in ADRIntegration tests pass

GD-1 — READ COMMITTED payment unsafe path​

23. Strong Answer Example​

Question: "We use READ COMMITTED for payments. Is that safe?"

Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—not by default, and ACID ≠ isolation strong enough for money.

PRACTICE interview answer map for READ COMMITTED payments safety

Figure A: PRACTICE map — Problem → Requirements → Assumptions → Capacity → Topology → Invariants → Constraints → Evolution.


Student interview script (PRACTICE)​

P — Problem framing​

"READ COMMITTED is a common default—Postgres uses it. It prevents dirty reads: you never see uncommitted data. For payments, the danger isn't dirty reads—it's lost updates and write skew on concurrent debit/credit logic.

Classic failure: two transfers both SELECT balance = 100, both compute 50, both UPDATE—one debit vanishes. Atomicity of each transaction doesn't save you; isolation was too weak for the invariant.

Short answer: Not safe by itself for concurrent balance updates. RC can be part of a safe design only if we add locks, conditional updates, SERIALIZABLE/SSI, or an append-only ledger—and we still need idempotency and a story for cross-service payments."

R — Requirements​

Payment invariantRC alone enough?What we need
Never see uncommitted balanceYesRC prevents dirty reads
No lost debit/credit on same accountNoLock, conditional UPDATE, or SERIALIZABLE
Transfer conserves funds (A+B constant)No if read-modify-writeAtomic multi-row txn + conflict control
No double-spend / double-captureNoIdempotency key + unique constraint
Cross-service "atomic" pay+orderNoOutbox / saga—not isolation level

"I'd ask: single DB transfer, or microservices? Hot wallet accounts? ORM defaults? Read replicas on the money path?"

A — Assumptions (state aloud)​

AssumptionWhy it matters
Concurrent transfers hit same accountsContends on balance rows
App does read → compute → writeClassic lost-update shape under RC
Postgres/MySQL-style OLTPEngine quirks (SSI vs SI vs gap locks)
"ACID" cited by teamAtomicity ≠ serializability
Money path may hit replicasLag breaks even strong primary isolation

"I'd assume concurrent load until they prove single-threaded payment workers—which is rare."

C — Capacity (cost of safety)​

READ COMMITTED, no locks → high concurrency; corrupt under contention
RC + SELECT FOR UPDATE → serialize hot accounts; watch deadlocks
SERIALIZABLE (Postgres SSI) → abort+retry (40001); measure abort rate
Append-only ledger inserts → high write throughput; balance = aggregate / cache
Idempotency key unique index → cheap safety; mandatory regardless of isolation

"I'd rather pay lock waits or SSI aborts on the money path than silent lost updates. Analytics stay at RC."

T — Topology (draw this)​

READ COMMITTED vs what payments need

Figure B: RC stops dirty reads but still allows lost updates / write skew—unsafe for concurrent payment RMW.

Safer payment isolation paths

Figure C: Pick a path—SERIALIZABLE/SSI, SELECT FOR UPDATE, or append-only ledger + idempotency.

Safe patternHow it worksWatch-outs
SELECT … FOR UPDATE then updatePessimistic lock both accounts (ordered by id)Deadlocks; lock ordering
Conditional updateUPDATE … SET bal=bal-50 WHERE id=? AND bal>=50; check rowcountEasy to forget in ORM
SERIALIZABLE / SSIDB aborts conflicting concurrent txs; app retriesAbort storms on hot keys
Append-only ledgerInsert debit/credit rows; unique transfer_idNeed careful balance query / cache
Idempotency keyClient retry ≠ double chargeRequired even with SERIALIZABLE

I — Invariants (safety)​

"Non-negotiable for payments:

  1. No lost updates on balances / authorization holds.
  2. Conservation — transfer doesn't create or destroy money inside one DB txn.
  3. Non-negative (or explicit overdraft policy) enforced in the same atomic update.
  4. Exactly-once business effect under retries — idempotency key.
  5. RC alone does not imply (1)–(3) for concurrent RMW.
  6. Cross-service atomicity is out of scope for isolation levels."

C — Constraints (second C)​

ConstraintDesign response
Hot celebrity / treasury accountLedger or queue serialization; don't blanket SERIALIZABLE globally
ORM / connection pool defaultsSet isolation + FOR UPDATE in repository; reset session on checkout
Deadlocks under lock ordering bugsAlways lock account ids in sorted order
Read replica for "balance API"Primary for money decisions; replica lag is not isolation
Multi-service paymentOutbox + saga compensations; not 2PC casually

E — Evolution (prove it)​

Phased delivery:

PhaseDeliverable
M1Inventory payment invariants; ADR: RC default except money paths
M2Harden transfer: FOR UPDATE or conditional update + idempotency unique
M3Concurrent transfer integration tests (parallel clients)
M4Optionally move contested paths to SSI or ledger
M5Monitor deadlocks, SSI aborts, duplicate idempotency conflicts

Failure modes:

FailureMitigation
Lost update under RC RMWLocks / conditional update / SERIALIZABLE
Write skew (two checks, both pass)SERIALIZABLE or constraint locking
Double charge on client retryIdempotency key
"Postgres is ACID so we're fine"Teach A ≠ I strength
Cross-DB partial commitOutbox / saga

Observability: deadlock rate, serialization failure (40001) rate, idempotency conflict count, balance conservation reconciler, concurrent-transfer chaos tests.


Closing line (interview)​

"So: READ COMMITTED for payments is not safe by default. It stops dirty reads but still allows lost updates and write skew on concurrent balance logic. I'd keep RC as the service default, and on the money path use SELECT FOR UPDATE or conditional updates, or SERIALIZABLE/SSI, plus idempotency keys—and an append-only ledger if contention is high. Cross-service payments need outbox/sagas, not a stronger SQL isolation name. I'd prove it with concurrent transfer tests and document it in an ADR."

Scoring signals​

StrongWeak / red flag
"Not by default" + names lost update"Yes, ACID / Postgres is fine"
Separates atomicity from isolationConflates A with I
Concrete fix: FOR UPDATE / conditional / SSI / ledgerOnly "use transactions"
Idempotency for retriesIgnores double-submit
Cross-service ≠ isolation levelClaims RC fixes microservices
Per-path ADR + concurrency testsGlobal SERIALIZABLE with no tradeoff

Compact outline (if time-boxed to 2 minutes)​

"No—not alone. RC prevents dirty reads, not lost updates. Two concurrent debits can both read 100 and both write 50. Fix with FOR UPDATE, conditional UPDATE, SERIALIZABLE, or ledger + idempotency. Cross-service needs outbox/saga. ADR per invariant; concurrent tests."

24. Weak Answer Example​

Question: "We use READ COMMITTED for payments. Is that safe?"

"Yes, Postgres is ACID so we're fine. Transactions are atomic."

Why weak / red flags: Ignores isolation level semantics, lost updates, write skew; no locking/conditional update/SSI; conflates atomicity with isolation—classic payment-incident pattern under concurrency.

25. Hands-On Exercise​

Exercise: Isolation anomaly reproduction

  1. Spin up PostgreSQL locally; open two psql sessions.
  2. Session A: BEGIN ISOLATION LEVEL READ COMMITTED; read a row.
  3. Session B: update and commit the same row.
  4. Session A: read again—observe non-repeatable read.
  5. Repeat with REPEATABLE READ—stable read.
  6. Implement write skew with two sessions and on-call doctor table.
  7. Retry with SERIALIZABLE—observe 40001 on conflict.
  8. Write ADR: isolation level for one service in your domain.

Success criteria: Reproduce non-repeatable read and write skew; document mitigation chosen.

26. Knowledge Check​

  1. What does atomicity guarantee? (All-or-nothing commit/abort.)
  2. Dirty read allowed at which level? (READ UNCOMMITTED.)
  3. Does REPEATABLE READ prevent write skew in PostgreSQL? (Not necessarily—need SERIALIZABLE for SSI.)
  4. What is a phantom read? (New rows in repeated range query.)
  5. Pessimistic locking example in SQL? (SELECT FOR UPDATE.)
  6. SQLSTATE for serialization failure in PostgreSQL? (40001.)

27. Flashcards​

#FrontBack
1AtomicityAll ops commit or none persist.
2ACID ConsistencyPreserves integrity constraints per transaction.
3IsolationHides concurrent uncommitted/changing state per level.
4DurabilityCommitted data survives crash via WAL.
5Dirty readRead uncommitted data from another txn.
6Non-repeatable readSame row, different value on re-read.
7Phantom readRange query returns new rows.
8Write skewSI anomaly: concurrent disjoint writes break invariant.
9SerializabilityEquivalent to some serial execution order.
10READ COMMITTEDNo dirty reads; default in PostgreSQL.
11SSIPostgreSQL SERIALIZABLE via snapshot + conflict detection.
12SELECT FOR UPDATEPessimistic row lock until commit.

28. Cheat Sheet​

ACID
A: all-or-nothing (undo/WAL)
C: app constraints (not CAP C)
I: isolation level
D: WAL + fsync

ISOLATION LADDER
RU → RC → RR → SERIALIZABLE
Stronger = fewer anomalies, more contention/aborts

KEY ANOMALIES
Lost update: RC+ without lock
Write skew: SI, not full serializable
Phantom: needs SERIALIZABLE / predicate lock

POSTGRES
Default RC; SERIALIZABLE = SSI, retry 40001

INTERVIEW
Engine-specific behavior
Invariant → level + locking
ACID ≠ distributed atomicity

30. References​

Primary sources​

Production and engineering​

  • PostgreSQL Documentation — Transaction Isolation — SSI behavior, isolation level semantics.
  • MySQL InnoDB Documentation — InnoDB Transaction Model — next-key locks, REPEATABLE READ.
  • Martin Kleppmann, Designing Data-Intensive Applications (O'Reilly) — Chapters 7–9 on transactions and isolation.

Distinction​

Claim typeSource
ACID definitionsGray & Reuter; textbook consensus
Anomaly phenomenaBerenson et al. (1995); Adya (1999)
PostgreSQL SSIPostgreSQL official docs
InnoDB gap locksMySQL official docs