A transaction groups several reads and writes into one unit that either happens completely or not at all, and isolation controls what concurrent transactions can see of each other. ACID is the set of guarantees relational databases give you; isolation levels decide how many concurrency anomalies slip through in exchange for speed. Knowing exactly which anomaly each level allows, and how to fix it, separates engineers who ship correct systems from those who ship race conditions.
Think of it like
A bank teller with a private desk
A transfer slip says "take $100 from savings, put $100 in checking". Atomicity means the teller never does only half. Isolation means every customer feels like they have the teller to themselves, even though dozens are served at once. Durability means once the receipt is printed, a power cut can't undo it. Consistency means the bank's rules (no negative balances) hold before and after.
ACID, property by property
- Atomicity
- All of a transaction's writes take effect, or none do. If anything fails midway (constraint violation, crash, explicit
ROLLBACK), every change is undone. It is really about abortability, not about concurrency. - Consistency
- A transaction moves the database from one valid state to another with respect to its invariants: declared constraints (
NOT NULL, foreign keys,CHECK) plus application rules. The database enforces the declared ones; the rest is the application's job. - Isolation
- Concurrent transactions don't interfere. The ideal is serializability: the result equals some one-at-a-time order. Most databases default to weaker levels for performance.
- Durability
- Once
COMMITreturns, the data survives crashes and power loss. Implemented with a write-ahead log flushed to disk (and often replication).
BASE: the other end of the spectrum
ACID
- Correctness first: transactions are atomic and isolated
- Pessimistic about concurrency and failure
- Traditionally a single node or tightly coordinated cluster
- PostgreSQL, MySQL, Oracle, SQL Server, Spanner, CockroachDB
BASE
- Basically Available: answer even during failures
- Soft state: data may be in flux without new input (replication in progress)
- Eventually consistent: replicas converge later
- Cassandra, DynamoDB (default mode), Riak, many caches
The split is less sharp than it used to be. DynamoDB, MongoDB and Cassandra (lightweight transactions) offer transactional operations, and distributed SQL databases provide full ACID at scale by paying for coordination. See Distributed Transactions for how that works across machines.
Concurrency anomalies
Each anomaly below is a specific interleaving of two transactions, T1 and T2, that produces a result no serial order could. The isolation levels in the next section are defined by which of these they prevent. Use the simulation above to run two transactions at different isolation levels and see which anomalies slip through.
Dirty write
| Step | T1 (Alice buys car 1) | T2 (Bob buys car 1) |
|---|---|---|
| 1 | UPDATE listings SET buyer = 'Alice' WHERE car = 1 | |
| 2 | UPDATE listings SET buyer = 'Bob' WHERE car = 1 (overwrites uncommitted data) | |
| 3 | UPDATE invoices SET recipient = 'Bob' WHERE car = 1 | |
| 4 | COMMIT | |
| 5 | UPDATE invoices SET recipient = 'Alice' WHERE car = 1 | |
| 6 | COMMIT | Result: Bob gets the car, Alice gets the invoice |
Dirty read
| Step | T1 (withdrawal) | T2 (fraud check) |
|---|---|---|
| 1 | UPDATE accounts SET balance = 0 WHERE id = 7 (was 500) | |
| 2 | SELECT balance FROM accounts WHERE id = 7 → 0 | |
| 3 | Flags the account as drained and freezes it | |
| 4 | ROLLBACK (the withdrawal failed) | Acted on a value that never officially existed |
Non-repeatable read (fuzzy read)
| Step | T1 (report) | T2 (payment) |
|---|---|---|
| 1 | SELECT balance FROM accounts WHERE id = 7 → 500 | |
| 2 | UPDATE accounts SET balance = 300 WHERE id = 7; COMMIT | |
| 3 | SELECT balance FROM accounts WHERE id = 7 → 300 | Same row, same transaction, different answer |
Phantom read
| Step | T1 (count on-call doctors) | T2 (add a doctor) |
|---|---|---|
| 1 | SELECT count(*) FROM doctors WHERE on_call → 2 | |
| 2 | INSERT INTO doctors (name, on_call) VALUES ('Dana', true); COMMIT | |
| 3 | SELECT count(*) FROM doctors WHERE on_call → 3 | A new row matching the predicate appeared |
Lost update
| Step | T1 | T2 |
|---|---|---|
| 1 | SELECT stock FROM items WHERE id = 1 → 10 | |
| 2 | SELECT stock FROM items WHERE id = 1 → 10 | |
| 3 | UPDATE items SET stock = 9 WHERE id = 1; COMMIT | |
| 4 | UPDATE items SET stock = 9 WHERE id = 1; COMMIT | |
| Result | Two items sold, stock only dropped by 1 |
Write skew
| Step | T1 (Alice goes off call) | T2 (Bob goes off call) |
|---|---|---|
| 1 | SELECT count(*) FROM doctors WHERE on_call → 2 | |
| 2 | SELECT count(*) FROM doctors WHERE on_call → 2 | |
| 3 | 2 ≥ 2, so UPDATE doctors SET on_call = false WHERE name = 'Alice' | |
| 4 | 2 ≥ 2, so UPDATE doctors SET on_call = false WHERE name = 'Bob' | |
| 5 | COMMIT | COMMIT: zero doctors on call, invariant broken |
Isolation levels
| Level | Dirty read | Non-repeatable read | Phantom | Lost update | Write skew |
|---|---|---|---|---|---|
| Read Uncommitted | Possible | Possible | Possible | Possible | Possible |
| Read Committed | Prevented | Possible | Possible | Possible | Possible |
| Repeatable Read / Snapshot Isolation (PostgreSQL) | Prevented | Prevented | Prevented | Prevented | Possible |
| Serializable | Prevented | Prevented | Prevented | Prevented | Prevented |
| Database | Default level | Notes |
|---|---|---|
| PostgreSQL | Read Committed | Repeatable Read = snapshot isolation that aborts on concurrent updates (could not serialize access); Serializable = SSI |
| MySQL (InnoDB) | Repeatable Read | Plain SELECTs read a snapshot; locking reads use next-key locks against phantoms. Does not detect lost updates from read-then-write in application code |
| Oracle | Read Committed | Its "SERIALIZABLE" is actually snapshot isolation, so write skew is possible |
| SQL Server | Read Committed (locking) | Optional Read Committed Snapshot and Snapshot isolation via row versioning |
| CockroachDB | Serializable | Read Committed is available as an option in newer versions |
How databases implement isolation
Two-phase locking (2PL)
- Growing phase acquires locks; shrinking phase releases them
- Strict 2PL holds every lock until commit or abort
- Shared locks for reads, exclusive for writes: readers block writers and vice versa
- Range or next-key locks stop phantoms
- Serializable, but deadlocks happen and throughput suffers under contention
MVCC + snapshot isolation
- Each write creates a new row version tagged with its transaction ID
- Each transaction reads a consistent snapshot taken when it starts
- Readers never block writers; writers never block readers
- Concurrent writes to the same row: the first committer wins and the other aborts
- Allows write skew; old versions need garbage collection (PostgreSQL
VACUUM)
Serializable snapshot isolation (SSI)
- Snapshot isolation plus tracking of read/write dependencies
- Aborts a transaction when a dangerous dependency cycle could form
- Optimistic: no read locks, no blocking
- Clients must retry on serialization failure (SQLSTATE
40001) - PostgreSQL
SERIALIZABLE, CockroachDB
- 1
Versions
In PostgreSQL every row version stores
xmin(the transaction that created it) andxmax(the transaction that deleted or replaced it, if any). - 2
Snapshot
When a transaction (or, under Read Committed, each statement) starts, it records which transactions had committed and which were still in progress.
- 3
Visibility
A version is visible if its creator committed before the snapshot and its deleter (if any) had not. Everything else is invisible, even if physically present.
- 4
Cleanup
When no running snapshot can see an old version anymore,
VACUUMreclaims it.
Practical fixes for real races
Atomic updates
-- Instead of SELECT stock, compute in the app, then UPDATE stock = 9:
UPDATE items SET stock = stock - 1 WHERE id = 1 AND stock > 0;
-- 1 row updated: sold. 0 rows: out of stock. No lost update at any isolation level.Pessimistic locking with SELECT ... FOR UPDATE
BEGIN;
-- Locks the matching rows: other FOR UPDATE / UPDATE / DELETE on them wait until we finish
SELECT name FROM doctors WHERE on_call AND shift_id = 1234 FOR UPDATE;
-- Application checks that at least 2 rows came back, then:
UPDATE doctors SET on_call = false WHERE name = 'Alice' AND shift_id = 1234;
COMMIT;- This fixes write skew when the conflicting rows already exist. When the conflict is about rows that don't exist yet (two people booking the same empty meeting slot), there is nothing to lock: use a unique constraint, "materialize" the conflict as a row you can lock, or use Serializable.
FOR UPDATE NOWAITfails immediately instead of waiting;FOR UPDATE SKIP LOCKEDskips locked rows, which is ideal for building a job queue on a table.- Lock rows in a consistent order (for example by primary key) to avoid deadlocks.
Optimistic concurrency with a version column
-- Read, remembering the version
SELECT id, body, version FROM docs WHERE id = 7; -- version = 3
-- Write only if nobody changed the row since we read it
UPDATE docs SET body = 'new text', version = version + 1
WHERE id = 7 AND version = 3;
-- 1 row updated: success. 0 rows: someone else won; re-read and retry (or ask the user).Durability: the write-ahead log
Writing modified data pages to disk on every commit would mean slow random I/O. Instead, databases append a description of every change to a sequential write-ahead log (WAL) and flush only the log at commit. Data pages are written back lazily, and after a crash the log is replayed. Press play to follow both paths.
Implementation
Compare-and-set on a version column; retries when another writer wins the race.
import psycopg
def update_doc(conn: psycopg.Connection, doc_id: int, transform, max_retries: int = 5) -> str:
"""conn is opened with autocommit=True; each statement is its own transaction."""
for _ in range(max_retries):
row = conn.execute("SELECT body, version FROM docs WHERE id = %s", (doc_id,)).fetchone()
if row is None:
raise KeyError(doc_id)
body, version = row
new_body = transform(body)
cur = conn.execute(
"UPDATE docs SET body = %s, version = version + 1 WHERE id = %s AND version = %s",
(new_body, doc_id, version),
)
if cur.rowcount == 1:
return new_body
# 0 rows: someone else updated the doc after our read. Loop and re-read.
raise RuntimeError("too much contention, giving up")Key takeaways
- Atomicity is about undoing partial work, isolation about concurrency, durability about surviving crashes; consistency is mostly the application's invariants.
- Know the six anomalies by their timelines: dirty write, dirty read, non-repeatable read, phantom, lost update, write skew.
- PostgreSQL defaults to Read Committed and MySQL to Repeatable Read; snapshot isolation still allows write skew.
- 2PL makes readers and writers block each other; MVCC lets them proceed and resolves write conflicts at commit.
- Fix races with atomic updates,
FOR UPDATE, version columns, constraints, or Serializable plus retries. - The WAL makes commits durable with one sequential fsync; data pages are written later.
Common pitfalls
- Reading a value, computing in application code, then writing it back (lost update) under Read Committed.
- Assuming Repeatable Read or Oracle's "Serializable" prevents write skew.
- Running Serializable without retry logic, so serialization failures surface as user-facing errors.
- Holding transactions open across network calls or user think time, which keeps locks and old MVCC versions alive.
- Turning off synchronous commit for critical data without realizing acknowledged writes can be lost.
Interview tips
- Draw the two-transaction timeline for the race the interviewer describes; it makes the anomaly obvious.
- Explain why snapshot isolation allows write skew: the two transactions write different rows, so no write-write conflict is detected.
- Mention optimistic concurrency (version column or ETag) for user-facing edit flows that span multiple requests.
Real-world applications
- Inventory and ticket booking: atomic decrements or
FOR UPDATEto avoid overselling. - Job queues on PostgreSQL with
FOR UPDATE SKIP LOCKED. - Collaborative edit forms with version columns or HTTP
If-Matchheaders. - Financial ledgers running at Serializable with automatic retries.
Test yourself
Which anomaly can snapshot isolation still allow?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.