Two-phase locking

Also known as: 2PL

On this page 7

Two-phase locking (2PL) is a concurrency control protocol in which every transaction acquires all the locks it needs before it releases any lock, dividing its life into a growing phase and a shrinking phase. In databases, this simple rule is enough to guarantee conflict serializability, meaning that concurrent transactions produce the same result as some serial order of execution.

2PL is the classical foundation of pessimistic concurrency control and of the serializable isolation level in many relational systems. It should not be confused with two-phase commit, a separate protocol that coordinates atomic commitment across several nodes in a distributed transaction.

How the two phases of locking work

During the growing phase, a transaction may request new locks but may not release any. The moment it releases its first lock, it enters the shrinking phase, in which it may release locks but may never acquire another. The point at which the transaction holds its maximum set of locks is called the lock point, and the serial order of transactions corresponds to the order of their lock points.

Locks come in modes. A shared lock allows other readers but blocks writers, and an exclusive lock blocks every other transaction. A lock manager grants or delays requests according to a compatibility matrix, shown in simplified form below.

Requested lockHeld shared lockHeld exclusive lock
Shared (S)GrantedWaits
Exclusive (X)WaitsWaits
Intention shared (IS)GrantedWaits
Intention exclusive (IX)WaitsWaits
Basic lock compatibility matrix

Real engines add intention locks and multiple granularities, such as table, page and row, so that a transaction locking one row signals its presence at the table level. This multiple granularity locking scheme lets the lock manager detect conflicts without inspecting every row lock.

Variants of two-phase locking

Basic 2PL guarantees serializability but not recoverability. If a transaction releases an exclusive lock before committing and later aborts, other transactions may already have read its uncommitted data, causing cascading aborts. Stricter variants close this gap by delaying when locks are released.

VariantLock release ruleKey property
Basic 2PLAny time after the lock pointSerializable, cascading aborts possible
Strict 2PLExclusive locks held until commit or abortNo dirty reads, recoverable
Strong strict 2PL (rigorous)All locks held until commit or abortCommit order equals serial order
Conservative 2PLAll locks acquired before execution startsDeadlock-free, low concurrency
Main variants of 2PL

Most production databases that use locking implement strict or rigorous 2PL, because releasing locks only at commit makes recovery straightforward. Conservative 2PL is rare in general-purpose systems, since a transaction seldom knows its full set of data items in advance.

Deadlocks and how databases resolve them

Two-phase locking does not prevent deadlocks. If transaction A holds a lock on row 1 and waits for row 2 while transaction B holds row 2 and waits for row 1, neither can proceed. Databases therefore combine 2PL with a deadlock handling strategy.

ApproachMechanismTrade-off
Wait-for graph detectionPeriodically search for cycles and abort a victimAccurate, some detection delay
Lock timeoutAbort a transaction waiting longer than a limitSimple, may abort without a real deadlock
Wait-dieOlder transactions wait, younger ones abortPrevents cycles using timestamps
Wound-waitOlder transactions force younger ones to abortFewer restarts for long transactions
Deadlock handling approaches used with 2PL

Applications must be written to retry aborted transactions, because a deadlock victim receives an error even though it did nothing wrong. Acquiring locks in a consistent global order, for example by primary key, greatly reduces deadlock frequency.

Two-phase locking compared with other concurrency controls

Two-phase locking competes with multiversion concurrency control (MVCC) and optimistic locking, and many modern engines combine these approaches. The key difference is whether conflicts are prevented by blocking or detected and resolved after the fact.

MethodReaders block writersTypical strengthTypical weakness
Two-phase lockingYesSimple serializability guaranteeBlocking and deadlocks
MVCC with snapshot isolationNoHigh read concurrencyWrite skew is possible
Serializable snapshot isolationNoSerializable without read locksAborts under contention
Optimistic lockingNoCheap when conflicts are rareWasted work when conflicts occur
2PL and alternative concurrency controls

Some systems apply 2PL only to writes and serve reads from snapshots. In these hybrid designs, write locks still follow strict 2PL while readers see consistent versions without blocking, a combination common in widely used relational databases.

Practical limitations and phantom anomalies

Locking individual rows is not sufficient to prevent the phantom read anomaly. If a transaction locks all rows matching a condition, another transaction can still insert a new matching row. Full serializability therefore requires predicate locks, index-range locks or next-key locks that cover gaps between existing keys.

  • Long transactions hold locks for a long time and block many others.
  • Hot rows, such as a shared counter, serialize all transactions that touch them.
  • Lock escalation from rows to a table can unexpectedly reduce concurrency.
  • Distributed 2PL requires global deadlock detection, which adds network latency.

Despite these costs, 2PL remains attractive because its guarantees are easy to reason about. When correctness under concurrent updates outweighs raw throughput, a locking approach often produces fewer surprising anomalies than weaker isolation levels.

The simple explanation

Two-phase locking is a rule that keeps database changes from colliding. Before a task touches a piece of data, it puts a lock on it. The rule is simple: once a task starts giving locks back, it may not take any new ones.

Picture a librarian who borrows several reference books for a project. She collects every book she needs first. Only after that does she start returning them. Nobody else can change those books in the middle of her work. Because everyone follows the same rule, the final result matches a careful one-at-a-time order.

How it is used in practice

An online ticketing platform sells seats for a concert with 5,000 seats and tens of thousands of buyers arriving within the first minute. Each purchase transaction reads a seat, checks that it is free, marks it as sold and creates an order record. Without proper concurrency control, two buyers could both see the same seat as free and both pay for it.

The database runs these purchases at the serializable level using strict two-phase locking with exclusive row locks. The first transaction to lock a seat holds the lock until it commits, so a competing buyer waits and then sees the seat as sold. Occasional deadlocks between multi-seat orders are detected by the lock manager, and the application retries the losing transaction up to three times.

To keep waiting short, the developers lock seats in ascending seat number order and keep each transaction under a few milliseconds. The result is zero double-booked seats during the sale, with only a small fraction of purchases needing a retry.