SQL & Relational Databases (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
Database Deadlocks: Detection and Resolution.
senior LevelDatabases & SQL
In Simple Words: A Deadlock occurs when Transaction 1 holds Lock A and waits for Lock B, while Transaction 2 holds Lock B and waits for Lock A:
- Detection: The database engine runs background deadlock detection (evaluating a Wait-For Graph for cycles) and kills the transaction with lower cost, returning error code
40P01(Postgres) or1213(MySQL). - Prevention: Always access and lock resources in a consistent, uniform order across all services (e.g. always lock user IDs in ascending order
WHERE id IN (1, 2) ORDER BY id ASC).