Guides

Transaction was deadlocked (Msg 1205): find the deadlock graph and fix the cause

By Scott Coffey, Senior Database Developer. Updated 2026-11-27.

A call that usually works fails once in a while with this:

Msg 1205, Level 13, State 51, Line 5
Transaction (Process ID 52) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

Two sessions each held a lock the other one needed. Neither could ever finish, so the deadlock monitor picked one, rolled back its whole transaction, and let the other one continue. Nothing is corrupted, but the victim's work is gone unless something reruns it.

This is different from blocking. Blocking is one session waiting on another and eventually getting through; the head blocker guide covers that. A deadlock is a cycle, and SQL Server breaks it within seconds. By the time anyone looks, both sessions are gone, so live DMVs show nothing. The evidence is in the deadlock graph.

Step 1: read what the error tells you

The message gives the victim's session id and nothing else: no table, no statement, no other session. The victim is normally the transaction that is cheapest to roll back, unless a session set DEADLOCK_PRIORITY. Retrying blindly can hide a real design problem, so find out what collided first.

Step 2: pull the deadlock graph from system_health

The system_health Extended Events session is on by default and records every deadlock as an xml_deadlock_report event, both in a memory ring buffer and in files in the instance's log folder. The files survive a restart, so read those:

SELECT x.e.value('@timestamp', 'datetime2(3)') AS deadlock_time_utc,
       x.e.query('data[@name="xml_report"]/value/deadlock') AS deadlock_graph
FROM (SELECT CAST(event_data AS xml) AS event_xml
      FROM sys.fn_xe_file_target_read_file(N'system_health*.xel', NULL, NULL, NULL)
      WHERE object_name = N'xml_deadlock_report') AS f
CROSS APPLY f.event_xml.nodes('/event') AS x(e)
ORDER BY deadlock_time_utc DESC;

Two things caught us in testing on SQL Server 2022. The timestamp is UTC, so convert before matching it to an application log. And the event did not appear right away: system_health buffers events for up to 120 seconds (its max_dispatch_latency), so a deadlock from a minute ago may not be there yet. The files also have a size limit and roll over, so on a busy server older deadlocks age out.

In SSMS, click the deadlock_graph value, save the XML with an .xdl extension, and reopen it to see the graphical view. For anything more than one deadlock, the next two queries are faster.

Step 3: list the processes, statements, and indexes involved

One row per session in each deadlock, with the victim marked and the batch it was running:

WITH dl AS (
    SELECT CAST(event_data AS xml) AS event_xml
    FROM sys.fn_xe_file_target_read_file(N'system_health*.xel', NULL, NULL, NULL)
    WHERE object_name = N'xml_deadlock_report'
)
SELECT d.event_xml.value('(/event/@timestamp)[1]', 'datetime2(0)') AS deadlock_time_utc,
       p.n.value('@spid', 'int') AS spid,
       CASE WHEN p.n.value('@id', 'varchar(50)')
                 = d.event_xml.value('(/event/data/value/deadlock/victim-list/victimProcess/@id)[1]', 'varchar(50)')
            THEN 'victim' ELSE 'survivor' END AS outcome,
       p.n.value('@currentdbname', 'sysname') AS database_name,
       p.n.value('@isolationlevel', 'varchar(50)') AS isolation_level,
       p.n.value('@lockMode', 'varchar(10)') AS lock_wanted,
       p.n.value('@waitresource', 'varchar(200)') AS wait_resource,
       p.n.value('@clientapp', 'nvarchar(128)') AS client_app,
       LTRIM(p.n.value('(inputbuf)[1]', 'nvarchar(max)')) AS input_buffer
FROM dl AS d
CROSS APPLY d.event_xml.nodes('/event/data/value/deadlock/process-list/process') AS p(n)
ORDER BY deadlock_time_utc DESC, outcome;

And the locked resources, with table and index names already resolved:

WITH dl AS (
    SELECT CAST(event_data AS xml) AS event_xml
    FROM sys.fn_xe_file_target_read_file(N'system_health*.xel', NULL, NULL, NULL)
    WHERE object_name = N'xml_deadlock_report'
)
SELECT d.event_xml.value('(/event/@timestamp)[1]', 'datetime2(0)') AS deadlock_time_utc,
       r.n.value('local-name(.)', 'varchar(30)') AS lock_type,
       r.n.value('@objectname', 'nvarchar(400)') AS object_name,
       r.n.value('@indexname', 'nvarchar(128)') AS index_name,
       r.n.value('(owner-list/owner/@mode)[1]', 'varchar(10)') AS held_mode,
       r.n.value('(waiter-list/waiter/@mode)[1]', 'varchar(10)') AS wanted_mode
FROM dl AS d
CROSS APPLY d.event_xml.nodes('/event/data/value/deadlock/resource-list/*') AS r(n)
ORDER BY deadlock_time_utc DESC;

In our test, two sessions updated dbo.Accounts and dbo.Orders in opposite order. The queries showed two keylock rows on the two primary keys, each held X by one session and wanted X by the other, plus both input buffers. That pattern, the same tables touched in a different order, is the most common cause. Others to look for: a scan that locks far more rows than it needs because an index is missing, and a reader holding shared locks while a writer waits, then the reverse.

Step 4: fix the cause

  • Access order. Make every code path that writes to the same tables touch them in the same order. With both sessions updating Accounts first, our test produced ordinary blocking that cleared on its own, not a deadlock.
  • Short transactions. Do no user interaction, remote calls, or waits inside a transaction. Fewer locks held for less time means fewer chances to collide.
  • Indexes. If wait_resource points at a clustered index for a query that filters on another column, a supporting index lets it lock a few keys instead of scanning.
  • Readers and writers. READ_COMMITTED_SNAPSHOT stops readers from taking shared locks, which removes reader/writer deadlocks. It does not help two writers, and it adds tempdb version store load, so test it first. Do not reach for NOLOCK; it returns rows that were never committed.

Step 5: retry the victim safely

Even with a good design, rare deadlocks can still happen, and the error itself says to rerun the transaction. Do it in one place, for 1205 only, a limited number of times, and only when the procedure owns the transaction:

CREATE OR ALTER PROCEDURE dbo.usp_PayOrder
    @OrderID   int,
    @AccountID int,
    @Amount    money
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    IF @@TRANCOUNT > 0
    BEGIN
        RAISERROR(N'Call with no open transaction: a deadlock rolls back the caller''s transaction too.', 16, 1);
        RETURN 1;
    END;

    DECLARE @Attempt int = 1, @MaxAttempts int = 3;

    WHILE 1 = 1
    BEGIN
        BEGIN TRY
            BEGIN TRANSACTION;
            -- Same order as every other writer: Accounts, then Orders.
            UPDATE dbo.Accounts SET Balance = Balance - @Amount WHERE AccountID = @AccountID;
            UPDATE dbo.Orders SET Status = 'paid' WHERE OrderID = @OrderID;
            COMMIT TRANSACTION;
            RETURN 0;
        END TRY
        BEGIN CATCH
            IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
            IF ERROR_NUMBER() = 1205 AND @Attempt < @MaxAttempts
            BEGIN
                SET @Attempt += 1;
                WAITFOR DELAY '00:00:00.200';
                CONTINUE;
            END;
            THROW;
        END CATCH;
    END;
END;

The @@TRANCOUNT check matters. A deadlock rolls back the entire transaction, including any outer one the caller opened, so retrying only the inner statements would commit half a unit of work. In our test, a session running this procedure at DEADLOCK_PRIORITY LOW was chosen as the victim on attempt 1, succeeded on attempt 2, and the balance was debited exactly once. Any other error, or a third deadlock, is rethrown to the caller.

The same structure follows SQL Rig's proc-template-safe.sql: XACT_ABORT, TRY/CATCH, errors rethrown rather than swallowed, and a refusal to run inside a caller's transaction. If the deadlock hits a SQL Server Agent job step, the step's @retry_attempts setting gives a coarser retry; the pack's agent-job-create-template.sql sets one retry by default, and the Agent job failure guide shows where Msg 1205 appears in job history.

Step 6: keep deadlocks visible

A retry that always succeeds can hide a deadlock rate that keeps climbing. Run the Step 3 queries on a schedule, or as part of a regular health check, and look at counts per day and per table. If the same pair of statements keeps showing up, fix the access order rather than raising @MaxAttempts.