Database Deadlock: The Two-Way Standoff

A deadlock is a 'Mexican standoff' where two transactions can't finish because each is waiting for a resource the other has locked. This happens in systems with concurrent writes. The database will kill one transaction, forcing your app to handle the retry.
WHY IT EXISTS Databases must guarantee that concurrent transactions don't corrupt data. This property, called isolation, is often enforced using locks. A lock prevents one transaction from changing data that another transaction is in the middle of using. While essential for data integrity, this locking mechanism creates the risk of deadlocks.
THE MENTAL MODEL Imagine two people, Alice and Bob, who each need to sign two documents, Doc1 and Doc2, to complete their work. Alice grabs Doc1 and Bob grabs Doc2. Now, Alice needs Doc2 to finish, but Bob has it. At the same time, Bob needs Doc1, but Alice has it. Neither will let go of the document they hold. They are stuck, waiting forever for a resource the other person has. This is a deadlock.
HOW IT WORKS A deadlock occurs when two or more transactions form a circular chain of dependencies. Transaction A is waiting for a resource locked by Transaction B, which in turn is waiting for a resource locked by Transaction A. Neither can move forward. The database's deadlock detector periodically checks for these cycles. When it finds one, it breaks the stalemate by choosing one transaction as the 'victim,' aborting it, and rolling back all its changes. This frees up its locks, allowing the other transaction(s) to proceed.
WHEN TO USE IT You don't 'use' a deadlock; you design systems to avoid or handle them. The underlying locking mechanism that causes them is fundamental for ensuring the ACID properties (Atomicity, Consistency, Isolation, Durability) of transactions in any database with concurrent users.
WHEN NOT TO USE IT The goal is to prevent deadlocks. A primary strategy is to ensure all transactions acquire locks on resources in a consistent order. For example, when modifying two bank accounts, always lock the account with the lower account number first. This breaks the circular wait condition. Other best practices include keeping transactions as short as possible and only locking the precise data needed for the minimum time required.
ONE CANONICAL EXAMPLE Transaction 1 begins and locks the Accounts row for user 'alice' to deduct a balance. Simultaneously, Transaction 2 begins and locks the Products row for 'widget' to update inventory. Now, Transaction 1 tries to lock the 'widget' row, but must wait for Transaction 2. Then, Transaction 2 tries to lock the 'alice' row, but must wait for Transaction 1. They are deadlocked. The database will abort one of them.
Read the original → learn.microsoft.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.