SQL fundamentals learning path Level 2 This level · 5 of 7
Medium sql sql-server

How does SQL Server detect and resolve a deadlock?

The 30 second answer

A lock monitor thread searches the wait-for graph for a cycle. The default interval is 5 seconds; if deadlocks are frequent it can drop as low as 100 milliseconds, and after a detection the next lock waits can trigger an immediate search. The engine then chooses a victim — lower DEADLOCK_PRIORITY first, then the transaction that is cheapest to roll back — rolls that transaction back, and returns error 1205.

Could you say this in an interview?

SQL Server does not leave a deadlock in place until a client times out. A lock monitor thread periodically walks tasks that are waiting, follows who owns the resource each waiter needs, and treats a cycle in that wait-for graph as a deadlock.

The default search interval is 5 seconds. That interval is not fixed: if the monitor finds deadlocks, it can drop as low as 100 milliseconds depending on how often they occur, and it rises back toward 5 seconds when they stop. After a deadlock is detected, the first few new lock waits can start a search immediately rather than waiting for the next interval.

When a cycle is found, the engine chooses one thread as the victim, terminates its current batch, rolls back its transaction (which releases its locks), and returns error 1205 to the application. The other session can then continue. Victim choice is not only "whoever is cheapest to roll back." If sessions have different DEADLOCK_PRIORITY values, the lower-priority session is chosen. If priorities are equal, the engine chooses the transaction that is least expensive to roll back, measured by the log bytes written so far. If priority and cost are also equal, the victim is chosen randomly. A session that is already rolling back is not chosen.

PostgreSQL also aborts one transaction when it finds a cycle, after deadlock_timeout, with SQLSTATE 40P01. The detection interval and error number are not the same as SQL Server's.

-- error 1205: this transaction was chosen as the deadlock victim and has been rolled back
SET DEADLOCK_PRIORITY LOW;
BEGIN TRANSACTION;
-- the lower-priority session is chosen first, before rollback cost is compared
UPDATE Seats SET Status = 'Held' WHERE Id = 'C7';
Sources (3)
  1. Microsoft Learn — Deadlocks Guidelearn.microsoft.com
  2. Microsoft Learn — SET DEADLOCK_PRIORITYlearn.microsoft.com
  3. PostgreSQL documentation — Deadlockspostgresql.org
Previous
Next