A STAR story for SQL Server deadlocks or blocking: system_health deadlock graphs, head blockers, the lock-order or index cause, the fix, retries and verification.
I tell it as capture → read → fix the access pattern → verify. Every [month-end] the [invoicing job] threw bursts of error 1205. I pulled the deadlock graphs from the system_health Extended Events session, which SQL Server keeps by default, and they showed two processes taking locks on [Invoices] and [Payments] in opposite order, made worse by a missing index that turned an update into a scan. I fixed the order, added the index (after checking its write cost and the plans it changed), shortened the transaction, and kept a retry on 1205 only after confirming both operations were idempotent, so a replay couldn't double-allocate a payment. I verified by counting deadlocks per night from system_health and watching LCK_M_* waits in Query Store: [~200] to zero. The trade-off: RCSI removes reader-writer blocking but not writer-writer deadlocks and adds tempdb load.
"At [company] the [billing system] on [Azure SQL] had a known problem: every month-end, when [the invoicing batch] ran alongside [payment allocation], we got bursts of deadlock errors, around [200] in a night, and finance had to re-run [failed invoices] by hand the next morning. People had added retries, which hid most of it, but not all.
I pulled the deadlock graphs from the
system_healthExtended Events session with a query against the ring buffer and event files. Every graph had the same shape: the batch updatedInvoicesthen inserted intoPayments, while payment allocation updatedPaymentsthen updatedInvoices. Opposite order, classic cycle. The graph also showed the batch's update held key-range locks on a large part ofInvoices, because there was no index on [CustomerId, Status], so it scanned and locked far more rows than it changed.I changed payment allocation to touch
Invoicesfirst, so both paths take locks in the same order, added the covering index so the update only locked the rows it needed, and moved [an external call] out of the transaction, which cut its length from [~2 s] to [~80 ms]. I kept the EF Core execution strategy retry for 1205 because deadlocks can never be fully ruled out. I tracked deadlock count per night fromsystem_health: the next month-end had [zero], and the manual re-runs stopped. What I took away is that a retry is a seatbelt, not a fix: the deadlock graph tells you exactly which access pattern to change."
| Blocking | Deadlock | |
|---|---|---|
| What it is | One session waits for another's lock | A cycle: each waits for the other |
| Resolves by | The blocker finishing | Lock monitor kills a victim (error 1205), about every 5 seconds it checks |
| Symptom | Timeouts, LCK_M_* waits |
Error 1205 |
| Evidence | sys.dm_exec_requests blocking_session_id, sp_WhoIsActive, blocked process report |
xml_deadlock_report in system_health |
| Cause | Fix |
|---|---|
| Opposite access order | Same order everywhere (e.g. parent then child) |
| Missing index -> scans lock too much | Index so the statement seeks |
| Long transactions (external calls, user think time) | Do work outside the transaction; keep it short |
| Reader-writer conflicts | RCSI / snapshot isolation |
| Lock escalation to table | Smaller batches (< 5,000 locks), better indexes |
| Serializable by default (TransactionScope) | Use ReadCommitted explicitly |
Template: [billing system], [~200] deadlocks per month-end between [invoicing] and [payment allocation]; graph showed opposite lock order plus a scan; fixed order, added index, shortened transaction from [2 s] to [80 ms]; deadlocks went to [0] and [N hours] of manual re-runs per month stopped.
Checks whether you can read SQL Server's evidence, fix the locking cause without sacrificing correctness, and verify the outcome.
Green flags
Red flags
This checks whether you understand locking well enough to read a deadlock graph, whether you fix the access pattern rather than just retrying, and whether you protect correctness (you didn't use NOLOCK or drop a transaction to make the errors go away).
Session A (invoicing) Session B (payment allocation)
UPDATE Invoices -> X lock I1 UPDATE Payments -> X lock P7
INSERT Payments -> waits P7 UPDATE Invoices -> waits I1
\______________ cycle ______________/
Lock monitor detects the cycle -> picks the cheaper victim -> error 1205
The victim is chosen by DEADLOCK_PRIORITY and then by the cost to roll back. The graph lists each process, its statement, the resources (KEY, PAGE, OBJECT with index names) and the lock modes held and requested.
SQL Server's system_health session captures xml_deadlock_report by default, on Azure SQL Database too (through the database's event file / sys.fn_xe_file_target_read_file, depending on the platform). For blocking, enable the blocked process report (blocked process threshold) on SQL Server, or use sys.dm_exec_requests, sys.dm_os_waiting_tasks and sp_WhoIsActive. Query Store wait stats show the trend of LCK_M_* waits over time.
Use STAR; the most impressive part is reading the graph, so give it one clear sentence. SOAR fits if the obstacle was that retries had hidden the problem and nobody had evidence.
Weak: "we added NOLOCK" or "we added retries". Good: explains the cycle. Strong: names the graph, the access order and the index. Excellent: verified with counts, kept a retry as a seatbelt, and explained why RCSI was or wasn't used.
The same story answers "a time you fixed a long-standing problem others had worked around" and "a time you improved a business process" (finance's manual re-runs). For a non-technical interviewer: "Two jobs were grabbing the same records in opposite order and getting stuck; I made them take turns in the same order."
system_health for xml_deadlock_report and open the graph in SSMS.sys.dm_tran_locks.The evidence query and the safety-net retry used in the story.
-- Deadlock graphs from system_health (SQL Server; on Azure SQL DB use the event file for the database)
SELECT
xed.value('@timestamp', 'datetime2') AS deadlock_time,
xed.query('.') AS deadlock_graph
FROM (
SELECT CAST(target_data AS xml) AS target_data
FROM sys.dm_xe_session_targets t
JOIN sys.dm_xe_sessions s ON s.address = t.event_session_address
WHERE s.name = 'system_health' AND t.target_name = 'ring_buffer'
) AS d
CROSS APPLY target_data.nodes('RingBufferTarget/event[@name="xml_deadlock_report"]') AS x(xed)
ORDER BY deadlock_time DESC;
-- The index that stopped the update from scanning (and locking) most of the table
CREATE INDEX IX_Invoices_CustomerId_Status ON dbo.Invoices (CustomerId, Status) INCLUDE (Total);
namespace Billing.Infrastructure;
// Safety net, not the fix: EF Core's SQL Server execution strategy retries transient errors,
// including deadlock victim 1205, and replays the whole unit of work.
public static class BillingDbRegistration
{
public static IServiceCollection AddBillingDb(this IServiceCollection services, string cs) =>
services.AddDbContext<BillingDbContext>(o => o.UseSqlServer(cs, sql =>
sql.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(2),
errorNumbersToAdd: null)));
}
STAR template
S: [System] on [SQL Server / Azure SQL]; [N deadlocks] when [job A] and [job B] overlapped.
T: I [took on] removing them, not just retrying.
A: Pulled graphs from system_health; saw [opposite order / scan]; fixed [order, index, transaction length]; kept retry as safety net.
R: Deadlocks [N -> 0]; [manual work / failed jobs] eliminated; verified over [period].
Illustrative only: billing month-end, ~200 deadlocks; opposite lock order + missing index; 0 the next month-end.
WITH (NOLOCK) to make it go away. Why it is wrong: Dirty reads, missing or duplicated rows; it doesn't stop writer-writer deadlocks. Instead: Fix the access pattern; consider RCSI for reader-writer blocking.sys.dm_exec_requests / sp_WhoIsActive into a table, alert on blocking duration and deadlock count, and watch LCK_M_* waits in Query Store.Seniors treat a deadlock graph as a precise bug report: it names the statements, the resources and the order. The senior answer fixes the design (order, indexes, transaction scope), keeps a retry for the irreducible remainder, and protects correctness. Mentioning that you checked whether an idempotent retry was safe for the operation (no double-charging) is a strong signal.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Consistent access order | Opposite-order cycles | Code change across paths | Order is dictated by external flows (then use app locks) |
| Index so statements seek | Scans locking too much | Write overhead, storage | Index won't be selective |
| RCSI | Reader-writer blocking | tempdb version store, semantic change | Writer-writer deadlocks |
sp_getapplock / UPDLOCK |
Serialise a critical section deliberately | Throughput | High-concurrency hot paths |
| Retry on 1205 | Always, as a seatbelt | Extra load | As the only fix; non-idempotent operations |
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.
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.
Optimistic concurrency assumes conflicts are rare: read the row with its rowversion, and when saving run UPDATE ... WHERE Id = @id AND RowVersion = @original. If 0 rows are affected, someone else changed it: return 409/412 and let the user reload or merge. No locks are held between read and write, so it suits web forms with user think time.
Pessimistic concurrency locks first: inside a short transaction, SELECT ... WITH (UPDLOCK, HOLDLOCK) so no one else can take the row until you commit; for job queues, UPDLOCK, READPAST lets workers skip claimed rows. sp_getapplock locks a logical name (e.g. 'invoice-run-2026-11') when there's no single row to lock.
The trade-off: optimistic costs retries under contention; pessimistic costs blocking and deadlock risk.
How to tell it (STAR)
**S:** At [company], our [billing system] on [Azure SQL] hit around [200] deadlocks every month-end when the invoicing batch overlapped payment allocation, and finance re-ran failed invoices by hand. **T:** I [took on] fixing it properly rather than adding more retries. **A:** I pulled the deadlock graphs from the system_health session. They showed the two jobs locking invoices and payments in opposite order, and a missing index made the update scan and lock far more rows than it needed. I changed allocation to use the same order, added the index, moved an external call out of the transaction so it shrank from [two seconds] to [80 milliseconds], and kept a retry only as a safety net after checking both operations were idempotent. **R:** The next month-end had [zero] deadlocks, the manual re-runs stopped, and we've had [none] in [N] months since.
Last updated 23 Nov 2026.