ACID and isolation levels
HardDatabasesTransactionsACID
What does ACID mean, and what are transaction isolation levels?
TL;DR
ACID is what a transaction guarantees: Atomicity (all or nothing), Consistency (constraints hold before and after), Isolation (concurrent transactions don't see each other's half-done work), and Durability (once committed, it survives a crash). Isolation levels trade correctness for concurrency by deciding which anomalies are allowed. From weakest to strongest: Read Uncommitted, Read Committed (the PostgreSQL default), Repeatable Read (the MySQL default), and Serializable.
Key points
| Level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| Read Uncommitted | Possible | Possible | Possible |
| Read Committed | ❌ | Possible | Possible |
| Repeatable Read | ❌ | ❌ | Possible (not in PostgreSQL) |
| Serializable | ❌ | ❌ | ❌ |
- Dirty read: reading another transaction's uncommitted data.
- Non-repeatable read: reading the same row twice and getting different values.
- Phantom: re-running a query and getting new rows.
- Lost update: two transactions read, modify and write the same row, and one overwrites the other. Common at Read Committed.
- Fixes for lost updates: an atomic update (
SET balance = balance - 100),SELECT ... FOR UPDATE, optimistic locking with aversioncolumn, or Serializable with retries. - Serializable can abort transactions with serialization errors; the app must retry them.
Example
sql
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; -- lock the row
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;Common follow-ups
- Optimistic vs pessimistic locking? Pessimistic locks the row up front (
FOR UPDATE). Optimistic checks a version on write (UPDATE ... WHERE version = 7) and retries on conflict; it's better when conflicts are rare. - How do databases provide isolation without blocking readers? MVCC: each transaction reads a snapshot, and writers create new row versions.
What interviewers look for
Tip
Define all four letters, map isolation levels to anomalies, and fix a lost update or double-spend concretely.
- Red flag: "we use transactions, so race conditions can't happen."