Diagnosing and Fixing SQL Server Deadlocks (Error 1205) with Extended Events and T-SQL

Enterprise data center server racks with structured network cabling powering production database infrastructure

At 2:15 PM during a routine billing batch, your application log starts throwing one of the most disruptive exceptions in the SQL Server ecosystem: Msg 1205, Level 13, State 51: Transaction (Process ID 87) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction. Users complain that invoices failed to save, support tickets pile up, and the first instinct on a busy engineering team is almost always the wrong one: sprinkle WITH (NOLOCK) across a few reporting queries or bump up the connection retry count and hope the storm passes.

Blindly adding NOLOCK trades a loud, honest failure for silent data corruption. Under READ UNCOMMITTED, SQL Server can read uncommitted rows that later roll back, skip rows mid-page-split, or return the same row twice during an allocation-order scan. Retrying the failed transaction without fixing the underlying lock collision only masks the symptom while burning CPU and log throughput as traffic grows. Fixing Error 1205 permanently requires pulling the actual deadlock graph out of SQL Server, identifying which lock resources formed the cycle, and removing the structural conflict.

How the Lock Monitor Picks a Deadlock Victim

A deadlock is not just slow blocking. Normal blocking clears as soon as the head blocker commits or rolls back. A deadlock is a circular wait that can never resolve on its own: Session A holds a lock on Resource 1 and waits for Resource 2, while Session B holds a lock on Resource 2 and waits for Resource 1. Neither session can advance until SQL Server intervenes.

SQL Server runs a background Lock Monitor thread that wakes up every five seconds by default to inspect wait chains for cycles. Once a deadlock is found, the interval dynamically shrinks (all the way down to 100 milliseconds during heavy deadlock bursts) so subsequent cycles are broken rapidly. To break the cycle, SQL Server chooses a victim using two criteria in order:

  1. DEADLOCK_PRIORITY: Any session that explicitly set SET DEADLOCK_PRIORITY LOW (or a lower integer from -10 to 10) is terminated first.
  2. Rollback cost: When priorities are equal (the default NORMAL, or 0), SQL Server estimates which transaction has generated fewer transaction log bytes and therefore costs less to roll back.

Keep in mind that SQL Server rolls back the victim's entire open transaction, releases its locks so the surviving session can finish, and sends Error 1205 back to the client. If a stored procedure was three steps deep inside an explicit BEGIN TRAN without proper XACT_ABORT ON or error handling, sloppy client code can accidentally leave orphaned state or retry only half the unit of work.

Pulling Deadlock Graphs from system_health Without Third-Party Tools

Many developers assume they need SQL Server Profiler, trace flags 1204/1222, or a paid monitoring suite running ahead of time to capture a deadlock. You do not. Every modern SQL Server instance (including SQL Server Express and Standard) ships with the built-in system_health Extended Events session enabled by default, and it automatically records full xml_deadlock_report graphs to disk.

One important operational caveat: avoid querying the ring_buffer target in sys.dm_xe_session_targets for deadlocks. The ring buffer caps its memory footprint and silently truncates large XML payloads or drops older events on busy servers. Reading the .xel rollover files on disk via sys.fn_xe_file_target_read_file is far more reliable and usually gives you days of historical graphs:

;WITH SystemHealthPath AS
(
    SELECT CAST(t.target_data AS XML)
           .value('(/EventFileTarget/File/@name)[1]', 'NVARCHAR(4000)') AS CurrentFilePath
    FROM sys.dm_xe_sessions AS s
    INNER JOIN sys.dm_xe_session_targets AS t
        ON s.address = t.event_session_address
    WHERE s.name = N'system_health'
      AND t.target_name = N'event_file'
),
WildcardPath AS
(
    SELECT LEFT(CurrentFilePath, LEN(CurrentFilePath) - CHARINDEX('\', REVERSE(CurrentFilePath)) + 1)
           + N'system_health*.xel' AS FilePattern
    FROM SystemHealthPath
)
SELECT TOP (25)
    xed.value('@timestamp', 'DATETIME2(3)') AS DeadlockUtcTime,
    xed.query('(data[@name="xml_deadlock_report"]/value/deadlock)[1]') AS DeadlockGraphXml
FROM WildcardPath AS wp
CROSS APPLY sys.fn_xe_file_target_read_file(wp.FilePattern, NULL, NULL, NULL) AS xel
CROSS APPLY (SELECT CAST(xel.event_data AS XML)) AS ev(event_xml)
CROSS APPLY ev.event_xml.nodes('/event[@name="xml_deadlock_report"]') AS n(xed)
ORDER BY DeadlockUtcTime DESC;

Run this query in SQL Server Management Studio (SSMS). Clicking any XML cell in the DeadlockGraphXml column opens the raw XML document. If you save that XML with a .xdl extension and reopen it inside SSMS, SSMS renders the classic visual diagram with the crossed-out oval marking the victim process. Even better, reading the raw XML directly gives you exact index names, lock modes, isolation levels, and input buffers that the visual diagram often truncates.

Reading the Four Sections of an XML Deadlock Graph

Do not get intimidated by the length of an xml_deadlock_report payload. Almost every root-cause answer lives in three nodes: <victim-list>, <process-list>, and <resource-list>. Start at <resource-list> first. Each child element (such as <keylock>, <pagelock>, <ridlock>, or <objectlock>) tells you the exact database, table, and index involved, plus the owner-list (who holds the lock and in what mode) and the waiter-list (who is blocked waiting for what mode).

Then jump to <process-list> and match the process id values. Look closely at each process's isolationlevel attribute, its <executionStack> (exact stored procedure and line number), and its <inputbuf>. In real production workloads, roughly ninety percent of Error 1205 events fall into four recurring patterns:

Deadlock Pattern Signature in XML Resource List Primary Structural Fix
Reverse Table Order Two X locks across two different tables (e.g., Orders and Inventory) Update tables in the exact same deterministic order across all procedures
Bookmark / Key Lookup One table, two indexes: S vs X collision between nonclustered index and clustered key Make the nonclustered index covering with INCLUDE columns, or enable RCSI
Unindexed Foreign Key Parent DELETE or key UPDATE holds X lock and scans child table with S/U locks Add a nonclustered index on the child table's foreign key column(s)
Serializable Range Conversion RangeS-S held by both sessions, both requesting RangeS-U or RangeI-N Lower isolation level from SERIALIZABLE, or serialize upsert with UPDLOCK, HOLDLOCK
Software developer inspecting code and query execution diagnostics on a dark-themed workstation monitor

Eliminating Single-Table Bookmark Lookup Deadlocks

The deadlock that confuses teams the most involves only a single table and a single-statement SELECT colliding with a single-statement UPDATE. Developers look at the code, see no explicit multi-step transaction, and assume SQL Server must have a bug. What actually happened is a classic inverted index traversal.

Suppose your dbo.Shipments table has a clustered primary key on ShipmentId and a nonclustered index on Status. A reporting query runs SELECT ShipmentId, TrackingNumber, ShippedAt FROM dbo.Shipments WHERE Status = 'Pending'. SQL Server seeks the nonclustered index (acquiring a shared S lock on the index key) and then performs a Key Lookup back to the clustered index to fetch TrackingNumber and ShippedAt. At the exact same millisecond, an order-fulfillment worker runs UPDATE dbo.Shipments SET Status = 'Shipped', ShippedAt = SYSUTCDATETIME() WHERE ShipmentId = 48291. That update acquires an exclusive X lock on the clustered index row first, and then moves to the nonclustered Status index to update the index key.

The reader went nonclustered to clustered. The writer went clustered to nonclustered. Under default READ COMMITTED locking, they cross paths in opposite directions and deadlock immediately.

If your XML graph shows two <keylock> entries on the same table referencing two different index names, turning the nonclustered index into a covering index breaks the cycle completely because the SELECT never needs to touch the clustered index:

-- Replace a narrow Status index with a covering index to eliminate Key Lookups
CREATE NONCLUSTERED INDEX IX_Shipments_Status_Covering
ON dbo.Shipments (Status)
INCLUDE (TrackingNumber, ShippedAt)
WITH (ONLINE = ON, DROP_EXISTING = OFF);

A practical caveat before creating covering indexes everywhere: every column you add to an INCLUDE list increases index size on disk and in the buffer pool, and forces SQL Server to maintain extra index pages whenever those columns change. Avoid dumping wide NVARCHAR(MAX) columns or 15 unrelated fields into an INCLUDE clause just to silence one query. Cover the hot read columns, or fix reader-writer contention database-wide with row versioning.

Fixing Missing Foreign Key Indexes and Reverse Lock Order

Unlike primary keys, SQL Server does not automatically index foreign key columns on child tables. When a process deletes a row from dbo.Customers (holding an X lock on the parent row), SQL Server must verify that no orphaned rows exist in dbo.Invoices. Without an index on dbo.Invoices(CustomerId), SQL Server executes a full clustered index scan on the child table, spraying shared locks across thousands of unrelated invoice rows and colliding with concurrent invoice updates.

You can audit unindexed foreign keys across your entire database in seconds:

SELECT
    OBJECT_SCHEMA_NAME(fk.parent_object_id) + '.' + OBJECT_NAME(fk.parent_object_id) AS ChildTable,
    c.name AS ForeignKeyColumn,
    fk.name AS ForeignKeyName
FROM sys.foreign_keys AS fk
INNER JOIN sys.foreign_key_columns AS fkc
    ON fk.object_id = fkc.constraint_object_id
INNER JOIN sys.columns AS c
    ON fkc.parent_object_id = c.object_id
   AND fkc.parent_column_id = c.column_id
WHERE NOT EXISTS
(
    SELECT 1
    FROM sys.index_columns AS ic
    WHERE ic.object_id = fkc.parent_object_id
      AND ic.column_id = fkc.parent_column_id
      AND ic.index_column_id = 1
)
ORDER BY ChildTable, ForeignKeyColumn;

For multi-table write deadlocks, inspect the <executionStack> of both competing procedures. If Procedure A updates dbo.Accounts and then inserts into dbo.LedgerEntries while Procedure B updates dbo.LedgerEntries and then recalculates dbo.Accounts, establish a strict team-wide table access order (for example, always lock parent entities before child entities, or alphabetical order for peer tables). Just as critical: shrink transaction scope. Never hold an open BEGIN TRAN while calling an external payment API, generating a PDF, or running slow validation selects that do not need transactional locking. Perform all read-only lookups and external I/O first, open the transaction right before the first write, execute the writes in canonical order, and commit immediately.

Using READ_COMMITTED_SNAPSHOT (RCSI) for Reader-Writer Contention

On OLTP databases where concurrent reporting queries constantly collide with high-frequency updates, chasing every individual bookmark-lookup deadlock with covering indexes becomes an endless game of whack-a-mole. Enabling READ_COMMITTED_SNAPSHOT (RCSI) changes SQL Server's default READ COMMITTED isolation level from pessimistic shared locking to optimistic row versioning, much like PostgreSQL or Oracle.

With RCSI enabled, readers no longer take shared locks on rows being modified, and writers no longer block readers. Instead, whenever an update modifies a row, SQL Server copies the pre-change version into the tempdb version store so concurrent readers see a transactionally consistent snapshot of committed data as of the start of their statement.

Check your current database status and enable RCSI during a planned maintenance window:

-- Check whether RCSI is currently enabled
SELECT name, is_read_committed_snapshot_on, snapshot_isolation_state_desc
FROM sys.databases
WHERE name = N'YourAppDb';

-- Enable RCSI (requires exclusive database access momentarily)
ALTER DATABASE YourAppDb
SET READ_COMMITTED_SNAPSHOT ON
WITH ROLLBACK IMMEDIATE;

Do not flip this switch blindly on a live production database at noon. First, WITH ROLLBACK IMMEDIATE kicks off all active connections and rolls back in-flight transactions to acquire an exclusive database lock. Second, RCSI moves concurrency overhead into tempdb: make sure tempdb sits on fast NVMe storage with multiple evenly sized data files and monitor sys.dm_tran_version_store_space_usage after rollout. Third, SQL Server appends a 14-byte version pointer to modified rows, which can trigger extra page splits on heavily packed clustered indexes with a 100 percent fill factor. Finally, understand its boundary: RCSI completely eliminates reader-writer deadlocks, including bookmark-lookup deadlocks, but it does not eliminate writer-versus-writer deadlocks where two transactions update the same rows in opposite order.

Verifying the Fix and Keeping Retries Honest

Even on a well-indexed RCSI database, occasional writer-vs-writer collisions can happen during unexpected traffic spikes. Add bounded retry logic in your data-access layer specifically for SQL error number 1205 (three attempts with randomized exponential backoff, such as 50 ms, 150 ms, and 400 ms, so colliding threads do not slam the same row again in lockstep). Never swallow the exception silently, though: emit a structured warning metric on every retry and run a scheduled check against system_health deadlock counts after every schema or ORM migration. That way, if a new Entity Framework query or unindexed foreign key reintroduces a lock cycle, you catch it in staging or during the first afternoon rather than after a billing batch collapses.

Related Guides on DailyFraction

Official Documentation References