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

📚 Interview question

Tell me about SQL Server deadlocks or blocking you had to fix in production. How did you capture the evidence, what did the deadlock graph or blocking chain show, how did you fix it without breaking correctness, and how did you know it was gone?

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.

Senior RealWorldScenario Advanced deadlocks extended-events locking real-world sql-server star-story

🎯 Key points

  • Symptom: error 1205 bursts (deadlock victim) or LCK_M_* waits and timeouts
  • Captured deadlock graphs from system_health (xml_deadlock_report); blocking via DMVs or blocked process report
  • Read the graph: resources, lock modes, the two statements and their access order
  • Root cause: opposite lock order, missing index causing scans, long transaction, escalation
  • Fix: consistent order, covering index (write cost and plan changes checked), shorter transactions, RCSI where it fits
  • Retry on 1205 only after confirming the unit of work is idempotent
  • Verified: deadlocks per night and LCK waits in Query Store before/after
  • Proactive: alert on deadlock count and blocking duration

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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_health Extended Events session with a query against the ring buffer and event files. Every graph had the same shape: the batch updated Invoices then inserted into Payments, while payment allocation updated Payments then updated Invoices. Opposite order, classic cycle. The graph also showed the batch's update held key-range locks on a large part of Invoices, 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 Invoices first, 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 from system_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."


Deadlock vs blocking

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

Usual causes and fixes

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

Production example

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.

🔍 What the interviewer is checking

Checks whether you can read SQL Server's evidence, fix the locking cause without sacrificing correctness, and verify the outcome.

Green flags

  • Uses system_health deadlock graphs or blocking DMVs
  • Explains the cycle and the access order
  • Fixes order, indexes and transaction length; retry as a safety net
  • Verifies with counts and gives numbers

Red flags

  • NOLOCK or "more retries" as the fix
  • Can't tell blocking from deadlocks
  • No evidence or verification
  • Blames the DBA or another team

📚 Learn in depth

1. What the interviewer is really assessing

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

2. The mechanism

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.

3. Getting the evidence

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.

4. Frameworks for telling it

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.

5. How it is scored

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.

6. Adapting the story

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

Try it yourself

  1. In a test database, open two SSMS windows and create a deadlock by updating two tables in opposite order.
  2. Query system_health for xml_deadlock_report and open the graph in SSMS.
  3. Fix the order and confirm no deadlock.
  4. Create a scan-based deadlock by removing an index; add it back and compare locks with sys.dm_tran_locks.
  5. Write and time your STAR version.

💻 Code

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.

⚠ Common mistakes

  • Mistake: Adding 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.
  • Mistake: Presenting retries as the fix, or retrying without checking idempotence. Why it is wrong: They hide the cause, amplify load, and a replayed non-idempotent operation can double-charge or double-allocate. Instead: Retry as a seatbelt on idempotent units of work; fix the order and indexes.
  • Mistake: Confusing blocking with deadlocks. Why it is wrong: They have different evidence and fixes. Instead: Name which one it was.
  • Mistake: Only looking at blocking when users complain. Why it is wrong: By then timeouts have hit customers and the head blocker may be gone. Instead: Enable the blocked process report (threshold e.g. 10 s) on SQL Server or poll sys.dm_exec_requests / sp_WhoIsActive into a table, alert on blocking duration and deadlock count, and watch LCK_M_* waits in Query Store.
  • Mistake: Adding an index without checking its cost. Why it is wrong: Every index slows inserts and updates, takes space, and can change other queries' plans. Instead: Check write volume, compare plans in Query Store after the change, and remove overlapping indexes.
  • Mistake: Not reading the graph: "we guessed". Why it is wrong: The graph names the statements and resources. Instead: One sentence on what it showed.
  • Mistake: Turning on RCSI without checking tempdb and code that relies on blocking reads. Why it is wrong: Version store growth and changed semantics. Instead: Test and monitor tempdb.
  • Mistake: "We" throughout, or lock-mode jargon for a non-technical interviewer. Why it is wrong: Your role is invisible and the listener is lost. Instead: "I pulled the graphs; two jobs took the same records in opposite order."
  • Mistake: No verification. Why it is wrong: You can't claim it's fixed. Instead: Deadlock counts before and after.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions month-end deadlocks or error 1205. Why: Checks the technical drill-down: reading the graph and the fix options.
    How to 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.

  2. When: Candidate describes timeouts and blocking rather than deadlocks. Why: Checks they can find a head blocker and the usual .NET causes.
    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.

  3. When: Candidate mentions concurrency control, retries or two workers updating the same rows. Why: Checks optimistic vs pessimistic concurrency choices.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Month-end deadlocks between invoicing and payment allocation
Situation
[Billing system] on [Azure SQL], [~50,000] invoices generated at month-end by [a batch job] while [payment allocation] ran from the bank feed. Finance closed the books the next day, so failures delayed [reporting / customer statements].
Signals
[~200] error 1205 per month-end in Application Insights exceptions; failed invoice batches in the job log; finance re-running [N] invoices by hand; `LCK_M_X` and `LCK_M_U` waits spiking in Query Store wait stats during the window.
Investigation
Ruled out a platform issue (DTU/CPU fine) and a single bad deploy (pattern had existed for months, hidden by retries). Pulled `xml_deadlock_report` events from `system_health`: every graph showed the batch holding X locks on `Invoices` keys and requesting `Payments`, while allocation held `Payments` and requested `Invoices`. The batch's update showed a scan on the clustered index because there was no index on [`CustomerId, Status`], so it locked far more rows than it changed. Also found [a call to the tax service] inside the transaction, stretching it to [~2 s].
Resolution
Mitigation: scheduled payment allocation to pause during the batch window for one month-end. Real fix: changed allocation to touch `Invoices` before `Payments` (same order as the batch); added the covering index so the update seeks; moved the external call before the transaction (transaction [2 s] to [80 ms]); kept EF Core `EnableRetryOnFailure` and confirmed both operations are idempotent before relying on retries.
Prevention
A documented lock-order rule (parent before child) in the team's data-access guidelines; a nightly check counting deadlocks from system_health with an alert above [5]; an integration test running both jobs concurrently against a test database; code review rule: no external calls inside a transaction.

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.

More in Production Incidents

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me