Bird
Raised Fist0
Interview Prepdatabase-management-systemshardGoogleAmazonFlipkartSwiggy

Two-Phase Locking (2PL) - Shared, Exclusive, Deadlock

Choose your preparation mode3 modes available
🎯
Two-Phase Locking (2PL) - Shared, Exclusive, Deadlock
hardDBMSGoogleAmazonFlipkart

Imagine multiple bank tellers updating the same account balance simultaneously without coordination - chaos and errors ensue. Two-Phase Locking is the protocol that ensures order and consistency in such concurrent transactions.

💡 Beginners often confuse locking with blocking or think locks are always exclusive; they also underestimate how deadlocks arise from lock management, leading to incomplete or incorrect explanations.
📋
Interview Question

Explain the Two-Phase Locking protocol, including the roles of shared and exclusive locks, and how deadlocks can occur and be handled in this context.

Locking protocols to ensure serializabilityDifference between shared (read) and exclusive (write) locksDeadlock conditions and detection in locking
💡
Scenario & Trace
ScenarioTwo transactions T1 and T2 both want to read and then update the same database record concurrently.
T1 acquires a shared lock to read the record → T2 requests a shared lock and is granted since shared locks are compatible → T1 upgrades to an exclusive lock to update the record → T2 waits because exclusive lock conflicts with shared lock → T1 commits and releases locks → T2 acquires exclusive lock and proceeds.
ScenarioTwo transactions each hold a lock the other needs, causing a deadlock.
T1 holds exclusive lock on record A and requests exclusive lock on record B → T2 holds exclusive lock on record B and requests exclusive lock on record A → both transactions wait indefinitely for the other to release locks → deadlock detected and one transaction is aborted to resolve.
  • What if a transaction tries to acquire a lock it already holds?
  • What happens if a transaction never releases locks (e.g., due to crash)?
  • How does lock compatibility affect concurrency and deadlock likelihood?
⚠️
Common Mistakes
Confusing shared and exclusive locks as the same

Interviewer doubts your grasp of concurrency control basics

✅ Clearly differentiate that shared locks allow concurrent reads, exclusive locks allow only one writer

Assuming locks can be acquired and released in any order

You miss the core two-phase property that ensures serializability

✅ Understand and emphasize the growing and shrinking phases with no lock acquisition after release

Ignoring deadlocks or thinking 2PL prevents them entirely

Interviewer sees incomplete understanding of concurrency hazards

✅ Explain that 2PL can cause deadlocks and describe detection and resolution methods

Not mentioning lock upgrades and their risks

You miss an important nuance that can cause deadlocks

✅ Discuss how upgrading from shared to exclusive locks can lead to deadlocks if not managed carefully

🧠
Basic Definition - What It Is
💡 This level covers the essential concept you must know to answer basic interview questions confidently.

Intuition

Two-Phase Locking is a protocol that ensures transactions acquire locks in two phases to maintain database consistency.

Explanation

Two-Phase Locking (2PL) is a concurrency control method used in databases to ensure serializability of transactions. It divides the transaction's locking activity into two distinct phases: the growing phase, where locks are acquired and no locks are released, and the shrinking phase, where locks are released and no new locks are acquired. Shared locks allow multiple transactions to read a resource concurrently, while exclusive locks prevent others from reading or writing. This protocol prevents conflicts that could lead to inconsistent data.

Memory Hook

💡 Think of 2PL as a 'lock ladder' you climb up acquiring locks, then climb down releasing them - no going back up once you start down.

Interview Questions

❓ What are the two phases in Two-Phase Locking?
  • Growing phase: acquiring locks only
  • Shrinking phase: releasing locks only
⏱
Depth Level
Interview Time30 seconds
Depthbasic

Covers the fundamental definition and purpose of 2PL, sufficient for screening rounds.

Interview Target: Minimum floor - never go below this

Knowing only this will help you pass initial screening but is insufficient for deeper technical rounds.

🧠
Mechanism Depth - How It Works
💡 This level is expected in product company interviews and demonstrates a solid understanding of 2PL internals.

Intuition

2PL manages locks carefully to ensure serializability by controlling when locks can be acquired and released, using shared and exclusive locks to balance concurrency and consistency.

Explanation

In Two-Phase Locking, transactions first enter the growing phase where they acquire shared locks for reading and exclusive locks for writing. Shared locks are compatible with other shared locks, allowing concurrent reads, but exclusive locks are exclusive to prevent conflicts during writes. Once a transaction releases any lock, it enters the shrinking phase and cannot acquire new locks, ensuring a strict order of operations that guarantees serializability. Deadlocks can occur when transactions wait indefinitely for locks held by each other; these are detected by wait-for graphs or timeouts and resolved by aborting one of the transactions. Lock upgrades (from shared to exclusive) must be handled carefully to avoid deadlocks.

Memory Hook

💡 Imagine a traffic intersection controlled by traffic lights (locks) that allow cars (transactions) to pass safely without collisions (conflicts).

Interview Questions

❓ How do shared and exclusive locks differ and interact in 2PL?
  • Shared locks allow multiple concurrent readers
  • Exclusive locks allow only one writer and block others
  • Shared and exclusive locks conflict, blocking incompatible access
❓ Explain how deadlocks arise in 2PL and how they are resolved.
  • Deadlocks occur when transactions wait cyclically for locks held by each other
  • Detection via wait-for graphs or timeouts
  • Resolution by aborting one transaction to break the cycle
⏱
Depth Level
Interview Time2-3 minutes
Depthintermediate

Demonstrates understanding of lock types, phases, deadlock conditions, and resolution strategies.

Interview Target: Target level for FAANG on-sites

Mastering this level distinguishes you from most candidates and prepares you for detailed concurrency questions.

📊
Explanation Depth Levels
💡 Choose your explanation depth based on the interview stage and company expectations.
LevelInterview TimeSuitable ForRisk
Basic Definition30sScreening call or initial roundsToo shallow for on-site or deep technical rounds
Mechanism Depth2-3 minutesOn-site interviews at FAANG and top product companiesRequires solid understanding; missing details can cost you
💼
Interview Strategy
💡 Use this guide to structure your explanation clearly and confidently before every mock or real interview.

How to Present

Start with a clear definition of Two-Phase Locking and its purpose.Give a simple example or analogy to illustrate shared and exclusive locks.Explain the growing and shrinking phases and how they ensure serializability.Discuss deadlocks: how they occur, how to detect, and how to resolve them.Mention edge cases like lock upgrades and transaction crashes.

Time Allocation

Definition: 30s → Example: 1min → Mechanism: 2min → Edge cases: 30s. Total ~4min

What the Interviewer Tests

Interviewer checks your understanding of concurrency control, lock compatibility, deadlock scenarios, and your ability to explain complex interactions clearly.

Common Follow-ups

  • What happens if a transaction tries to acquire a lock it already holds? → It can proceed or upgrade the lock if allowed.
  • How does 2PL guarantee serializability? → By preventing cycles in the precedence graph through lock ordering.
💡 These are common curveballs that test your depth beyond the basic protocol.
🔍
Pattern Recognition

When to Use

Interviewers ask about 2PL when testing knowledge of transaction concurrency control, serializability, and deadlock handling.

Signature Phrases

'Explain Two-Phase Locking and its phases''Compare shared and exclusive locks''What happens when two transactions deadlock?'

NOT This Pattern When

Similar Problems

Practice

(1/5)
1. Trace the sequence of events when two transactions concurrently update the same row under pessimistic locking with row-level locks. What happens if the second transaction tries to acquire the lock while the first holds it?
easy
A. The second transaction immediately aborts with a deadlock error
B. The second transaction acquires a shared lock and reads the row but cannot update
C. The second transaction proceeds and overwrites the first transaction's changes
D. The second transaction waits until the first transaction commits or rolls back

Solution

  1. Step 1: Understand pessimistic locking behavior

    Pessimistic locking blocks conflicting operations to prevent concurrency issues.
  2. Step 2: Analyze lock acquisition

    When the first transaction holds an exclusive row-level lock, the second transaction must wait to acquire the same exclusive lock.
  3. Step 3: Outcome of concurrent update attempts

    The second transaction is blocked until the first commits or rolls back, releasing the lock.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Waiting prevents dirty writes and ensures serializability under pessimistic concurrency control.
Hint: Pessimistic locks cause waiting, not immediate aborts or overwrites.
Common Mistakes:
  • Thinking the second transaction aborts immediately
  • Assuming the second transaction can overwrite without waiting
  • Confusing shared and exclusive locks in updates
2. You are designing a database for a university system. Which scenario best indicates the need for a many-to-many (N:M) relationship between entities?
easy
A. Each student has exactly one student ID.
B. Each classroom is assigned to only one course at a time.
C. Each professor teaches only one course.
D. Each student can enroll in multiple courses, and each course can have multiple students.

Solution

  1. Step 1: Identify the entities involved

    Students and Courses are entities.
  2. Step 2: Analyze the relationship cardinality

    Students can enroll in multiple courses, and courses can have multiple students, indicating a many-to-many relationship.
  3. Step 3: Evaluate other options

    Each student has exactly one student ID describes a 1:1 attribute, not a relationship. Each professor teaches only one course is a 1:1 or 1:N but not N:M. Each classroom is assigned to only one course at a time is a 1:1 or 1:N scenario.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Many-to-many relationships occur when multiple instances of one entity relate to multiple instances of another.
Hint: N:M relationships occur when both sides can have multiple related entities.
Common Mistakes:
  • Confusing unique attributes with relationships
  • Assuming 1:N when both sides can have multiple connections
3. You have a relation R with attributes ABCD and functional dependencies F = {A -> B, B -> C}. You want to decompose R into smaller relations while ensuring no data loss. In which scenario would you prioritize a lossless join decomposition over dependency preservation?
easy
A. When all functional dependencies must be preserved at the cost of possible data loss during joins
B. When the schema is already in BCNF and no further decomposition is needed
C. When the primary goal is to avoid redundant data and anomalies, even if some dependencies are not preserved
D. When the relation has no functional dependencies and normalization is unnecessary

Solution

  1. Step 1: Understand lossless join vs dependency preservation

    Lossless join ensures no spurious tuples after decomposition, while dependency preservation ensures all FDs are enforceable without joins.
  2. Step 2: Analyze the trade-off

    Sometimes, to achieve lossless join, some dependencies may not be preserved in decomposed relations.
  3. Step 3: Scenario matching

    When avoiding data anomalies is critical, lossless join is prioritized even if some dependencies are lost.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    When all functional dependencies must be preserved at the cost of possible data loss during joins reverses the priorities, C and D are irrelevant to the scenario.
Hint: Lossless join prevents data loss; dependency preservation keeps all FDs enforceable.
Common Mistakes:
  • Confusing dependency preservation as more important than lossless join always
  • Assuming BCNF always guarantees dependency preservation
  • Believing relations without FDs need normalization
4. In which scenario is MVCC most beneficial compared to traditional locking mechanisms in a database system?
easy
A. When strict serializability is required and no stale reads are allowed
B. When transactions are short-lived and mostly write-heavy with minimal reads
C. When many concurrent transactions perform mostly read operations with occasional writes
D. When the database workload consists primarily of batch updates with no concurrent reads

Solution

  1. Step 1: Understand MVCC's strength in concurrency

    MVCC allows readers to access snapshot versions without blocking writers, making it ideal for workloads with many reads and fewer writes.
  2. Step 2: Analyze write-heavy workloads

    Write-heavy workloads with minimal reads benefit less from MVCC since version maintenance overhead can be costly.
  3. Step 3: Analyze batch updates without concurrent reads

    Batch updates without concurrent reads do not leverage MVCC's snapshot isolation benefits.
  4. Step 4: Analyze strict serializability requirements

    MVCC provides snapshot isolation, which may allow some anomalies; strict serializability requires stronger mechanisms.
  5. Final Answer:

    Option C -> Option C
  6. Quick Check:

    MVCC shines in read-heavy concurrent environments [OK]
Hint: MVCC excels when many reads coexist with some writes
Common Mistakes:
  • Assuming MVCC is best for write-heavy workloads
  • Confusing snapshot isolation with strict serializability
  • Believing MVCC is unnecessary without concurrent reads
5. You have a SQL query with multiple clauses: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, and LIMIT. To correctly process the query and produce the expected result, which approach best models the order in which these clauses are logically executed by the database engine?
easy
A. Execute clauses in the written order from top to bottom as they appear in the query.
B. Execute clauses in the logical order: FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT.
C. Execute all filtering clauses first (WHERE and HAVING), then grouping, then selection, ignoring FROM order.
D. Execute SELECT first to identify columns, then FROM to get tables, then apply filters and limits.

Solution

  1. Step 1: Understand SQL logical execution order

    SQL does not execute clauses in the written order. Instead, it first identifies data sources (FROM), then filters rows (WHERE), groups rows (GROUP BY), filters groups (HAVING), selects columns (SELECT), orders results (ORDER BY), and finally limits output rows (LIMIT).
  2. Step 2: Match problem description to logical execution order

    The logical order ensures correct filtering and grouping before selection and ordering, which matches Execute clauses in the logical order: FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT exactly.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Logical execution order matches database engine processing [OK]
Hint: SQL executes clauses logically, not in written order [OK]
Common Mistakes:
  • Assuming SQL executes clauses top-to-bottom as written
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard