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

📚 Interview question

Users report that pages time out, and in SQL Server you see dozens of sessions waiting on LCK_M_ waits. How do you find the head blocker, work out what it is doing, and fix the cause? What usually causes blocking in a .NET application?

Diagnosing SQL Server blocking: finding the head blocker with sys.dm_exec_requests, sp_WhoIsActive and the blocked process report, reading what it holds, and fixing the usual .NET causes (open transactions, missing indexes, escalation, chatty transactions).

Mid-Level Debugging Intermediate blocking debugging dmv locking sp-whoisactive sql-server

🎯 Key points

  • Blocking chain: follow blocking_session_id to the head blocker
  • sys.dm_exec_requests and sys.dm_exec_sessions with open_transaction_count
  • Sleeping head blocker = open transaction left by the app
  • sp_WhoIsActive @find_block_leaders = 1; history from the blocked process report, Query Store wait stats or Azure SQL Intelligent Insights
  • Causes: missing index scans, long transactions, external calls inside a transaction
  • Lock escalation: batch DML under ~5,000 locks, index, or partition with LOCK_ESCALATION = AUTO
  • Mitigate with KILL only after checking rollback cost
  • Fix with indexes, shorter transactions and RCSI for readers (not NOLOCK)

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"Blocking isn't a deadlock: it's a queue, and the whole queue is waiting on one or two sessions at the front. So the first job is to find the head blocker. I query sys.dm_exec_requests for rows with a non-zero blocking_session_id and follow the chain until I reach a session that isn't blocked by anyone. sp_WhoIsActive with @find_block_leaders = 1 does that for me and shows the SQL text, the wait and the number of sessions behind it.

Then the important question is whether the head blocker is running or sleeping. If it's running, it's a slow statement and I look at its plan: usually a scan because of a missing index, so it locks far more rows than it needs, sometimes escalating to a table lock. If it's sleeping with an open transaction, the app started a transaction and isn't doing anything in the database. For example, at [company] a checkout endpoint opened a transaction, updated stock, then called the payment gateway inside it. When the gateway slowed down to [8] seconds, every other checkout queued behind those row locks. We moved the gateway call out of the transaction and the timeouts went from [hundreds an hour] to zero.

To mitigate, I might KILL the head blocker, but only after checking how much it has done, because the rollback holds the locks too. For the fix: indexes so writes touch only their rows, short transactions with no external calls, batching big jobs below the escalation threshold, and RCSI so reports stop being blocked by writers. The mistake I see is putting NOLOCK on the readers. That hides the symptom and returns wrong data. Find the front of the queue and make it shorter."


Triage queries and tools

Tool What it tells you
sys.dm_exec_requests Running requests, blocking_session_id, wait_type, wait_time
sys.dm_exec_sessions Status (sleeping), open_transaction_count, host and program name
sys.dm_tran_locks Which resources the head blocker holds
sp_WhoIsActive One-call view with SQL text, plan and block leaders
Blocked process report (XE) History of blocking longer than a threshold
Application Insights dependencies Which endpoint and SQL call timed out

Usual causes in .NET apps

Cause Signal Fix
Transaction around slow non-database work Sleeping head blocker, open transaction Move work outside the transaction
Missing index Running head blocker, scan in plan, many locks Add the index
Lock escalation OBJECT X lock in sys.dm_tran_locks Batch, index, partition
Leaked connection or transaction Sleeping session for minutes, program_name = your app await using, always commit or roll back
Readers waiting on writers LCK_M_S waits RCSI

Production example

A reporting query blocked order writes every morning: [40] sessions waiting for up to [30] seconds. The head blocker was the report, scanning Orders under repeatable read set by an old connection string. Switching it to read committed with RCSI and adding a covering index removed the blocking and cut the report from [45] to [6] seconds.

🔍 What the interviewer is checking

Checks a methodical approach to a live blocking incident and knowledge of the real root causes in .NET applications.

Green flags

  • Follows the chain to the head blocker and checks if it is sleeping
  • Names sys.dm_exec_requests, sp_WhoIsActive or the blocked process report
  • Connects blocking to transaction scope in application code
  • Separates mitigation from the long-term fix

Red flags

  • Proposes NOLOCK everywhere
  • Kills sessions without thinking about rollback
  • Confuses blocking with deadlocks

📚 Learn in depth

1. Blocking vs deadlock

Blocking:  S1 holds X on row 7  <-  S2 waits  <-  S3 waits  <-  S4 waits
           (resolves when S1 commits)
Deadlock:  S1 waits for S2, S2 waits for S1  (never resolves; engine kills one)

Blocking is normal for microseconds. It becomes a problem when the head blocker holds locks for seconds.

2. Finding the head blocker

A head blocker appears as a blocking_session_id of others but has blocking_session_id = 0 itself. A sleeping head blocker won't appear in sys.dm_exec_requests at all, because it has no active request: you find it in sys.dm_exec_sessions with open_transaction_count > 0, and its last statement via sys.dm_exec_connections.most_recent_sql_handle.

3. Running vs sleeping head blocker

State Meaning Look at
running/runnable A slow statement Actual plan, logical reads, missing index
suspended (non-lock wait) Waiting on I/O, memory grant, network (ASYNC_NETWORK_IO) Wait type; ASYNC_NETWORK_IO means the client reads slowly
sleeping + open transaction App holds the transaction App code, connection pool, external calls

ASYNC_NETWORK_IO deserves a mention: a .NET client that streams a large result and processes each row slowly keeps locks (under higher isolation levels) and the request open.

4. Capturing blocking you missed

Set the blocked process threshold (seconds) and capture the blocked_process_report event with Extended Events. In Azure SQL Database you can use Extended Events on the database, and Intelligent Insights or Query Performance Insight show lock wait spikes.

EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'blocked process threshold (s)', 10; RECONFIGURE;

5. Killing safely

KILL <spid> rolls back the transaction, and the rollback holds the same locks. KILL <spid> WITH STATUSONLY shows the rollback progress. With ADR (always on in Azure SQL Database) rollback is near-instant.

6. Fixing the root cause

  • Index so the statement seeks and locks only target rows.
  • Keep transactions short: read and compute outside, write inside, no HTTP calls.
  • Turn on RCSI so readers use versions and stop taking S locks.
  • Batch large DML.
  • In .NET, await using every connection and transaction, and set CommandTimeout sensibly so a stuck query doesn't hold locks forever.

Try it yourself

  1. Open a transaction in SSMS, update a row and leave the window; query that row from two other windows; find the head blocker with the query in the code example.
  2. Install sp_WhoIsActive in a test database and run it with @find_block_leaders = 1, @get_plans = 1.
  3. Configure a blocked process report session and generate a 15-second block; read the XML.
  4. Turn on RCSI and repeat step 1: which sessions still block?

💻 Code

Find the head blocker and what it is running, including sleeping blockers.

-- Who is blocked, by whom, and on what
SELECT r.session_id, r.blocking_session_id, r.wait_type, r.wait_time / 1000.0 AS wait_s,
       r.wait_resource, t.text AS sql_text
FROM sys.dm_exec_requests AS r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t
WHERE r.blocking_session_id <> 0;

-- Head blockers: block others but are not blocked themselves (catches sleeping sessions too)
SELECT s.session_id, s.status, s.host_name, s.program_name, s.open_transaction_count,
       s.last_request_end_time, t.text AS last_sql
FROM sys.dm_exec_sessions AS s
JOIN sys.dm_exec_connections AS c ON c.session_id = s.session_id
CROSS APPLY sys.dm_exec_sql_text(c.most_recent_sql_handle) AS t
WHERE s.session_id IN (SELECT blocking_session_id FROM sys.dm_exec_requests WHERE blocking_session_id <> 0)
  AND s.session_id NOT IN (SELECT session_id FROM sys.dm_exec_requests WHERE blocking_session_id <> 0);

-- Or: EXEC sp_WhoIsActive @find_block_leaders = 1, @get_plans = 1, @sort_order = '[blocked_session_count] DESC';

The usual .NET cause, and the fix:

namespace Shop.Checkout;

using Microsoft.Data.SqlClient;

public sealed class CheckoutService(string connectionString, IPaymentGateway payments)
{
    public async Task CheckoutAsync(Guid orderId, decimal amount, CancellationToken ct)
    {
        // Before: BeginTransaction -> reserve stock -> await payments.ChargeAsync(...) -> Commit
        // Row locks were held for the whole gateway call (seconds), blocking every other checkout.

        // After: the slow external call happens outside any transaction.
        var charge = await payments.ChargeAsync(orderId, amount, ct);

        await using var conn = new SqlConnection(connectionString);
        await conn.OpenAsync(ct);
        await using var tx = (SqlTransaction)await conn.BeginTransactionAsync(ct);
        await using var cmd = new SqlCommand(
            "UPDATE dbo.Orders SET Status = 'Paid', PaymentRef = @ref WHERE OrderId = @id AND Status = 'Pending';",
            conn, tx) { CommandTimeout = 5 };
        cmd.Parameters.AddWithValue("@ref", charge.Reference);
        cmd.Parameters.AddWithValue("@id", orderId);
        await cmd.ExecuteNonQueryAsync(ct);
        await tx.CommitAsync(ct); // locks held for milliseconds
    }
}

public interface IPaymentGateway
{
    Task<ChargeResult> ChargeAsync(Guid orderId, decimal amount, CancellationToken ct);
}

public sealed record ChargeResult(string Reference);

⚠ Common mistakes

  • Mistake: Only looking at sys.dm_exec_requests for the head blocker. Why it is wrong: A sleeping session holding an open transaction has no request row. Instead: Check sys.dm_exec_sessions.open_transaction_count.
  • Mistake: Adding NOLOCK to every blocked query. Why it is wrong: Read uncommitted returns dirty, missing or duplicated rows and does nothing for blocked writers. Instead: Enable RCSI so readers get the last committed version without S locks, and fix the head blocker.
  • Mistake: Killing the head blocker without checking its work. Why it is wrong: A long rollback keeps the locks and can take as long as the work did. Instead: Check transaction age and log used, and use KILL ... WITH STATUSONLY.
  • Mistake: Calling HTTP services or message brokers inside a database transaction. Why it is wrong: Locks are held for network latency and outages. Instead: Use the outbox pattern or do the call before or after.
  • Mistake: Raising CommandTimeout to make the errors go away. Why it is wrong: It is a stopgap: users wait longer, more sessions pile up behind the same locks, and the root cause stays. Instead: Shorten lock duration and footprint with indexes and smaller transactions.
  • Mistake: Running one huge DELETE or UPDATE during business hours. Why it is wrong: It escalates to a table lock and blocks every writer. Instead: Batch under the escalation threshold or partition and switch out.
  • Mistake: Confusing blocking with deadlocks. Why it is wrong: They need different diagnostics (blocked process report vs deadlock graph). Instead: Check for error 1205 to tell them apart.

🏛 Senior insight: trade-offs

Blocking is a symptom of lock duration multiplied by lock footprint. Duration comes from application design (transaction scope, external calls, slow clients) and footprint from the plan (scans, escalation). A senior engineer separates mitigation (kill, fail over traffic) from cure, and leaves monitoring behind: an alert on blocked process reports or on lock wait time catches the next one before users do.

Fix When it fits Cost When not to
Index the blocking statement Head blocker scans Write overhead per index Table is write-hot and the query is rare
Shorten the transaction Sleeping or chatty head blockers Code change, maybe outbox Work that must be atomic with the external call (use a saga instead)
RCSI Readers blocked by writers Version store in tempdb Writers blocked by writers (no effect)
KILL Incident in progress Rollback time, failed user request As a routine fix

🔗 Follow-ups the interviewer may ask

  1. When: Candidate distinguishes blocking from deadlocks. Why: Checks the candidate can handle the cyclic case, not just queues.
    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 mentions a purge or delete job as the head blocker. Why: Checks the foreign-key and escalation version of blocking.
    How to answer

    When you delete a parent row, SQL Server must check every child table that references it. If the child's foreign key column has no index, each check is a table scan, and the delete's locks are held for the whole long statement. A large delete also escalates to a table lock after about 5,000 locks, blocking everyone.

    I'd confirm it from the actual plan (a scan of the child under the FK check, huge logical reads) and the blocking chain (sys.dm_exec_requests, sp_WhoIsActive). The fix: index the FK columns, delete in small batches with short transactions, and avoid wide cascades. Separately, constraints created WITH NOCHECK are untrusted, so the optimiser cannot use them; re-validate with WITH CHECK CHECK CONSTRAINT once the data is clean.

  3. When: Candidate suggests RCSI to stop readers waiting. Why: Checks what RCSI costs and how it behaves with EF Core.
    How to answer

    New Azure SQL Database databases have READ_COMMITTED_SNAPSHOT (RCSI) on by default (on-premises SQL Server doesn't; check is_read_committed_snapshot_on in sys.databases for your database). With RCSI each statement reads a consistent committed version without blocking writers. For several statements to see the same version, use IsolationLevel.Snapshot (needs ALLOW_SNAPSHOT_ISOLATION ON). The cost is the row-version store (tempdb, or the persistent version store when accelerated database recovery is on, as it always is in Azure SQL Database), a 14-byte versioning tag added to modified rows, and update conflicts (error 3960) under snapshot that you must retry.

🛠 Real-world problems: how you handle them

Checkout timeouts caused by a payment call inside a transaction
Situation
An ASP.NET Core checkout API on Azure SQL Database, about [N] orders an hour at peak. During a [sale event] checkout requests started timing out after 30 seconds.
Signals
Application Insights showed SQL dependency durations jumping from [20 ms] to 30 seconds with `Execution Timeout Expired`; Azure SQL showed high lock wait time but normal CPU; support tickets about failed payments that had actually been charged.
Investigation
Ran sp_WhoIsActive with `@find_block_leaders = 1`: the head blockers were sleeping sessions from the API with `open_transaction_count = 1`. `sys.dm_tran_locks` showed X key locks on popular products in `dbo.Stock`. The last SQL was the stock update. Correlating the session's host and time with Application Insights traces showed the request was waiting on the payment gateway, which had slowed to [8] seconds.
Resolution
Immediate: raised the gateway client timeout lower (fail fast) so transactions ended sooner, which drained the queue. Real fix: restructured checkout to reserve stock with a short atomic conditional update, call the gateway outside any transaction, then confirm the order in a second short transaction, with an idempotency key on the payment.
Prevention
Code review checklist item: no network calls inside a database transaction. Added an Extended Events blocked process report (threshold 10 seconds) with an alert, and a load test with a slowed gateway stub in CI.

How to tell it (STAR)

**S:** During [a sale event], our checkout API on Azure SQL started timing out, and customers were being charged without getting an order. **T:** I was [on call / the lead on the service] and had to stop the timeouts and find the cause. **A:** Application Insights showed SQL calls hitting the 30-second timeout while CPU was normal, which pointed at blocking. sp_WhoIsActive showed the head blockers were sleeping API sessions holding open transactions with X locks on hot stock rows. Tracing the requests showed they were waiting on the payment gateway, which had slowed to [8] seconds, inside the transaction. I shortened the gateway timeout to drain the queue, then restructured checkout so the payment call happens outside the transaction with an idempotency key. **R:** Lock waits disappeared, checkout p95 went from [30 s] back to [400 ms], and we added a blocked-process alert and a review rule so it didn't come back.

↩ Usually asked after

More in Transactions and Locking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me