</> MAANG.io
system design · 201

Intermediate

Master system design interviews with scalable architecture patterns, distributed systems, and real-world design challenges.

0/124 solved 0% complete

Two-Phase Locking (2PL)

maang.io System Design Series


Two-phase locking is the textbook mechanism for serializable transactions: a transaction first only acquires locks (the growing phase), then only releases them (the shrinking phase) — never acquiring after releasing. That discipline guarantees a serializable schedule, at the cost of deadlocks, which the database detects and breaks. It's the counterpoint to MVCC and a pillar of the ACID story.

This deep dive comes in three parts:

  • Foundations & Core Concepts — shared/exclusive locks, the two phases, and strict 2PL.
  • Internals — deadlock detection, predicate locks for phantoms, and the MVCC contrast, with worked numbers.
  • Interview — Staff/Principal Q&A: isolation levels, deadlock handling, and locking vs MVCC.

Two-Phase Locking (2PL) — Part 2: Internals & Implementation

maang.io System Design Series


What is this?

Back to our shared reference library. In Part 1 the librarian's rules kept our reports consistent. Now go behind the front desk and watch the machinery: the card catalog the librarian uses to track who holds which card for which book, the waiting list taped beside each contested book, and — the ugly case — what happens when two researchers each refuse to hand back the one book the other is standing there waiting for. That standoff has a name (a deadlock), and how the library breaks it (someone gets tapped on the shoulder and told to start over) is where the real engineering lives.

That card catalog is the lock manager, and its central data structure is the lock table. Everything in this chapter hangs off it.

The one-line idea: the lock manager is a big in-memory hash table from "which row" to "who holds a lock, in what mode, and who's queued behind them." Granting a lock is a hash lookup plus a compatibility check; the hard parts are detecting deadlocks in the wait queues and stopping phantoms that no row-level lock can catch.


Sign in to continue reading

The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.

Sign in to read the full lesson

Sign in to MAANG.io

Use your Google or Microsoft account — no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.