← Back

Two-Phase Locking

9 min read

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:

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:

  1. Transaction 1 reads the account balance and updates it.
  2. 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:

  1. Transaction 1 reads the initial balance — $100.
  2. Before Transaction 1 can save, Transaction 2 also reads $100.
  3. Transaction 2 adds $10 and writes $110 back.
  4. 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:

  1. Each transaction becomes a node.
  2. 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.

text
+------+          +------+
|  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.

text
+------+          +------+
|  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:

The Two Phases

To keep the runtime schedule cycle-free, 2PL breaks a transaction's lock usage into two strict, non-overlapping phases:

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):

Without the 2-Phase Rule ("Casual Locking")

  1. T1 acquires an exclusive lock on A, subtracts $100 (A = $900).
  2. T1 releases the lock on A — before it has touched B.
  3. 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.
  4. 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

  1. 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.
  2. 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.
  3. T1 completes: adds $100 to B (B = $1100), then enters its shrinking phase and releases both locks.
  4. 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:

  1. Transaction 1 updates an object, enters its shrinking phase, and releases its exclusive lock before committing.
  2. Transaction 2 acquires the lock and reads Transaction 1's update — uncommitted dirty data.
  3. 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):

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.