Back
Deadlock

π What is Deadlock?
A Deadlock is a condition in which two or more transactions are waiting for each other to release the lock on the data they need. This causes the transaction process to get "stuck" π« and prevents any transaction from continuing.
π Example
Imagine there are two bank accounts, A and B, both with sufficient balance to make transfers. Hereβs how a deadlock might happen:
-
Transaction 1:
- π€ User A wants to transfer money to account B.
- π Transaction 1 acquires a lock on account A.
- π Transaction 1 then tries to acquire a lock on account B, but B is already locked by Transaction 2.
- β³ Transaction 1 must wait until Transaction 2 releases the lock on B.
-
Transaction 2:
- π€ User B wants to transfer money to account A.
- π Transaction 2 acquires a lock on account B.
- π Transaction 2 then tries to acquire a lock on account A, but A is already locked by Transaction 1.
- β³ Transaction 2 must wait until Transaction 1 releases the lock on A.
β οΈ Deadlock Situation
- Both transactions wait for each other: Transaction 1 waits for Transaction 2 to release the lock on B, while Transaction 2 waits for Transaction 1 to release the lock on A.
- No progress: Because both transactions are waiting, neither can complete. The system appears to be in a "stuck" π« deadlock state.
β Why Does Deadlock Happen?
- Different order of data access: When transactions access data in different sequences, conflicts over locks can arise.
- Lack of deadlock prevention mechanisms: If the database lacks the ability to detect or prevent deadlocks, this condition can easily occur.
π How To Prevent Deadlock?
- Assign a lock sequence: Define a strict order for acquiring locks on resources. For example, always lock accounts with smaller IDs first π’.
- Use timeout: Set a timeout β° for waiting on locks. If a transaction doesnβt acquire a lock within the allotted time, itβs canceled and can retry later.
- Detect and resolve deadlocks: Enable the database system to automatically detect deadlock conditions and choose one transaction to cancel so others can proceed.
π The Importance of Preventing Deadlock
Deadlocks can degrade the databaseβs performance π and even lead to inconsistent data. Understanding the deadlock mechanism and applying preventive strategies is essential for reliable database management.