Diagnosing SQL Server deadlocks: getting deadlock graphs from system_health (and Azure SQL), reading the victim, resources, owners and waiters, the common patterns (opposite lock order, conversion, missing index, serializable ranges), and fixing with lock order, indexes, RCSI, UPDLOCK and idempotent retries.
A deadlock is a cycle: session A holds what B needs and B holds what A needs. The lock monitor detects it and kills the cheapest transaction as the victim with error 1205. On SQL Server, the system_health Extended Events session already captures every xml_deadlock_report; in Azure SQL Database I create a database-scoped XE session (or use the deadlock data in Query Performance Insight).
The graph shows each process's statement, isolation level and the resources with owner and waiter lock modes. Common causes: two code paths touching tables in opposite order, read-then-update conversions, scans from missing indexes, and serializable range locks. Fixes: index to shrink the lock footprint, consistent access order, UPDLOCK, RCSI, lower isolation. Then retry 1205 for idempotent work, as a safety net, not the fix.
"A deadlock is different from blocking because it can never resolve by waiting: there's a cycle, and SQL Server's lock monitor breaks it by rolling back one victim and raising error 1205. The good news is the evidence is free. On SQL Server, the system_health Extended Events session records every deadlock graph, so I start there; on Azure SQL Database I use a database-scoped Extended Events session.
For example, at [company] our month-end invoicing job and the payments API deadlocked [dozens] of times in the first hour of the month. The graph had two processes: the invoice job held an X lock on
Invoicesand wanted a U lock onPayments; the payments API held X onPaymentsand wanted to updateInvoices. Classic opposite access order. There was a second pattern too: the job'sUPDATE Invoices ... WHERE CustomerId = @cscanned the clustered index becauseCustomerIdhad no index, so it locked far more rows than it needed and collided with almost everything. We added the index, changed the payments code to touchInvoicesbeforePaymentslike everything else, and put a retry with backoff around both units of work, which were already idempotent. Deadlocks went from [about 40] to [zero or one] per month-end.The mistake I see is going straight to retry logic or
NOLOCK. Retries are needed, because some deadlocks are unavoidable at scale, but they only hide a design problem if that's all you do, and they're dangerous if the work isn't idempotent: a retry that sends a second email or charges a card twice is worse than the deadlock. My order is: read the graph, shrink the lock footprint with indexes, make access order consistent, reduce isolation or use RCSI, and then retry."
| Element | What to look for |
|---|---|
victim-list |
Which process was killed (usually the one with less log used) |
process |
isolationlevel, trancount, waitresource, lockMode, inputbuf, executionStack (procedure and line) |
resource-list |
Each resource (keylock, pagelock, objectlock) with owner-list (mode held) and waiter-list (mode requested) |
| Index names | Which index each lock is on: tells you about scans and missing indexes |
| Pattern | Graph clue | Fix |
|---|---|---|
| Opposite access order | Two objects, each held by one side | Same order in every code path |
| Conversion (S to X) | Same resource, both hold S and want X | UPDLOCK on the read, or one UPDATE |
| Scan from missing index | Many keys or page locks, clustered index locks for a narrow predicate | Add the index |
| Serializable ranges | RangeS-S, RangeI-N modes |
Lower isolation; fix TransactionScope default |
| Key lookup deadlock | A reader on the non-clustered and a writer on the clustered index | Covering index or RCSI |
| FK / cascade checks | Locks on parent or child tables not in the statement | Index FK columns; avoid cascades on hot paths |
After the fix above, the month-end window processed [N] invoices with [0] deadlocks across three months, and the retry policy fired [twice], both times successfully. A deadlock count alert from the XE session was added to the dashboard.
Checks that the candidate can read a deadlock graph, recognise the pattern, fix the root cause rather than only retrying, and leave the system designed so deadlocks stay rare (consistent access order, short transactions, idempotent retries, monitoring).
Green flags
Red flags
NOLOCK or DEADLOCK_PRIORITY as the fixThe lock monitor thread wakes about every 5 seconds (more often after it finds one) and walks the wait-for graph. When it finds a cycle, it picks a victim based on DEADLOCK_PRIORITY and then the cost to roll back (log used), rolls that transaction back, and returns error 1205 to its client.
Session 61 Session 74
holds X on Invoices(key 9) holds X on Payments(key 3)
wants U on Payments(key 3) ---> owned by 74
owned by 61 <--- wants U on Invoices(key 9)
cycle -> victim chosen -> 1205
system_health session writes xml_deadlock_report to its ring buffer and system_health*.xel files. Query with sys.fn_xe_file_target_read_file.database_xml_deadlock_report event to a ring buffer or an Azure Storage event file. Query Performance Insight and Intelligent Insights also flag deadlocks..xdl files as a picture; the XML holds more detail (execution stack, isolation level).For each process note: spid, isolationlevel (look for serializable from TransactionScope), trancount, lockMode it waits for, waitresource, the executionStack frames and inputbuf. For each resource note the object and index name, the owner's held mode and the waiter's requested mode. Draw the cycle by hand: it almost always reduces to one of the patterns in the answer table.
Deadlocks need overlap. A statement that seeks touches a handful of keys; one that scans touches thousands, so its chance of overlapping with another transaction is far higher. An index on the predicate and on foreign key columns often removes the deadlock entirely.
If every transaction touches Customers -> Invoices -> Payments in that order, cycles between them can't form. Keep transactions short and touch the hot rows last, so locks on them are held briefly.
RCSI removes reader/writer deadlocks because readers no longer take S locks. Writer/writer deadlocks remain. On Azure SQL Database and SQL Server 2025 with optimized locking enabled, TID locking and lock after qualification reduce the number and duration of row locks, which removes many update/update deadlocks; it is not a guarantee.
The whole transaction was rolled back, so the retry must re-run the whole unit of work, not just the failed statement. It must be idempotent (idempotency keys, conditional updates, outbox for side effects). Use exponential backoff with jitter and a small limit (3 to 5).
SELECT ... WITH (HOLDLOCK) followed by UPDATE in two sessions, then fix it with UPDLOCK, HOLDLOCK.UPDATE ... WHERE and measure how often a concurrent load test deadlocks, then add it back.Pull recent deadlock graphs from system_health (SQL Server or Managed Instance):
SELECT x.ev.value('@timestamp', 'datetime2') AS occurred_utc,
x.ev.query('(data/value/deadlock)[1]') AS deadlock_graph
FROM (
SELECT CAST(event_data AS xml) AS e
FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL)
WHERE object_name = 'xml_deadlock_report'
) AS d
CROSS APPLY d.e.nodes('/event') AS x(ev)
ORDER BY occurred_utc DESC;
-- Azure SQL Database: database-scoped session
CREATE EVENT SESSION deadlocks ON DATABASE
ADD EVENT sqlserver.database_xml_deadlock_report
ADD TARGET package0.ring_buffer;
ALTER EVENT SESSION deadlocks ON DATABASE STATE = START;
The fix: consistent order, an index, and an idempotent retry from .NET.
CREATE INDEX IX_Invoices_CustomerId ON dbo.Invoices (CustomerId); -- seek instead of clustered scan
namespace Billing.Data;
using Microsoft.Data.SqlClient;
public static class DeadlockRetry
{
// Re-runs the WHOLE unit of work: SQL Server already rolled the transaction back.
public static async Task<T> ExecuteAsync<T>(Func<CancellationToken, Task<T>> unitOfWork, CancellationToken ct, int maxAttempts = 4)
{
for (var attempt = 1; ; attempt++)
{
try
{
return await unitOfWork(ct);
}
catch (SqlException ex) when (ex.Number == 1205 && attempt < maxAttempts)
{
var delay = TimeSpan.FromMilliseconds(50 * Math.Pow(2, attempt) + Random.Shared.Next(0, 50));
await Task.Delay(delay, ct); // backoff with jitter so the two sides don't collide again
}
}
}
}
// Usage: the unit of work must be idempotent (e.g. keyed on InvoiceId + PaymentId).
// await DeadlockRetry.ExecuteAsync(ct => payments.ApplyAsync(invoiceId, paymentId, ct), ct);
In EF Core, EnableRetryOnFailure() on the SQL Server provider already treats 1205 as transient; wrap explicit transactions in CreateExecutionStrategy().ExecuteAsync(...).
NOLOCK to the reading side. Why it is wrong: It returns wrong data and doesn't help writer/writer deadlocks. Instead: RCSI, or a covering index for key lookup deadlocks.DEADLOCK_PRIORITY HIGH on the important job. Why it is wrong: It just moves the failure to the other side. Instead: Remove the cycle.TransactionScope is a common hidden cause. Instead: Check isolationlevel on every process.Deadlocks are a design signal: they tell you two code paths disagree about order or lock far more than they need. At scale a small residual rate is normal, so the senior position is 'minimise, then tolerate safely': indexes and access order first, isolation second, idempotent retries always, and an alert so you notice when the rate changes after a release.
| Fix | When it fits | Cost | When not to |
|---|---|---|---|
| Index the predicate / FK | Scans in the graph | Write overhead | Already seeking |
| Consistent access order | Opposite-order cycles | Refactor code paths | Single-table conversion deadlocks |
UPDLOCK on read |
Read-then-update conversions | Serialises updaters | Pure reporting reads |
| RCSI | Reader/writer deadlocks | Version store | Writer/writer cycles |
| Retry 1205 | Residual deadlocks | Latency on retry | Non-idempotent side effects |
Blocking is sessions waiting for locks another session holds. I find the head blocker by following blocking_session_id in sys.dm_exec_requests to the session that isn't blocked itself, or with sp_WhoIsActive @find_block_leaders = 1. Then I check what it is: a running query, or a sleeping session with open_transaction_count > 0, which means the app opened a transaction and never finished it.
Typical .NET causes: transactions left open around slow work or HTTP calls, scans caused by missing indexes locking far more rows than needed, lock escalation from big batches, and leaked connections. Mitigation may be KILL, but the fix is indexing, shorter transactions and RCSI so readers don't wait on writers.
Isolation levels decide which anomalies a transaction can see. Read uncommitted takes no shared locks, so dirty reads are possible (it's what NOLOCK does). Read committed, the default, only reads committed data, using short-lived S locks, or row versions when RCSI is on, but a re-read can change (non-repeatable read). Repeatable read holds S locks to the end of the transaction, so rows you read can't change, but new rows can appear (phantoms). Serializable adds key-range locks so ranges can't change either. Snapshot gives a transaction-consistent view from row versions.
The trade-off: each step up holds more locks for longer, which means more blocking and deadlocks. Pick the lowest level that is correct, and solve specific races with targeted locks or constraints.
If the connection drops during COMMIT, the client can't know whether the transaction committed, and a blind retry may apply the work twice. Make the unit idempotent (a unique request id checked at the start and enforced by a unique index), or use ExecuteInTransactionAsync with a verifySucceeded delegate that queries the database to see if the work landed before retrying. Clear the change tracker between attempts so stale Added entities aren't re-sent. Only transient errors should be retried: let permanent failures (constraint violations, login failures) surface immediately. Log each retry and its outcome so an in-doubt commit can be traced and reconciled later.
How to tell it (STAR)
**S:** Every month-end our invoicing job and the payments API deadlocked [around 40] times in the first hour, which delayed invoices. **T:** I owned [the billing service] and needed the deadlocks gone before the next month-end. **A:** I pulled the deadlock graphs from system_health and found two patterns: opposite access order between invoices and payments, and an update scanning the clustered index because `CustomerId` wasn't indexed. I added the index, aligned the payments code to the same table order as everything else, enabled RCSI, and added an idempotent retry with backoff for the rare remaining case. **R:** The next three month-ends had [zero] deadlocks, the retry fired [twice] in total, and an alert now tells us if the rate changes after a release.
Last updated 23 Nov 2026.