SQL & Relational Database Mastery · Chapter 11 · ~15 min · Advanced
Transactions, ACID & Locking: Concurrency & Isolation
Guarantee data integrity with ACID transactions, compare isolation levels, prevent dirty reads, and avoid deadlocks with row-level locks.
- Enforce data integrity using ACID transactions (Atomicity, Consistency, Isolation, Durability)
- Compare the 4 ANSI SQL isolation levels: Read Uncommitted, Read Committed, Repeatable Read, and Serializable
- Diagnose concurrency anomalies: Dirty Reads, Non-Repeatable Reads, and Phantom Reads
- Prevent deadlocks and manage row-level locking with SELECT FOR UPDATE
Transactions, ACID & Locking: Concurrency & Isolation: learn it visually
Guarantee data integrity with ACID transactions, compare isolation levels, prevent dirty reads, and avoid deadlocks with row-level locks.
1Intuition: The 4 ACID Guarantees
In distributed systems and multi-threaded web applications, hundreds of concurrent HTTP requests attempt to read and mutate the database simultaneously. Without strict transaction semantics, race conditions will corrupt balances, generate duplicate registrations, and silently lose inventory.
Relational databases guarantee system stability through the ACID contract:
Atomicity
All or nothing. If any single query fails, the entire transaction rolls back cleanly.
Consistency
State transitions must satisfy all constraints, foreign keys, triggers, and checks.
Isolation
Concurrent transactions execute without uncommitted interference or race conditions.
Durability
Committed updates are flushed to the Write-Ahead Log (WAL) and survive power cuts.
In ACID guarantees, what does 'Durability' specifically ensure?
2Architecture: Isolation Levels & Concurrency Anomalies
The ANSI SQL standard defines 4 isolation levels to manage the trade-off between concurrency throughput and anomaly prevention. Study the 3 crucial transactional models below:
Wrong idea: Multiple SQL statements execute safely one after another
Executing debit from account A, followed by credit to account B without a transaction. If the server crashes or power fails between statement 1 and statement 2, money disappears permanently into thin air.
Real system: Transactions ensure all-or-nothing atomicity with automatic rollback
Wrapping commands in BEGIN ... COMMIT guarantees that if any statement fails or the database crashes, the engine executes ROLLBACK and restores the exact pre-transaction state.
-- High-Contention Flash Checkout using SELECT FOR UPDATE:
BEGIN TRANSACTION;
-- 1. Acquire exclusive row lock on product inventory
SELECT stock_count
FROM inventory
WHERE product_id = 99
FOR UPDATE;
-- 2. Verify stock availability inside lock boundary
-- (If stock_count < 1, application issues ROLLBACK)
-- 3. Safely decrement stock
UPDATE inventory
SET stock_count = stock_count - 1
WHERE product_id = 99;
-- 4. Record customer order
INSERT INTO orders (product_id, customer_id, created_at)
VALUES (99, 42, NOW());
COMMIT;Which ANSI SQL isolation level is the ONLY level that permits Dirty Reads (reading uncommitted changes from other concurrent transactions)?
3Interactive Visual: Dual-Session Concurrency Lab & Deadlocks
Run concurrent writer and reader sessions side by side to experience MVCC snapshot isolation in real time. Inspect the deadlock graph to understand why ascending key lock order is essential.
Dual-Session Concurrency Lab & Deadlock Visualizer
Table initial balance: $100
Run SELECT query while Session 1 is in-flight:
Initial committed row state.
What is the key difference between a 'Non-Repeatable Read' and a 'Phantom Read'?
4Bug Hunt: Prevent Inventory Race Condition with SELECT FOR UPDATE
A flash sale checkout service is overselling inventory because two concurrent users check stock at the same millisecond and both execute an update. Protect the transaction by wrapping it in a transaction block and acquiring an exclusive row lock with SELECT ... FOR UPDATE.
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
• Add BEGIN TRANSACTION; at the beginning.
• Append FOR UPDATE; to the SELECT query.
• Add COMMIT; at the end.
Why is 'SELECT ... FOR UPDATE' preferred over optimistic concurrency in high-contention flash-sale checkout systems?
5Recap & Transaction Safety Checklist
- Wrap Multi-Statement Writes: Never execute multi-step mutations without
BEGIN ... COMMITblocks. - Know Your Default Isolation: PostgreSQL and Oracle default to Read Committed; MySQL InnoDB defaults to Repeatable Read.
- Prevent Deadlocks: Always acquire row locks in deterministic ascending primary key order (
ORDER BY id FOR UPDATE). - Keep Transactions Lean: Never make third-party HTTP API calls or heavy disk I/O while holding database row locks inside an active transaction.
Ready for Chapter 12 (SQL Capstone & Senior Technical Interview Prep)? Mark as complete: