AI Glossary / Data engineering and architecture / Intermediate
Two-phase locking
Definition
Two-phase locking, or 2PL, is a database concurrency-control protocol that divides each transaction's lock use into two phases. During the growing phase it may acquire locks but release none. After releasing its first lock, it enters the shrinking phase and may release locks but acquire no new ones. With appropriate locking of conflicting operations, this produces conflict-serializable execution schedules.
What it means
Transactions often run concurrently, yet their combined effects should respect the intended consistency rules. Locks regulate access when operations could interfere. A shared lock can permit compatible readers; an exclusive lock protects a write from conflicting access.
The two-phase rule governs when these locks may be acquired and released. It does not mean “take exactly two locks” or “run exactly two transactions.” It also differs from two-phase commit, which coordinates commit or abort across participants. A database may use commitment and concurrency mechanisms together because they solve different problems.
How it works
A transaction requests the locks required for its operations. A lock manager checks compatibility with locks already held by other transactions and grants the request or makes it wait. During the growing phase, the transaction can obtain additional locks as needed.
Once it releases a lock, it cannot acquire another under basic 2PL. This restriction prevents certain problematic interleavings. It does not require every transaction to execute alone, because compatible operations can still proceed concurrently.
Variants add stronger retention rules. Strict 2PL holds exclusive locks until commit or abort, avoiding cascading rollbacks caused by other transactions using uncommitted writes. Rigorous, or strong strict, 2PL holds all locks until that point. Basic 2PL can still deadlock. Correct serializable treatment of queries also requires protecting the relevant conflicts, including ranges or predicates where necessary, rather than assuming row locks cover every possible insertion.
Three practical examples
1. Stock allocation: Two transactions attempt to reduce the same available quantity. Appropriate conflicting locks prevent them from independently updating the item as though the other's change did not exist.
2. Coordinated record changes: A transaction updates two related records while another operation reads them. Locking and the selected isolation behavior determine whether the reader can observe an inappropriate intermediate combination.
3. Database diagnosis: Engineers inspect a blocking chain and determine which transaction holds a needed lock. Understanding lock retention helps explain why a seemingly idle application can delay other work until its transaction finishes.
Think of it this way
Think of a workshop rule under which a job can collect tools until it returns its first tool; after that, it may only return tools. This creates a clear boundary between gathering access rights and relinquishing them.
The analogy has limits. Database locks have compatibility modes and can protect logical conditions as well as individual records. The tool rule also does not prevent two jobs from waiting on tools held by each other. Deadlock handling remains a separate requirement.
Worked example
Suppose transaction T1 needs exclusive locks on records A and B. It acquires A, then B, updates both and releases them. This sequence obeys 2PL because all acquisitions occur before the first release.
Now consider a sequence in which T1 acquires A, updates A, releases A and then requests B. That request violates 2PL: releasing A already started the shrinking phase. The issue is the order of lock operations, not whether B happens to be available.
For a deadlock example, T1 holds A and requests B while T2 holds B and requests A. Both transactions are still in their growing phases, so neither has violated the basic rule. Yet neither can proceed. The database needs detection and recovery or a prevention policy. Following 2PL ensures a scheduling property; it does not automatically guarantee progress without additional mechanisms.
Illustrative case study
Fictional case study: LockMeadow adds a reporting screen to an inventory application. One application path begins a transaction, updates a record and then waits for a user to confirm another screen. Under its lock-retention behavior, that transaction continues blocking an unrelated user's conflicting update.
The team moves the human decision outside the short database transaction and rechecks the necessary conditions when it performs the final update. It also tests retry behavior after deadlock-related aborts rather than assuming every attempt succeeds.
LockMeadow learns that correct concurrency control and good transaction design are complementary. Removing locks indiscriminately would risk incorrect results; keeping transactions focused reduces unnecessary waiting while preserving the database's consistency mechanisms.
Common misconceptions and mistakes
A common mistake is confusing two-phase locking with two-phase commit. Another is assuming that any use of locks ensures serializability, regardless of when they are released or whether all relevant conflicts are protected.
Do not assume basic 2PL is deadlock-free or that it automatically prevents every cascading rollback. The strict variants add important rules. Also avoid treating every delay as a deadlock: a transaction waiting for another that can still progress is blocked, but there may be no cycle. Diagnosis should distinguish ordinary contention from a genuine circular wait.
Business use
Two-phase locking helps explain how transactional systems protect consistent results while allowing concurrency. For businesses, its effects appear in reliable updates, waiting times and occasional transaction retries.
Application teams should keep transactions appropriately short, understand the database's actual isolation and locking behavior, and handle documented retryable failures. Useful monitoring includes lock wait duration, long-running transactions and deadlock events. For data pipelines and AI-serving applications, avoid leaving database transactions open while performing slow external computation unless that scope is deliberately required and tested. Optimize the transaction boundary without discarding the consistency rule it protects.
People also ask
Does 2PL mean a transaction takes two locks?
No. The two phases describe acquisition and release behavior; a transaction can use many locks.
Can transactions deadlock while following 2PL?
Yes. They can each hold a lock needed by the other, so a separate deadlock strategy is necessary.
What does strict 2PL add?
It retains exclusive locks until commit or abort, preventing other transactions from reading or overwriting those uncommitted writes through conflicting access.
Check your understanding
A transaction releases one lock and later acquires a different lock. Does it obey basic two-phase locking?
Answer: No. The first release begins the shrinking phase, during which new locks cannot be acquired.
Related terms
- Concurrency control
- shared lock
- exclusive lock
- serializability
- deadlock
- transaction isolation
- two-phase commit
- cascading rollback
Learn next
Draw the lock-acquisition and release sequence for two transactions touching the same records. Check the phase rule, then separately inspect whether their waiting relationships can form a cycle.
More in Data engineering and architecture
- Tuple Type - A tuple type describes the structure of a tuple or record: its component attributes or fields and their associated types.
- Tuple-versioning - Tuple-versioning retains multiple versions of a database row, or tuple, to represent changes over time.
- Two-phase commit protocol - The two-phase commit protocol, or 2PC, coordinates an all-or-nothing decision for a transaction involving multiple transactional participants.
- Type - token distinction - The type - token distinction separates a repeatable kind or pattern from a particular instance of it.
- Unavoidable Redundancy - Unavoidable redundancy is a descriptive term for repeated information that cannot simply be removed by a proposed normalization decomposition without losing...
- Uncertain database - An uncertain database represents information whose value, existence or interpretation is not fully settled.
Sources
Silberschatz, Korth and Sudarshan, Database System Concepts, concurrency-control slides: https://www.db-book.com/slides-dir/PDF-dir/ch18.pdf
Carnegie Mellon University, two-phase-locking lecture notes: https://15445.courses.cs.cmu.edu/spring2026/notes/18-twophaselocking.pdf
The textbook source supplies the strict-versus-rigorous distinction. Record sequences and LockMeadow are fictional; actual lock modes, range protection and transaction behavior depend on the database and configuration.
Previous: Two-phase commit protocol Next: Two-proportion Z-test