{}DSA Atlas

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.

Intermediate → Advanced8 interview questions

What a transaction is

A transaction groups operations into one logical unit:

SQL
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

PropertyGuaranteeMechanism
Atomicityall or nothingundo log / WAL, rollback
Consistencyconstraints and invariants hold before and afterconstraints, triggers, application logic
Isolationconcurrent transactions don't interfere (per isolation level)locking, MVCC, SSI
Durabilitycommitted data survives crashesWAL + fsync before commit ack; replication

Concurrency anomalies

AnomalyWhat happensExample
Dirty readread another transaction's uncommitted dataT2 sees T1's debit; T1 rolls back
Dirty writeoverwrite uncommitted datatwo transactions interleave writes to the same row
Non-repeatable readreading the same row twice gives different valuesT1 reads balance 100; T2 commits 50; T1 reads 50
Phantom readre-running a range query returns new/missing rowsCOUNT(*) WHERE dept = 5 changes mid-transaction
Lost updatetwo read-modify-writes; one overwrites the otherboth read stock 10, both write 9
Read skewsee parts of the database at different points in timetransfer: see account A after, account B before
Write skeweach transaction checks an invariant, writes a different row; together they break ittwo doctors both go off call

Lost update, visually

T1T2stock (row) read stock = 10 read stock = 10 write 9, commit write 9, commit 101099 ✗ (should be 8) fix: UPDATE stock SET qty = qty − 1 …, SELECT … FOR UPDATE, or a version check
Two sales, one decrement.

Isolation levels

LevelDirty readNon-repeatablePhantomLost updateWrite skew
Read Uncommitted✗ possiblepossiblepossiblepossiblepossible
Read Committed (Postgres, Oracle, SQL Server default)✓possiblepossiblepossiblepossible
Repeatable Read (MySQL default)✓✓engine-dependentengine-dependentpossible
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)

LockCompatible withTaken by
Shared (S)Sreads (in lock-based engines), SELECT … FOR SHARE
Exclusive (X)nothingwrites, SELECT … FOR UPDATE
Intention (IS/IX)hierarchical lockingtable-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

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

balance=100xmin=50 · xmax=70 balance=80xmin=70 · xmax=90 balance=30xmin=90 · xmax=∞ old versionold versioncurrent A transaction whose snapshot was taken after txid 70 committed but before 90: sees balance = 80. New transactions see 30. Versions no snapshot can see are removed by VACUUM (Postgres) / purge (InnoDB).
Every update creates a new version; each transaction reads the version visible to its snapshot.
  • 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

SQL
-- 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
PessimisticOptimistic
Strategylock firstvalidate at commit
Best underhigh contention, short transactionslow contention, long think time, distributed/HTTP
Cost of conflictwaiting (and deadlocks)wasted work + retry
ToolsFOR UPDATE, mutexesversion columns, CAS, ETag/If-Match

Durability: WAL, checkpoints, recovery

UPDATE / COMMIT buffer pool pagemodified in RAM (dirty) WAL recordappend + fsync at commit data files WAL on disk 1st: before ack later: checkpoint
The log is written (sequentially) before the data pages; commit is acknowledged after the log is on disk.
  • WAL rule: log first, data later. Sequential log writes are cheap; random data-page writes are deferred and batched.
  • Group commit: one fsync covers 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

SQL
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

0 / 8 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.