An application log shows Msg 1205, Level 13: "Transaction (Process ID 51) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction." On SQL Server 2019, 2022 or 2025 the engine has already resolved the deadlock by rolling back one transaction. Your job is to find which two statements collided, on which index, and why, before they collide again at peak load. The system_health session has already recorded the deadlock graph. This guide shows how to pull and read those graphs, match the four common patterns, pick a fix, retry safely, and what changes on Azure SQL Database.
- Error 1205 means the engine broke a lock cycle by rolling back the victim's whole transaction.
- On SQL Server and Managed Instance, read past deadlocks from
system_healthby filtering onxml_deadlock_report. No setup is needed. - In each graph, read the victim, lock modes, isolation level and the two resources, then map the HoBT ID to an index.
- Index tuning is the lowest-risk fix; then one access order, row versioning (RCSI) and shorter transactions.
- Every application path still needs a retry on 1205 with a short random delay.
Scope and review date: November 2026. This post covers SQL Server 2019, 2022 and 2025 and Azure SQL Database, with notes on Azure SQL Managed Instance. Queries, defaults and limits were checked against Microsoft Learn on 25 November 2026. They were not run in a lab, so try them on a non-production copy first.
What does SQL Server error 1205 actually mean?
A deadlock is a cycle: session A holds a lock that B needs, and B holds a lock that A needs. Neither can move. The Microsoft Learn deadlocks guide describes how the lock monitor finds them. It searches every 5 seconds by default. Once it starts finding deadlocks it shortens the interval to as little as 100 milliseconds, and it goes back to 5 seconds when they stop.
When it finds a cycle, the engine picks a victim. It ends that session's current batch, rolls back its transaction, releases its locks and returns error 1205. The victim is the session with the lowest DEADLOCK_PRIORITY (LOW, NORMAL, HIGH, or an integer from -10 to 10; the default is NORMAL, which is 0). If the priorities match, the engine picks the transaction that is cheapest to roll back. If those match too, it picks one at random.
A priority changes who loses, not whether a deadlock happens. Use SET DEADLOCK_PRIORITY LOW only for work that can always afford to retry, such as a report.
Blocking is a different problem: a blocked session waits until the blocker commits or the client times out. If your logs show timeouts and no 1205s, find the head blocker instead of reading deadlock graphs.
How do I get the deadlock graph from system_health?
The system_health session ships with SQL Server and Azure SQL Managed Instance. It starts with the instance and records "any deadlocks that are detected, including the deadlock graph", as the xml_deadlock_report event. It writes to two targets:
ring_buffer: in memory. It holds recent events only and is lost on restart.event_file:system_health*.xelfiles in the instance's log folder. The documented limits are 5 MB per file and 4 files kept. Standard and Enterprise editions raise this to 100 MB per file and 10 files.
The file target keeps more history, so start there. This query, built on the documented sys.fn_xe_file_target_read_file example, returns one row per deadlock:
-- SQL Server 2017 and later: deadlocks from the system_health event files
SELECT CAST(f.event_data AS xml).value('(event/@timestamp)[1]', 'datetime2(3)') AS deadlock_utc,
CAST(f.event_data AS xml).query('(event/data/value/deadlock)[1]') AS deadlock_graph
FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL) AS f
WHERE f.object_name = N'xml_deadlock_report'
ORDER BY deadlock_utc DESC;Interpretation: each row is one resolved deadlock, with its time in UTC. Click a deadlock_graph cell in SSMS, save the XML as a .xdl file and reopen it to see the graphical deadlock graph. On SQL Server 2022 and later, the function needs VIEW SERVER PERFORMANCE STATE. On 2019 it needs VIEW SERVER STATE.
The deadlocks guide also gives a query for the ring_buffer target. Use it when the files have rolled over, but treat an empty result with care: the ring buffer holds only recent events. If both targets are empty while the application logs show 1205s, check that the session is running in sys.dm_xe_sessions. Microsoft recommends that you don't stop, alter or delete system_health.
Deadlock triage runbook for SQL Server
Five steps from the first 1205 in the logs to a fix you can verify; none of them change data
-
Confirm it is error 1205
Timeouts with no 1205 point to blocking instead.
-
Pull every graph from system_health
Read the event files first; they hold more history than the ring buffer.
SELECT * FROM sys.fn_xe_file_target_read_file( 'system_health*.xel', NULL, NULL, NULL) WHERE object_name = N'xml_deadlock_report'; -
Map each waitresource to an index
A KEY resource carries a database ID and a HoBT ID; look the HoBT ID up in sys.partitions.
-
Match the graph to a known pattern
Group graphs by statement pair, then check both execution plans.
-
Apply the lowest-risk fix and recount
Index changes first. Recount the same pair a week later.
Main risk: fixing the first graph you open. Count graphs per statement pair before you change anything, or you may tune a one-off while the repeating deadlock keeps firing.
How do I read a SQL Server deadlock graph?
Every graph has three parts. The deadlocks guide names them victim-list, process-list and resource-list. Read them in this order:
- Victim: the process ID in
victim-list, usually the one with the smallerlogused. - Processes: note each one's
isolationlevel,lockMode(the mode it waits for),waitresourceand statement (inputbuf). - Resources: each lock names the index, its owner and held mode, and its waiter and wanted mode. Crossed owners and waiters make the cycle.
A key lookup deadlock graph, trimmed
Output from the Microsoft Learn deadlocks guide; attributes trimmed and wrapped to fit
The cycle: the SELECT holds S on the nonclustered index idx1 and waits on the clustered index cidx. The UPDATE holds X on cidx and waits on idx1. The full XML is in the deadlocks guide.
To compare many graphs, shred them into one row per process:
WITH d AS (
SELECT CAST(event_data AS xml).value('(event/@timestamp)[1]', 'datetime2(3)') AS deadlock_utc,
CAST(event_data AS xml).query('(event/data/value/deadlock)[1]') AS g
FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL)
WHERE object_name = N'xml_deadlock_report'
)
SELECT d.deadlock_utc,
p.n.value('@spid', 'int') AS spid,
CASE WHEN p.n.value('@id', 'varchar(50)')
= d.g.value('(deadlock/victim-list/victimProcess/@id)[1]', 'varchar(50)')
THEN 1 ELSE 0 END AS is_victim,
p.n.value('@isolationlevel', 'varchar(40)') AS isolation_level,
p.n.value('@lockMode', 'varchar(20)') AS waiting_for,
p.n.value('@waitresource', 'varchar(200)') AS wait_resource,
p.n.value('@logused', 'bigint') AS log_used,
p.n.value('(inputbuf/text())[1]', 'nvarchar(max)') AS input_buffer
FROM d
CROSS APPLY d.g.nodes('deadlock/process-list/process') AS p(n)
ORDER BY d.deadlock_utc DESC, is_victim DESC;Interpretation: group by input_buffer to see which pairs repeat. serializable (4) on a path you expected to be read committed, or range modes such as RangeI-N, point to the range-lock pattern below.
To turn a waitresource such as KEY: 5:72057594214350848 (1a39e6095155) into a table and index, run this in the database whose ID is the first number (SELECT DB_NAME(5)):
SELECT OBJECT_SCHEMA_NAME(p.object_id) AS schema_name,
OBJECT_NAME(p.object_id) AS table_name,
i.name AS index_name,
i.type_desc
FROM sys.partitions AS p
JOIN sys.indexes AS i
ON i.object_id = p.object_id AND i.index_id = p.index_id
WHERE p.hobt_id = 72057594214350848;Interpretation: the bracketed hex value is a hash of the key, not the key. Waits on two indexes of one table suggest a key lookup.
Lock mode definitions are in the transaction locking and row versioning guide. S on a reader usually means no row versioning, range modes mean SERIALIZABLE, and xactlock resources mean optimized locking is on.
Which deadlock patterns cause most SQL Server deadlocks?
Most graphs fit one of four shapes. Match yours before you change anything, because each one has a different fix.
The key lookup deadlock from the graph above
Each session holds one index on dbo.t1 and waits for the other's; the SELECT is the victim
The fix: add c3 to idx1 as an included column. The SELECT then never touches cidx, so step 3 disappears and the cycle cannot close.
1. Key lookup deadlocks
This is the graph above. A reader seeks a nonclustered index, then looks up columns that are not in it from the clustered index. A writer updates a row through the clustered index and then has to maintain the nonclustered key. The two touch the same two structures in opposite order. A covering index removes the lookup:
-- idx1 was (c2); include c3 so the SELECT is answered from idx1 alone
CREATE NONCLUSTERED INDEX idx1
ON dbo.t1 (c2)
INCLUDE (c3)
WITH (DROP_EXISTING = ON, ONLINE = ON);Interpretation: after the change, the SELECT plan shows an Index Seek on idx1 and no Key Lookup. ONLINE = ON needs Enterprise or Developer edition, or Azure SQL; drop that option on Standard and schedule the rebuild. RCSI also breaks this cycle, because the reader stops taking S locks.
2. Reverse-order updates
Two transactions update the same rows or tables in opposite order. The deadlocks guide gives a version that deadlocks even with optimized locking on:
-- Session 1 -- Session 2
BEGIN TRANSACTION xactA; BEGIN TRANSACTION xactB;
UPDATE t2 SET b = b + 10 WHERE a = 1; UPDATE t2 SET b = b + 10 WHERE a = 2;
UPDATE t2 SET b = b + 100 WHERE a = 2;
UPDATE t2 SET b = b + 20 WHERE a = 1;Interpretation: each session holds the row the other needs next. With optimized locking, the graph shows xactlock resources and XACT wait resources instead of KEY, but the cause is the same. The fix is in the code. Every transaction that touches both rows or tables must take them in the same order, for example by ascending key.
3. Unindexed foreign keys
When a parent row is deleted, or its key updated, the engine must check the child table for referencing rows. Without an index on the foreign key column, that check scans the child table and takes locks across far more rows than it needs. Microsoft's Azure SQL deadlock article says that when deadlocks involve columns referenced by foreign keys, the referencing table needs indexes that find related rows efficiently. This query lists foreign keys whose first column does not lead any index:
SELECT fk.name AS foreign_key,
OBJECT_NAME(fk.parent_object_id) AS child_table,
c.name AS fk_column
FROM sys.foreign_keys AS fk
JOIN sys.foreign_key_columns AS fkc
ON fkc.constraint_object_id = fk.object_id AND fkc.constraint_column_id = 1
JOIN sys.columns AS c
ON c.object_id = fkc.parent_object_id AND c.column_id = fkc.parent_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.key_ordinal = 1);Interpretation: each row is a candidate index. Prioritise the child tables that appear in your deadlock graphs. The query checks only the first column, so review multi-column keys by hand.
4. Serializable range locks
Under SERIALIZABLE, a read takes key-range locks on the range it read. The classic case is "check, then insert". Two sessions both read an empty range and both take RangeS-S, which are compatible with each other. Then both try to insert, and each needs RangeI-N, which conflicts with the other's RangeS-S.
-- Deadlock-prone under SERIALIZABLE
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF NOT EXISTS (SELECT 1 FROM dbo.Customers WHERE Email = @Email)
INSERT dbo.Customers (Email) VALUES (@Email);
COMMIT TRANSACTION;
-- Safer: take the range in update mode, so the second session waits at the SELECT
BEGIN TRANSACTION;
IF NOT EXISTS (SELECT 1 FROM dbo.Customers WITH (UPDLOCK, HOLDLOCK) WHERE Email = @Email)
INSERT dbo.Customers (Email) VALUES (@Email);
COMMIT TRANSACTION;Interpretation: RangeS-U conflicts with another RangeS-U, so the second caller blocks briefly instead of deadlocking. Key-range locks need an index on Email. Without one, the read locks far more. If the graph shows serializable (4) and nobody chose it, check the client library's default. .NET TransactionScope, for example, defaults to serializable unless you set IsolationLevel.
How do I stop a deadlock from coming back?
Microsoft's Azure SQL deadlock guidance calls nonclustered index tuning "the lowest risk approach", because it changes no query code. Work through the options in roughly this order.
- Index the statements in the graph. A seek touches fewer rows than a scan, so it takes fewer locks.
- Force a known-good plan. If a deadlock happens only under one plan, force the other plan with Query Store.
- Use one access order. Order statements so every transaction touches tables and rows in the same sequence.
- Keep transactions short and in one batch. Do no user interaction or remote calls inside an open transaction.
- Use row versioning. RCSI removes shared locks from read committed reads; snapshot isolation does so for transactions that opt in.
-- Is row versioning already on for this database?
SELECT name, is_read_committed_snapshot_on, snapshot_isolation_state_desc
FROM sys.databases
WHERE name = DB_NAME();
-- Turn on RCSI (needs exclusive access; ROLLBACK IMMEDIATE ends other sessions)
ALTER DATABASE CURRENT SET READ_COMMITTED_SNAPSHOT ON WITH ROLLBACK IMMEDIATE;Interpretation: Microsoft recommends RCSI for all applications unless one depends on readers being blocked by writers. Check that before you enable it. Row versions live in tempdb, or in the user database when accelerated database recovery is on, so watch version store size after the change.
A read returns the last committed version instead of waiting. Read-then-update code can lose updates unless it uses UPDLOCK or one atomic statement.
Optimized locking on SQL Server 2025
Optimized locking releases row and page locks as soon as each row is updated and holds only one transaction ID lock to the end. With RCSI on, it also qualifies rows without taking U locks (lock after qualification). Microsoft says this "can avoid certain types of deadlocks". It is off by default in SQL Server 2025 and not available in SQL Server 2022 or earlier.
-- SQL Server 2025: ADR is a prerequisite; RCSI enables the LAQ part
ALTER DATABASE CURRENT SET ACCELERATED_DATABASE_RECOVERY = ON;
ALTER DATABASE CURRENT SET OPTIMIZED_LOCKING = ON;
SELECT DATABASEPROPERTYEX(DB_NAME(), 'IsOptimizedLockingOn') AS is_optimized_locking_enabled;Interpretation: 1 means it is on, 0 off, and NULL not available on this version. It does not stop reverse-order deadlocks. Lock hints such as UPDLOCK and HOLDLOCK reduce its benefit, so the serializable fix above still takes range locks.
How should my application retry after error 1205?
The deadlocks guide is explicit: any application can be chosen as a victim, so every path needs an error handler for 1205. Without one, the application may carry on unaware that its transaction was rolled back. Retry the whole transaction, not the last statement, because the engine rolled back everything since BEGIN TRANSACTION. Microsoft suggests a random pause, for example between one and three seconds, so the two sessions do not collide again.
SET XACT_ABORT ON;
DECLARE @OrderID int = 42, @attempt int = 1, @delay datetime;
WHILE 1 = 1
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
UPDATE dbo.Orders SET Status = N'Shipped' WHERE OrderID = @OrderID;
UPDATE dbo.OrderLines SET ShippedAt = SYSUTCDATETIME() WHERE OrderID = @OrderID;
COMMIT TRANSACTION;
BREAK;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
IF ERROR_NUMBER() = 1205 AND @attempt < 3
BEGIN
SET @attempt += 1;
SET @delay = DATEADD(MILLISECOND, 1000 + ABS(CHECKSUM(NEWID())) % 2000, 0);
WAITFOR DELAY @delay; -- random 1 to 3 seconds
END
ELSE
THROW;
END CATCH;
END;Interpretation: two retries cover the usual case. After that, THROW re-raises 1205 so the caller and your monitoring see it. Apply the same rule in application code: catch the driver exception whose error number is 1205 (SqlException.Number in Microsoft.Data.SqlClient), wait, and rerun the whole unit of work. Make sure nothing outside the transaction, such as a sent email, runs twice, and log each retry.
Should I use trace flag 1222 or Extended Events?
Trace flags 1204 and 1222 write deadlock details to the SQL Server error log. Flag 1222 groups the output by process and then by resource, in an XML-like format that, in the guide's words, "doesn't conform to an XML Schema Definition". Microsoft's guidance is to avoid both flags on "workload-intensive systems that are experiencing deadlocks" and to use the xml_deadlock_report event, which it calls the recommended method. Since system_health already captures that event, most instances need nothing extra.
If you still want the error log copy, DBCC TRACEON (1222, -1) sets it until the next restart, and -T1222 as a startup parameter keeps it. Azure SQL Managed Instance accepts only a short documented list of global trace flags, and 1222 is not on it. DBCC TRACEON is not documented for Azure SQL Database.
Three ways to capture deadlock graphs
Switch between them to compare where the graph goes and what setup it needs
Trace flag 1222
| Question | Trace flag 1222 |
|---|---|
| Where the graph goes | SQL Server error log |
| Format | XML-like text, not valid XML |
| Setup | DBCC TRACEON (1222, -1) or -T1222 |
| Available on | SQL Server |
| Microsoft's guidance | Avoid on busy systems with deadlocks |
system_health
| Question | system_health |
|---|---|
| Where the graph goes | ring_buffer and system_health*.xel files |
| Format | XML; saves as .xdl for the SSMS graph |
| Setup | None; on by default |
| Available on | SQL Server and Azure SQL Managed Instance |
| Microsoft's guidance | Recommended; do not stop or alter the session |
Azure SQL Database session
| Question | Database-scoped session |
|---|---|
| Where the graph goes | ring_buffer, or event_file blobs in Azure Storage |
| Format | XML from database_xml_deadlock_report |
| Setup | CREATE EVENT SESSION ... ON DATABASE; a container and credential for files |
| Available on | Azure SQL Database and SQL database in Fabric |
| Microsoft's guidance | Event file for long-term use; ring buffer for short-term needs |
Default choice: read system_health first; create your own session only on Azure SQL Database or for longer retention.
What is different on Azure SQL Database?
Three things change. First, there is no system_health session in Azure SQL Database, so nothing captures deadlock graphs until you create a session. Second, new databases have RCSI and snapshot isolation on by default, and optimized locking is always on. Microsoft says this makes deadlocks less likely, and the ones you do see are usually between writers. Third, the event is sqlserver.database_xml_deadlock_report, scoped to the database. Microsoft's sample session:
CREATE EVENT SESSION [deadlocks] ON DATABASE
ADD EVENT sqlserver.database_xml_deadlock_report
ADD TARGET package0.ring_buffer
WITH
(
STARTUP_STATE = ON,
MAX_MEMORY = 4 MB
);
GO
ALTER EVENT SESSION [deadlocks] ON DATABASE
STATE = START;
GOInterpretation: the ring buffer is capped at 4 MB, and its contents are lost when the session stops, for example on failover. STARTUP_STATE = ON restarts the session but does not bring the lost events back. For long-term capture, use an event_file target in an Azure Storage container with a database-scoped credential, as the Azure SQL deadlock article shows. Query the ring buffer through sys.dm_xe_database_sessions and sys.dm_xe_database_session_targets, not the server-level views.
If is_read_committed_snapshot_on in sys.databases is 0 on Azure SQL Database, someone turned it off. Microsoft advises finding out why before turning it back on, because the application may depend on readers being blocked. A Deadlocks metric is also available for portal alerts.
Frequently asked questions
How do I find deadlock history in SQL Server without any setup?
Query the built-in system_health Extended Events session. It records every deadlock graph as an xml_deadlock_report event in a ring buffer and in system_health*.xel files. Read the files with sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL), filtered on object_name = 'xml_deadlock_report'. Azure SQL Database has no system_health session, so you must create a database-scoped session there.
How does SQL Server choose the deadlock victim?
The session with the lower DEADLOCK_PRIORITY loses. Priority can be LOW, NORMAL or HIGH, or an integer from -10 to 10, and the default is NORMAL (0). If priorities are equal, SQL Server rolls back the transaction that is cheapest to roll back. If cost is also equal, it picks one at random. A session that is already rolling back cannot be chosen.
Does enabling RCSI stop SQL Server deadlocks?
It stops many of them, but not all. Read committed snapshot isolation removes shared locks from read committed reads, which breaks reader and writer cycles such as key lookup deadlocks. Writer and writer deadlocks, such as updates in reverse order, still happen. Check that no code relies on readers waiting for writers before you enable it.
Should my application retry a transaction after error 1205?
Yes. The victim's transaction has been rolled back, so retry the whole unit of work, not only the last statement. Wait a short random interval first, such as one to three seconds, so the same two sessions do not collide again. Cap the retries at two or three, and log each one so new deadlock patterns show up in monitoring.
Key takeaways
- Error 1205 is the engine resolving a lock cycle. The victim's whole transaction is gone, so the application has to retry it.
- On SQL Server and Managed Instance, the graphs are already in
system_health. On Azure SQL Database, create adatabase_xml_deadlock_reportsession before you need it. - Read the victim, the lock modes, the isolation level and the two resources, then map HoBT IDs to indexes.
- Match the graph to a pattern (key lookup, reverse order, unindexed foreign key or serializable range) and fix that cause, starting with indexes.
- RCSI and SQL Server 2025 optimized locking cut reader and writer deadlocks. Consistent access order is still the only fix for writers that cross.
Get help with SQL Server deadlocks from JusDB
JusDB's SQL Server performance tuning team can analyse your xml_deadlock_report history, group the graphs by statement pair, and recommend index, isolation level and code changes for the patterns that repeat. That includes a plan for moving a database to RCSI or optimized locking safely.
Bring a week of deadlock graphs or access to system_health, the SQL Server version and edition, and the procedures involved. Your team approves every production change.