Question #44 of 60•Databases•Medium• ~3 min read

How do Database Deadlocks occur and how do engines detect and resolve them?

Executive Takeaway

Examine lock wait graphs, lock timeouts, and transaction ordering strategies to prevent database deadlocks.

Architectural Breakdown & AnalysisFAANG Aligned

A Deadlock occurs when two or more database transactions hold locks on records that the other transactions need, creating a circular wait state.

Deadlock Scenario

  • Tx A locks Row 1, requests lock on Row 2.
  • Tx B locks Row 2, requests lock on Row 1.
  • Neither transaction can proceed.

Resolution Strategies

  1. Wait-For Graph Detection: DB engine maintains a directed graph of transactions waiting for locks. If a cycle is detected, the engine aborts the victim transaction with a lower execution cost.
  2. Lock Timeout: Aborts any transaction that waits longer than lock_timeout (e.g. 5s).
TIP — Prevention Strategy

Always acquire locks on multiple tables or rows in the exact same deterministic order across application code routines.

Key Architectural Comparison

Deadlock StrategyDetection MechanismResolution ActionPerformance Impact
Wait-For Graph Cycle DetectionDatabase engine traverses directed dependency graph.Aborts the "victim" transaction with least work done.Low background overhead.
Lock TimeoutTimer expires if lock cannot be acquired within threshold.Aborts waiting query and rolls back transaction.Simple, but can cause false aborts under heavy load.
Deterministic OrderingApplication code acquires locks in identical alphabetical order.Prevents deadlocks from ever forming.Zero database aborts; requires strict coding hygiene.
Previous QuestionHow do Leaky Bucket, Token Bucket, and Fixed Window Rate Limiting algorithms compare?Next Question How do you design an In-Memory Key-Value Store (Redis Architecture)?

Continue Learning on Being SDE

Explore deep-dive system architecture modules, low-level object-oriented designs, and interview cheat sheets.