Two-Phase Locking
The Goal: Conflict Serializability
Conflict serializability is the standard test a database uses to guarantee that running multiple transactions at the same time is correct — the same test covered in detail in Concurrency Anomalies. A schedule of overlapping transactions is conflict serializable if the final database state is identical to the result of running those same transactions one after another in a safe serial sequence.
To determine this, the database looks for conflicting operations. Two operations conflict if:
- They belong to different transactions.
- They access the exact same piece of data.
- At least one of the operations is a Write.
A Simple Example
Two transactions trying to update the same bank account balance — Transaction 1 checks the balance, deducts $50 for a bill payment, and saves the new balance. Transaction 2 checks the balance, adds a $10 deposit, and saves the new balance.
A safe (conflict serializable) execution:
- Transaction 1 reads the account balance and updates it.
- Transaction 2 reads the newly updated balance and adds $10 to it.
Why valid: Transaction 1 completed all its reads and writes on that account before Transaction 2 touched it — the outcome is identical to running Transaction 1 completely, followed by Transaction 2.
An invalid (NOT conflict serializable) execution:
- Transaction 1 reads the initial balance — $100.
- Before Transaction 1 can save, Transaction 2 also reads $100.
- Transaction 2 adds $10 and writes $110 back.
- Transaction 1 subtracts $50 from its stale initial read and writes $50 back, overwriting the deposit.
Why it fails: the conflicting reads and writes crossed paths in both directions — the final result matches neither running Transaction 1 first nor Transaction 2 first.
Solving It with a Dependency Graph (DAG)
How does the database prove one schedule is safe and the other isn't? By building a dependency graph:
- Each transaction becomes a node.
- Whenever two transactions conflict on the same data item, the database draws a directed edge from the transaction that went first to the one that went second.
Scenario 1: The Safe Execution
Timeline: T1 reads $100, writes $50. T2 then reads $50, writes $60.
- T1 wrote the balance before T2 read it → edge T1 → T2.
- T1 wrote the balance before T2 wrote it → reinforces T1 → T2.
+------+ +------+
| T1 | -------> | T2 |
+------+ +------+The graph flows in one direction — no cycles. It's a Directed Acyclic Graph (DAG), so the execution is proven conflict serializable: equivalent to running all of T1 first, then T2.
Scenario 2: The Invalid Execution
Timeline: T1 reads $100. T2 reads $100. T2 writes $110. T1 writes $50.
- T1 read the balance before T2 updated it → edge T1 → T2.
- T2 wrote the balance before T1 wrote it → edge T2 → T1.
+------+ +------+
| T1 | -------> | T2 |
| | <------- | |
+------+ +------+The graph contains a cycle (T1 → T2 → T1) — it is not a DAG. The loop proves the updates crossed paths illegally; the database detects it and rejects or aborts the execution.
The Catch: You Can't Build the DAG Upfront
So the DAG is the mechanism — a schedule with a cycle-free dependency graph is conflict serializable, and one with a cycle isn't. But there's a major practical hurdle: building the graph requires knowing the entire schedule of operations in advance. In real-world production databases, queries arrive dynamically from users in real time — the engine cannot predict what operations a transaction will send next.
Two-Phase Locking (2PL) is the classic pessimistic runtime protocol (invented by Jim Gray in the 1970s) that enforces conflict serializability dynamically as queries execute, without knowing upcoming operations ahead of time — by making cycle-forming schedules impossible to produce in the first place.
How Two-Phase Locking Works
To coordinate overlapping requests across cores, transactions talk to a centralized Lock Manager to acquire locks on database objects before reading or writing:
- Shared locks (S): requested when a transaction wants to read an object. Multiple transactions can hold shared locks on the same object at once.
- Exclusive locks (X): requested when a transaction wants to write/update an object. Only one transaction can hold an exclusive lock at a time — blocking all other readers and writers.
The Two Phases
To keep the runtime schedule cycle-free, 2PL breaks a transaction's lock usage into two strict, non-overlapping phases:
- Growing phase: the transaction requests and acquires locks from the Lock Manager as needed. It cannot release any locks during this phase.
- Shrinking phase: the instant the transaction releases its first lock, it enters the shrinking phase. From this moment it can only release existing locks — it is strictly forbidden from acquiring new ones.
By ensuring no transaction can acquire a new lock after releasing a previous one, 2PL mathematically guarantees the dynamic schedule is conflict serializable: the lock ordering can never form the circular wait pattern that showed up as a cycle in the dependency graph.
The Two Phases, By Example
Simply holding locks is not enough to guarantee serializability — if a transaction can acquire and release locks whenever it wants, another transaction can slip into the middle of its execution and read an inconsistent intermediate state. So let's run one scenario both ways: a bank with two accounts, each holding $1000 (total $2000):
- T1: transfer $100 from Account A to Account B.
- T2: calculate the total sum of both accounts (A + B).
Without the 2-Phase Rule ("Casual Locking")
- T1 acquires an exclusive lock on A, subtracts $100 (A = $900).
- T1 releases the lock on A — before it has touched B.
- T2 arrives to sum the accounts:
- Acquires a shared lock on A, reads $900, releases it.
- Acquires a shared lock on B, reads $1000 (T1 hasn't updated B yet), releases it.
- T2 outputs $900 + $1000 = $1900 — $100 has vanished.
- T1 resumes, acquires an exclusive lock on B, adds $100 (B = $1100).
Why it fails: if T1 ran completely first, T2 would see $900 + $1100 = $2000; if T2 ran first, it would see $1000 + $1000 = $2000. But because T1 dropped its lock on A early, T2 slipped into the middle: T2 saw T1's change on A (T1 → T2), while T1 executed after T2 on B (T2 → T1) — a cycle (T1 → T2 → T1) in the dependency graph. Non-serializable.
With Two-Phase Locking
- T1, growing phase: acquires an exclusive lock on A, subtracts $100 (A = $900). It needs to update B next — and under 2PL, it cannot release its lock on A while it still has locks to acquire. So it acquires an exclusive lock on B while still holding A.
- T2 arrives: requests a shared lock on A to start its sum. BLOCKED — the Lock Manager denies it because T1 still holds the exclusive lock. T2 waits in line.
- T1 completes: adds $100 to B (B = $1100), then enters its shrinking phase and releases both locks.
- T2 unblocks: acquires shared locks on A and B, reads $900 + $1100, and outputs $2000 — correct.
Why the Rule Guarantees Serializability
Forcing a transaction to hold its existing locks while acquiring new ones prevents anyone from sneaking into intermediate states. And once it releases its first lock, forbidding new acquisitions ensures all dependency arrows between conflicting operations flow strictly in one direction — no circular dependencies, so the execution is provably conflict serializable.
The Problem with Basic 2PL: Cascading Aborts
Basic 2PL guarantees serializability — but releasing exclusive locks before commit creates a severe runtime issue:
- Transaction 1 updates an object, enters its shrinking phase, and releases its exclusive lock before committing.
- Transaction 2 acquires the lock and reads Transaction 1's update — uncommitted dirty data.
- If Transaction 1 subsequently aborts or crashes, Transaction 2 has acted on data that legally never existed. Transaction 2 must also be aborted and rolled back — along with any other transactions that read from Transaction 2.
One aborted transaction can cascade through the system, taking innocent transactions down with it.
The Industry Standard: Strong Strict 2PL (SS2PL)
To eliminate cascading aborts, virtually all modern production databases use a stricter variation — Strong Strict Two-Phase Locking (SS2PL):
- The rule: a transaction holds all of its locks — shared and exclusive — until it completely commits or aborts.
- The result: the shrinking phase collapses into a single instantaneous event at the very end. Uncommitted writes are never exposed to other transactions, making cascading aborts and dirty reads impossible.
Pessimistic by Design
It's worth naming what 2PL fundamentally is: the classic pessimistic concurrency control protocol. And its opposite — Optimistic Concurrency Control (OCC / timestamp ordering) — is defined by an opposite assumption about the world.
The pessimistic approach (2PL): assume conflicts will happen often, so prevent them upfront. Before a transaction can read or write any record, it must request and hold a lock from the Lock Manager — and if another transaction holds a conflicting lock, the incoming transaction is blocked and forced to wait in line. High safety with no wasted work from aborts, but transactions spend a lot of time waiting in lock queues, which limits throughput on multi-core hardware.
The optimistic approach (OCC): assume conflicts are rare, so let everyone run freely and handle the rare conflicts at the end. Transactions take no locks — they execute reads and writes in private workspaces, and only when a transaction is ready to commit does the database perform a validation phase (using timestamps) to check whether a conflict occurred. If one did, the transaction is aborted and restarted. Excellent parallelism when conflicts are rare — but if many transactions contend on the same records, the constant aborts and restarts waste more CPU than locking ever would.
Which one wins depends entirely on the workload: 2PL when contention is high, OCC when it's low.
Related reads
- Concurrency Anomalies — the races 2PL exists to prevent, and the dependency-graph test it satisfies
- Optimistic Concurrency Control — the lock-free alternative for low-contention workloads
- Concurrency Control Theory in Databases — the problem statement, from processors up to ACID