# Topic 49: Locks & Isolation Levels
Read Committed vs Repeatable Read vs Serializable, MVCC mechanics, row-level locks, table locks, and deadlock resolution.
1. Definition
Isolation levels define the degree to which modifications made by concurrent transactions are isolated from one another, balancing concurrency anomalies against locking overhead.
2. Explain Like I'm 5
Isolation levels are soundproof glass partitions between rooms. At lower levels, you can hear mumbling through the wall; at the highest level (Serializable), it is completely soundproof, as if you were the only person in the building.
3. Animation & Visual Simulation
Interactive Engine TraceLocks & Isolation Levels Visual Simulator
BEGIN;
SELECT balance FROM accounts WHERE id = 10 FOR UPDATE;
UPDATE accounts SET balance = balance - 100 WHERE id = 10;
COMMIT;Active InputStep 1: Input & Parsing Stage
Initiating Locks & Isolation Levels
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Two users simultaneously attempting to book the very last remaining seat on an airplane.
| Isolation Level | Dirty Read | Non-Repeatable Read | Phantom Read | Write Skew |
|---|---|---|---|---|
| Read Uncommitted | Possible | Possible | Possible | Possible |
| Read Committed (PG Default) | Prevented | Possible | Possible | Possible |
| Repeatable Read | Prevented | Prevented | Prevented (PG) | Possible |
| Serializable | Prevented | Prevented | Prevented | Prevented |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectBEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ; SELECT balance FROM accounts WHERE id = 1; -- Even if another transaction updates account 1, this transaction -- sees the exact same snapshot until it commits! COMMIT;
BEGIN; -- Locks matching rows exclusively until COMMIT: SELECT id, available_seats FROM flights WHERE id = 42 FOR UPDATE; UPDATE flights SET available_seats = available_seats - 1 WHERE id = 42; COMMIT;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Readers Don't Block Writers | Under MVCC, read transactions never block write transactions, and writers never block readers. |
| Pessimistic vs Optimistic | Pessimistic locking (SELECT FOR UPDATE) locks rows upfront; Optimistic locking checks version counters at commit time. |
| Deadlock Detection | When transaction A waits for B and B waits for A, the database engine aborts one transaction with a deadlock error. |
| Two-Phase Locking (2PL) protocol | In 2PL, a transaction acquires locks during the expanding phase and releases all locks only at COMMIT. |
| MVCC non-blocking read-write guarantee | Readers reading older MVCC snapshots never block concurrent writers; writers never block readers. |
7. Deep Dive: Write Skew: The Anomaly that Breaks Repeatable Read
Write Skew occurs when two concurrent transactions read disjoint sets of rows, make decisions based on what they read, and update overlapping constraints. For example, two on-call doctors simultaneously check if at least one doctor remains on call, and both log off at the same instant! Only SERIALIZABLE isolation prevents write skew.
-- Tx 1 (Doctor Alice): Checks doctor count >= 2, marks herself off. -- Tx 2 (Doctor Bob): Checks doctor count >= 2, marks himself off. -- Under Repeatable Read: Both commit, leaving 0 doctors on call! -- Under Serializable: One transaction fails with serialization_failure.
8. Advantages & Disadvantages
Advantages
- •Granular control over concurrency vs consistency trade-offs.
- •SELECT ... FOR UPDATE prevents race conditions in booking and inventory engines.
Disadvantages & Trade-offs
- •Serializable transactions require application retry loops on serialization failures.
9. Common Interview Questions
Q1.How does MVCC (Multi-Version Concurrency Control) achieve non-blocking reads and writes?
Instead of acquiring locks on rows during reads, MVCC assigns every transaction a unique transaction ID. When a row is updated, the engine appends a new version with xmin set to current TX and xmax on the old tuple. When a reader runs, it takes a Snapshot containing active transaction IDs: it reads the row version committed before its snapshot started. Readers never block writers, and writers never block readers.
Q2.What is a Deadlock, how does the engine detect it, and how does it recover?
A Deadlock occurs when Transaction A holds Lock 1 and waits for Lock 2, while Transaction B holds Lock 2 and waits for Lock 1. Neither can proceed. The database Lock Manager maintains a directed "Wait-For Graph" where nodes are transactions and edges are lock requests. A background thread detects cycles in the graph (deadlocks) and forcibly aborts one of the transactions (the deadlock victim) with a serialization/deadlock error, allowing the other to complete.
Q3.What is the Write Skew anomaly and which isolation level prevents it?
Write Skew occurs under Snapshot Isolation (Repeatable Read). Example: On-call doctor rule requires at least 1 doctor on call. Alice and Bob are both on call. Alice queries on_call_count (sees 2), Bob queries on_call_count (sees 2). Both concurrently execute UPDATE set on_call = false. Both transactions commit because they modified DIFFERENT rows. Now ZERO doctors are on call! Only SERIALIZABLE isolation (or explicit SELECT FOR UPDATE) prevents Write Skew.
Q4.What is the difference between Shared (S) and Exclusive (X) locks?
A Shared Lock (S-Lock) is acquired for reading (e.g. SELECT ... FOR SHARE); multiple concurrent transactions can hold S-locks on the same row simultaneously. An Exclusive Lock (X-Lock) is acquired for writing (INSERT, UPDATE, DELETE, SELECT ... FOR UPDATE); only ONE transaction can hold an X-lock, blocking all other transactions from acquiring S-locks or X-locks until the transaction commits.
Q5.What is lock escalation and why does PostgreSQL NOT use lock escalation?
Lock escalation (common in SQL Server) occurs when an engine holding thousands of individual row locks automatically converts them into a single table lock to save lock manager RAM, unexpectedly locking out concurrent users. PostgreSQL allocates a fixed, generous lock table in shared memory and NEVER escalates row locks to table locks, ensuring predictable concurrency.
10. Interview-Ready Answer
“Transaction isolation levels dictate concurrency anomaly boundaries. PostgreSQL defaults to Read Committed using MVCC so readers never block writers. To prevent race conditions, applications employ SELECT FOR UPDATE or promote to Serializable isolation with automated retry loops.”
11. Quick Test
Which concurrency anomaly can occur under Repeatable Read in the ANSI SQL standard, but is completely eliminated by Serializable isolation?