🗄️ Databases

Deadlock

Deadlock

A state in which two or more processes wait indefinitely for each other's resources.

📖 Detailed Explanation

Deadlock is a state in which two or more transactions wait for resources held by each other and can never proceed. For example, a deadlock occurs when Transaction A locks Table X and then requests Table Y, while Transaction B locks Table Y and then requests Table X.

The four necessary conditions for a deadlock are mutual exclusion (only one can use it at a time), hold and wait (requesting others while holding one), no preemption (cannot be forcibly reclaimed), and circular wait (waiting in a circle). Breaking any one of these can prevent a deadlock.

Most DBMSs detect deadlocks automatically and resolve them by rolling back the transaction with the lowest cost. The application must implement retry logic.

💻 Code Example

-- 데드락 발생 시나리오
-- 트랜잭션 A
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1; -- A가 row 1 락
UPDATE accounts SET balance = balance + 100 WHERE id = 2; -- B의 락 대기

-- 트랜잭션 B (동시 실행)
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE id = 2;  -- B가 row 2 락
UPDATE accounts SET balance = balance + 50 WHERE id = 1;  -- A의 락 대기 → DEADLOCK!

-- 해결책: 일관된 순서로 락 획득
-- 항상 id가 작은 것부터 처리
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

-- Python에서 재시도 로직
import time
from sqlalchemy.exc import OperationalError

def transfer_with_retry(from_id, to_id, amount, max_retries=3):
    for attempt in range(max_retries):
        try:
            with db.begin():
                # 일관된 순서로 락 획득
                ids = sorted([from_id, to_id])
                db.execute(f"SELECT * FROM accounts WHERE id IN ({ids}) FOR UPDATE")
                db.execute(f"UPDATE accounts SET balance = balance - {amount} WHERE id = {from_id}")
                db.execute(f"UPDATE accounts SET balance = balance + {amount} WHERE id = {to_id}")
            return True
        except OperationalError as e:
            if "deadlock" in str(e).lower() and attempt < max_retries - 1:
                time.sleep(0.1 * (2 ** attempt))  # 지수 백오프
                continue
            raise

🗣️ Examples of Practical Conversations

Operations team: "We're seeing intermittent deadlock errors in the payment system."

DBA: "I checked with SHOW ENGINE INNODB STATUS, and the order of the point deduction and the balance update is different between them."

Backend developer: "So the lock order gets tangled during concurrent payments. I'll change it to always acquire locks in user_id order."

DBA: "Also, try narrowing the transaction scope. Move external API calls outside the transaction."

Interviewer: "Please explain the conditions under which a deadlock occurs and how to prevent it."

Candidate: "It occurs when four conditions are satisfied at the same time: mutual exclusion, hold and wait, no preemption, and circular wait. To prevent it, acquire resources in a consistent order, minimize the transaction scope, and set timeouts."

Interviewer: "What about resolving it after detection?"

Candidate: "The DBMS detects it automatically and rolls one back, and then the application retries with exponential backoff."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Reviewer: "Looking at this code, it first updates the orders table and then updates the inventory table..."

Developer: "Yes, it's the order creation logic."

Reviewer: "But in the cancellation logic, it restores the inventory first and then changes the order status. If they run concurrently, a deadlock is possible."

Developer: "Ah, we need to align the lock order. I'll change cancellation to go in the order → inventory sequence as well."

⚠️ Cautions

🔗 Related Terms

📚 Learn More