📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Every month-end your SQL Server logs a burst of deadlocks (error 1205) in the invoicing and payments code. How do you capture and read the deadlock graph from the system_health session, work out the cause, and fix it so it doesn't come back?

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.

Senior Debugging Advanced deadlocks debugging extended-events locking retry sql-server

🎯 Key points

  • Deadlock = cycle of waits; the lock monitor (every 5 s, more often right after finding one) picks a victim and raises 1205
  • system_health XE session captures xml_deadlock_report on SQL Server 2022/2025 and MI; Azure SQL Database needs a database-scoped XE session
  • Graph: process list (victim, isolationlevel, inputbuf), resource list (owner and waiter modes)
  • Patterns: opposite access order, S-to-X conversion, scan from missing index, serializable range locks, FK and cascade checks
  • Fix order: index to shrink footprint, consistent access order, targeted hints (UPDLOCK on read-then-update), RCSI for readers
  • Optimized locking (Azure SQL Database, opt-in on SQL Server 2025) reduces row-lock deadlocks
  • Retry 1205 with exponential backoff and jitter, only for idempotent units of work
  • Alert on deadlock count; don't use DEADLOCK_PRIORITY as the fix

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 Invoices and wanted a U lock on Payments; the payments API held X on Payments and wanted to update Invoices. Classic opposite access order. There was a second pattern too: the job's UPDATE Invoices ... WHERE CustomerId = @c scanned the clustered index because CustomerId had 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 touch Invoices before Payments like 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."


Reading a deadlock graph

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

Common patterns and fixes

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

Production example

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.

🔍 What the interviewer is checking

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

  • Goes to system_health or an XE session first
  • Reads owner/waiter modes and index names to find the pattern
  • Fixes with indexes and access order before retries
  • Insists retries re-run the whole idempotent unit of work
  • Proposes systemic prevention: an ADR for table access order and a deadlock-rate alert

Red flags

  • Uses NOLOCK or DEADLOCK_PRIORITY as the fix
  • Thinks deadlocks and blocking are the same
  • Retries non-idempotent operations blindly

📚 Learn in depth

1. How SQL Server detects deadlocks

The 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

2. Where to get the graph

  • SQL Server: the 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.
  • Azure SQL Database: no server-level system_health; create a database-scoped XE session with the database_xml_deadlock_report event to a ring buffer or an Azure Storage event file. Query Performance Insight and Intelligent Insights also flag deadlocks.
  • Azure SQL Managed Instance: system_health works as on SQL Server.
  • SSMS opens .xdl files as a picture; the XML holds more detail (execution stack, isolation level).

3. Reading the XML

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.

4. Why indexes fix so many deadlocks

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.

5. Access order and transaction shape

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.

6. Versioning and optimized locking

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.

7. Retry correctly

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).

Try it yourself

  1. Create two tables, open two SSMS windows and update them in opposite order to produce a 1205; then find the graph in system_health with the query in the code example.
  2. Reproduce a conversion deadlock with SELECT ... WITH (HOLDLOCK) followed by UPDATE in two sessions, then fix it with UPDLOCK, HOLDLOCK.
  3. Drop an index used by an UPDATE ... WHERE and measure how often a concurrent load test deadlocks, then add it back.
  4. Write an xUnit test with Testcontainers that runs two conflicting transactions in parallel and asserts the retry policy succeeds.

💻 Code

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(...).

⚠ Common mistakes

  • Mistake: Adding retries and calling it fixed. Why it is wrong: The deadlock rate grows with load, and non-idempotent retries duplicate side effects. Instead: Fix the cause, then retry idempotent units of work.
  • Mistake: Retrying immediately, without backoff, and without an idempotency check. Why it is wrong: The two sides collide again straight away, and a retry after an ambiguous failure can charge or email twice. Instead: Exponential backoff with jitter, a small attempt limit, and idempotency keys or conditional updates.
  • Mistake: Retrying only the failed statement. Why it is wrong: The whole transaction was rolled back; earlier statements are gone. Instead: Re-run the entire unit of work.
  • Mistake: Adding 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.
  • Mistake: Setting DEADLOCK_PRIORITY HIGH on the important job. Why it is wrong: It just moves the failure to the other side. Instead: Remove the cycle.
  • Mistake: Turning on trace flag 1222 and reading the error log. Why it is wrong: system_health already captures richer XML. Instead: Query system_health or a dedicated XE session.
  • Mistake: Ignoring the isolation level in the graph. Why it is wrong: Serializable from a default TransactionScope is a common hidden cause. Instead: Check isolationlevel on every process.
  • Mistake: Not indexing foreign keys. Why it is wrong: FK checks and cascades scan child tables and widen locks. Instead: Index FK columns used in deletes and joins.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate confuses deadlocks with long blocking. Why: Checks the difference between a queue and a cycle.
    How to answer

    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.

  2. When: Candidate sees serializable in the graph. Why: Checks isolation-level knowledge behind range-lock deadlocks.
    How to answer

    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.

  3. When: Candidate talks about retry policies or EF Core execution strategies. Why: Checks the commit-in-doubt edge case of retries.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Month-end deadlocks between invoicing and payments
Situation
A billing platform on [SQL Server 2022 / Azure SQL MI]: a month-end invoicing job generates [N] invoices while the payments API keeps applying payments. Failures delay invoices to [customers].
Signals
Spike of `SqlException` number 1205 in Application Insights in the first hour of each month; failed job items in the invoicing log; deadlock count in the system_health session jumping from near zero to [40+].
Investigation
Extracted `xml_deadlock_report` events from system_health for the window. Two patterns: (1) invoice job held X on `Invoices` and waited for U on `Payments`, the API held X on `Payments` and waited on `Invoices`: opposite access order. (2) The job's update locked many keys on the clustered index of `Invoices` for a `CustomerId` predicate: a scan from a missing index. Confirmed the scan with the actual execution plan and `SET STATISTICS IO ON` ([N] logical reads).
Resolution
Immediate: wrapped both units of work in a 1205 retry with jittered backoff after confirming they were idempotent (keyed on InvoiceId and PaymentId). Real fix: added `IX_Invoices_CustomerId`, changed the payments path to update `Invoices` before `Payments` like every other path, and turned on RCSI to remove reader/writer deadlocks from reports.
Prevention
Documented the table access order in an ADR; added an alert on deadlocks per hour from the XE data; a month-end load test in staging with production-like volumes; FK-index check in the schema review checklist.

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.

↩ Usually asked after

More in Transactions and Locking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me