Skip to content
Back to 50 Concepts
Topic 49 of 50transactionsAdvanced

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Locks & Isolation Levels Visual Simulator

Step 1 of 3
SQL>BEGIN; SELECT balance FROM accounts WHERE id = 10 FOR UPDATE; UPDATE accounts SET balance = balance - 100 WHERE id = 10; COMMIT;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for Locks & Isolation Levels
SQL Input

Initiating Locks & Isolation Levels

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Turn-based board game: Under Serializable isolation, every player takes their turn in a strict sequence, ensuring no two players move the same piece simultaneously.

4. Real-World Example

Two users simultaneously attempting to book the very last remaining seat on an airplane.

Isolation Levels & Concurrency Anomalies
Isolation LevelDirty ReadNon-Repeatable ReadPhantom ReadWrite Skew
Read UncommittedPossiblePossiblePossiblePossible
Read Committed (PG Default)PreventedPossiblePossiblePossible
Repeatable ReadPreventedPreventedPrevented (PG)Possible
SerializablePreventedPreventedPreventedPrevented
Relational walkthrough: Serializable isolation guarantees execution matches a sequential one-by-one serial order.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Setting transaction isolation level
BEGIN 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;
Step 2: Explicit pessimistic row locking with FOR UPDATE
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;
Prevents race conditions by making competing transactions wait.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Readers Don't Block WritersUnder MVCC, read transactions never block write transactions, and writers never block readers.
Pessimistic vs OptimisticPessimistic locking (SELECT FOR UPDATE) locks rows upfront; Optimistic locking checks version counters at commit time.
Deadlock DetectionWhen transaction A waits for B and B waits for A, the database engine aborts one transaction with a deadlock error.
Two-Phase Locking (2PL) protocolIn 2PL, a transaction acquires locks during the expanding phase and releases all locks only at COMMIT.
MVCC non-blocking read-write guaranteeReaders 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.
Caution: Never rely on Repeatable Read when cross-row business rules depend on concurrent reads.

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

Scenario Question:

Which concurrency anomaly can occur under Repeatable Read in the ANSI SQL standard, but is completely eliminated by Serializable isolation?

Select your answer: