SQL & Relational Databases (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
What is a Deadlock and how do databases detect and resolve them?
senior LevelDatabases & SQL
In Simple Words: A deadlock is a circular lock wait dependency where Transaction A waits for a resource locked by Transaction B, and Transaction B waits for a resource locked by Transaction A:
- Detection: The database maintains a Wait-For Graph. Cycles in the graph indicate deadlocks.
- Resolution: The engine aborts ("kills") one of the transactions (the Victim, typically the one that has done the least work) with an error (
Transaction rolled back), allowing the other transaction to complete. - Prevention: Always access and lock resources in the exact same alphabetical/numerical order across all application transactions!