Transactions, ACID & Concurrency Control
ACID in depth, isolation levels and every anomaly (dirty read, non-repeatable read, phantom, lost update, write skew), locking and two-phase locking, MVCC and snapshot isolation, SSI, optimistic vs pessimistic control, SELECT FOR UPDATE/SKIP LOCKED, and how WAL and ARIES make transactions durable.
What a transaction is
A transaction groups operations into one logical unit:
BEGIN;
UPDATE account SET balance = balance - 500 WHERE id = 1;
UPDATE account SET balance = balance + 500 WHERE id = 2;
INSERT INTO transfer (from_id, to_id, amount) VALUES (1, 2, 500);
COMMIT; -- or ROLLBACK on any error
Either all three statements take effect, or none do — even if the server crashes between them.
ACID
| Property | Guarantee | Mechanism |
|---|---|---|
| Atomicity | all or nothing | undo log / WAL, rollback |
| Consistency | constraints and invariants hold before and after | constraints, triggers, application logic |
| Isolation | concurrent transactions don't interfere (per isolation level) | locking, MVCC, SSI |
| Durability | committed data survives crashes | WAL + fsync before commit ack; replication |
Concurrency anomalies
| Anomaly | What happens | Example |
|---|---|---|
| Dirty read | read another transaction's uncommitted data | T2 sees T1's debit; T1 rolls back |
| Dirty write | overwrite uncommitted data | two transactions interleave writes to the same row |
| Non-repeatable read | reading the same row twice gives different values | T1 reads balance 100; T2 commits 50; T1 reads 50 |
| Phantom read | re-running a range query returns new/missing rows | COUNT(*) WHERE dept = 5 changes mid-transaction |
| Lost update | two read-modify-writes; one overwrites the other | both read stock 10, both write 9 |
| Read skew | see parts of the database at different points in time | transfer: see account A after, account B before |
| Write skew | each transaction checks an invariant, writes a different row; together they break it | two doctors both go off call |
Lost update, visually
Isolation levels
| Level | Dirty read | Non-repeatable | Phantom | Lost update | Write skew |
|---|---|---|---|---|---|
| Read Uncommitted | ✗ possible | possible | possible | possible | possible |
| Read Committed (Postgres, Oracle, SQL Server default) | ✓ | possible | possible | possible | possible |
| Repeatable Read (MySQL default) | ✓ | ✓ | engine-dependent | engine-dependent | possible |
| Snapshot Isolation (Postgres "RR") | ✓ | ✓ | ✓ | ✓ (aborts) | possible |
| Serializable | ✓ | ✓ | ✓ | ✓ | ✓ |
(✓ = prevented)
Higher isolation = fewer anomalies but more blocking or aborts. Serializable transactions must be retried on serialization failures (SQLSTATE 40001).
Locking and two-phase locking (2PL)
| Lock | Compatible with | Taken by |
|---|---|---|
| Shared (S) | S | reads (in lock-based engines), SELECT … FOR SHARE |
| Exclusive (X) | nothing | writes, SELECT … FOR UPDATE |
| Intention (IS/IX) | hierarchical locking | table-level marker before row locks |
| Gap / next-key (InnoDB) | — | lock ranges to prevent phantoms |
| Predicate locks | — | serializable range protection (SIRead locks in Postgres SSI) |
Two-phase locking: a transaction has a growing phase (acquire locks, release none) then a shrinking phase (release, acquire none). This guarantees conflict-serializability. Strict 2PL holds all write locks until commit (prevents cascading aborts) — what lock-based databases do. Downside: blocking and deadlocks (detected and broken by aborting a victim — see Deadlocks).
Explicit locking in SQL
BEGIN;
SELECT balance FROM account WHERE id = 7 FOR UPDATE; -- row lock until COMMIT
UPDATE account SET balance = balance - 100 WHERE id = 7;
COMMIT;
-- job queues: let concurrent workers take different rows
SELECT id FROM jobs WHERE status = 'ready' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1;
-- fail fast instead of waiting
SELECT * FROM seat WHERE id = 12 FOR UPDATE NOWAIT;
MVCC and snapshot isolation
- Readers never block writers, writers never block readers.
- Writers still conflict: the second writer to the same row waits, then (under RR/serializable) aborts if the first committed.
- Snapshot isolation (SI): each transaction reads from a snapshot taken at its start; "first committer wins" on write-write conflicts. Prevents most anomalies, but not write skew.
- Serializable Snapshot Isolation (SSI) (Postgres Serializable, CockroachDB): SI plus tracking of read-write dependencies; aborts transactions that would form a dangerous cycle. Serializable with mostly-optimistic behaviour.
Optimistic vs pessimistic concurrency
-- optimistic: version column
UPDATE document
SET body = $1, version = version + 1
WHERE id = $2 AND version = $3; -- 0 rows → someone else updated it → reload / retry / 409 Conflict
| Pessimistic | Optimistic | |
|---|---|---|
| Strategy | lock first | validate at commit |
| Best under | high contention, short transactions | low contention, long think time, distributed/HTTP |
| Cost of conflict | waiting (and deadlocks) | wasted work + retry |
| Tools | FOR UPDATE, mutexes | version columns, CAS, ETag/If-Match |
Durability: WAL, checkpoints, recovery
- WAL rule: log first, data later. Sequential log writes are cheap; random data-page writes are deferred and batched.
- Group commit: one
fsynccovers many concurrent transactions. - Checkpoints bound recovery time by flushing dirty pages and recording a position in the log.
- ARIES recovery: Analysis (what was in flight), Redo (repeat history from the checkpoint), Undo (roll back losers, logging compensation records).
- The WAL is also the basis of replication (ship the log to replicas) and point-in-time recovery (base backup + archived WAL) and CDC (Debezium reads the WAL/binlog).
Savepoints and nested work
BEGIN;
INSERT INTO orders ...;
SAVEPOINT before_coupon;
UPDATE coupon SET used = true WHERE code = 'X'; -- fails?
ROLLBACK TO SAVEPOINT before_coupon; -- undo just that part
COMMIT;
Practical transaction rules
- Keep transactions short; never wait for a user or call another service inside one.
- Access rows in a consistent order to reduce deadlocks.
- Use the lowest isolation level that is correct, plus targeted locks or atomic statements for invariants.
- Be ready to retry on deadlock (
40P01) and serialization failure (40001) — make the transaction body idempotent. - For cross-service consistency you can't use one database transaction → see sagas and the outbox pattern in Distributed data and Queues & streams.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.