Live blocking on Azure SQL: who, why, how (DMV query)
My troubleshooting DMV query: one row per head blocker with who it is, why it blocks (verdict, open transaction, isolation, log written) and how (locks held, waiting sessions and resources).
"The database is blocked!" Before reaching for KILL, I want three answers: who blocks, why it blocks, and how (which locks, on what, who waits behind). sp_who2 gives a session number and little else. Here is my DMV query: one row per head blocker, the session at the top of the chain, the one that blocks others without being blocked itself.
It works on Azure SQL Database, SQL Managed Instance and SQL Server. Read only: nothing is killed, nothing is changed. Permissions: VIEW DATABASE STATE on Azure SQL Database (otherwise you only see your own session), VIEW SERVER STATE elsewhere. Run it in the database where the blocking happens.
flowchart LR
H["Head blocker (who?)"] -->|"locks held (how?)"| B1["Blocked session 1"]
B1 --> B2["Blocked session 2"]
H --> V["Verdict (why?)"]
V --> T["Open transaction, isolation, log written"]
Reading the verdict
The verdicts follow the blocking scenarios Microsoft describes for Azure SQL Database:
| Verdict | What it means | What to do |
|---|---|---|
| Idle with an open transaction | sleeping session, open transaction: no COMMIT or ROLLBACK, often after a timeout |
Look at the application; KILL only with the session owner |
| ASYNC_NETWORK_IO | The client does not read every row: the locks stay until it fetches them all | Look at the application or the network |
| Long statement still running | A long statement holding its locks | Tune the statement, shorten the transaction |
| Rollback in progress | A rollback is running: the locks stay until it ends | Wait; LogBytesUsed gives its size |
| Statement waiting on ... | The statement waits on something else while holding its locks | Deal with that wait |
| Idle without open transaction | The blocking has probably just ended | Run it again |
Also look at: IsolationLevel at RepeatableRead or Serializable (locks kept until the end of the transaction), a high TransactionAgeSec, many WriteLocksHeld, and a big LogBytesUsed: a KILL would start a long rollback.
The query
DECLARE @HeadSessionId int = NULL; -- one head blocker only (NULL = all)
DROP TABLE IF EXISTS #Chain;
DROP TABLE IF EXISTS #Heads;
-- Blocking chains: every blocked session with its head blocker
WITH Blocked AS (
SELECT r.session_id, r.blocking_session_id, r.wait_time
FROM sys.dm_exec_requests AS r
WHERE r.blocking_session_id > 0
),
Chain AS (
SELECT b.blocking_session_id AS HeadSessionId, b.blocking_session_id AS DirectBlockerId,
b.session_id AS BlockedSessionId, b.wait_time AS WaitMs, 1 AS Depth
FROM Blocked AS b
WHERE NOT EXISTS (SELECT 1 FROM Blocked AS x WHERE x.session_id = b.blocking_session_id)
UNION ALL
SELECT c.HeadSessionId, b.blocking_session_id, b.session_id, b.wait_time, c.Depth + 1
FROM Chain AS c
JOIN Blocked AS b ON b.blocking_session_id = c.BlockedSessionId
)
SELECT HeadSessionId, DirectBlockerId, BlockedSessionId, WaitMs, Depth
INTO #Chain
FROM Chain
WHERE @HeadSessionId IS NULL OR HeadSessionId = @HeadSessionId
OPTION (MAXRECURSION 100);
SELECT HeadSessionId,
COUNT(*) AS BlockedSessions,
SUM(CASE WHEN Depth = 1 THEN 1 ELSE 0 END) AS DirectlyBlocked,
MAX(Depth) AS ChainDepth,
MAX(WaitMs) AS LongestWaitMs
INTO #Heads
FROM #Chain
GROUP BY HeadSessionId;
-- 1. Who and why
SELECT
h.HeadSessionId,
s.login_name AS LoginName, s.host_name AS HostName, s.program_name AS ProgramName,
c.client_net_address AS ClientAddress, DB_NAME(s.database_id) AS DatabaseName,
CASE
WHEN r.status = 'rollback'
THEN 'Rollback in progress: the locks stay until it ends'
WHEN r.session_id IS NULL AND s.open_transaction_count > 0
THEN 'Idle with an open transaction: the application did not COMMIT or ROLLBACK (often after a timeout or a cancel)'
WHEN r.session_id IS NULL
THEN 'Idle without open transaction: the blocking has probably just ended, run again'
WHEN r.wait_type = 'ASYNC_NETWORK_IO'
THEN 'The client does not read its results (ASYNC_NETWORK_IO): locks held until it fetches every row'
WHEN r.wait_type IS NULL OR r.status IN ('running', 'runnable')
THEN 'Long statement still running: tune it or shorten the transaction'
ELSE 'Statement waiting on ' + r.wait_type + ' while it holds its locks'
END AS Verdict,
s.status AS SessionStatus, r.status AS RequestStatus, r.command AS Command,
r.wait_type AS WaitType, r.wait_time AS WaitMs,
CASE COALESCE(r.transaction_isolation_level, s.transaction_isolation_level)
WHEN 1 THEN 'ReadUncommitted' WHEN 2 THEN 'ReadCommitted' WHEN 3 THEN 'RepeatableRead'
WHEN 4 THEN 'Serializable' WHEN 5 THEN 'Snapshot' ELSE 'Unspecified'
END AS IsolationLevel,
COALESCE(r.open_transaction_count, s.open_transaction_count) AS OpenTransactions,
tx.TransactionName, tx.TransactionBegin,
DATEDIFF(SECOND, tx.TransactionBegin, GETDATE()) AS TransactionAgeSec,
tx.TransactionType, tx.TransactionState, tx.LogBytesUsed,
s.last_request_start_time AS LastRequestStart, s.last_request_end_time AS LastRequestEnd,
CASE WHEN r.session_id IS NULL THEN DATEDIFF(SECOND, s.last_request_end_time, GETDATE()) END AS IdleSec,
h.BlockedSessions, h.DirectlyBlocked, h.ChainDepth, h.LongestWaitMs,
lk.LocksHeld, lk.WriteLocksHeld,
CASE WHEN r.session_id IS NOT NULL
THEN SUBSTRING(rt.text, (r.statement_start_offset / 2) + 1,
((CASE WHEN r.statement_end_offset = -1 THEN DATALENGTH(rt.text) ELSE r.statement_end_offset END
- r.statement_start_offset) / 2) + 1)
ELSE lt.text
END AS RunningOrLastStatement
FROM #Heads AS h
LEFT JOIN sys.dm_exec_sessions AS s ON s.session_id = h.HeadSessionId
LEFT JOIN sys.dm_exec_requests AS r ON r.session_id = h.HeadSessionId
LEFT JOIN sys.dm_exec_connections AS c ON c.session_id = h.HeadSessionId
OUTER APPLY sys.dm_exec_sql_text(r.sql_handle) AS rt
OUTER APPLY sys.dm_exec_sql_text(c.most_recent_sql_handle) AS lt
OUTER APPLY (
SELECT TOP (1)
tat.name AS TransactionName,
tat.transaction_begin_time AS TransactionBegin,
CASE tat.transaction_type
WHEN 1 THEN 'ReadWrite' WHEN 2 THEN 'ReadOnly' WHEN 3 THEN 'System' WHEN 4 THEN 'Distributed'
END AS TransactionType,
CASE tat.transaction_state
WHEN 0 THEN 'NotInitialized' WHEN 1 THEN 'NotStarted' WHEN 2 THEN 'Active'
WHEN 3 THEN 'Ended' WHEN 4 THEN 'CommitStarted' WHEN 5 THEN 'Prepared'
WHEN 6 THEN 'Committed' WHEN 7 THEN 'RollingBack' WHEN 8 THEN 'RolledBack'
END AS TransactionState,
(SELECT SUM(tdt.database_transaction_log_bytes_used)
FROM sys.dm_tran_database_transactions AS tdt
WHERE tdt.transaction_id = tat.transaction_id) AS LogBytesUsed
FROM sys.dm_tran_session_transactions AS tst
JOIN sys.dm_tran_active_transactions AS tat ON tat.transaction_id = tst.transaction_id
WHERE tst.session_id = h.HeadSessionId
ORDER BY tat.transaction_begin_time
) AS tx
OUTER APPLY (
SELECT COUNT(*) AS LocksHeld,
SUM(CASE WHEN tl.request_mode IN ('X', 'IX', 'SIX', 'U', 'IU', 'SIU', 'UIX') THEN 1 ELSE 0 END) AS WriteLocksHeld
FROM sys.dm_tran_locks AS tl
WHERE tl.request_session_id = h.HeadSessionId
AND tl.request_status = 'GRANT'
) AS lk
ORDER BY h.LongestWaitMs DESC;
-- 2. How: locks held by the head blockers, per object and mode
SELECT
tl.request_session_id AS HeadSessionId,
COALESCE(OBJECT_SCHEMA_NAME(p.object_id) + N'.' + OBJECT_NAME(p.object_id),
CASE WHEN tl.resource_type = 'OBJECT'
THEN OBJECT_SCHEMA_NAME(CONVERT(int, tl.resource_associated_entity_id)) + N'.'
+ OBJECT_NAME(CONVERT(int, tl.resource_associated_entity_id)) END,
tl.resource_type COLLATE DATABASE_DEFAULT) AS ObjectOrResource,
tl.resource_type AS LockResourceType,
tl.request_mode AS LockMode,
COUNT(*) AS LockCount
FROM sys.dm_tran_locks AS tl
JOIN #Heads AS h ON h.HeadSessionId = tl.request_session_id
LEFT JOIN sys.partitions AS p
ON tl.resource_database_id = DB_ID()
AND tl.resource_type IN ('KEY', 'PAGE', 'RID', 'HOBT')
AND p.hobt_id = tl.resource_associated_entity_id
WHERE tl.request_status = 'GRANT'
AND tl.resource_database_id = DB_ID()
GROUP BY tl.request_session_id,
COALESCE(OBJECT_SCHEMA_NAME(p.object_id) + N'.' + OBJECT_NAME(p.object_id),
CASE WHEN tl.resource_type = 'OBJECT'
THEN OBJECT_SCHEMA_NAME(CONVERT(int, tl.resource_associated_entity_id)) + N'.'
+ OBJECT_NAME(CONVERT(int, tl.resource_associated_entity_id)) END,
tl.resource_type COLLATE DATABASE_DEFAULT),
tl.resource_type, tl.request_mode
ORDER BY HeadSessionId, LockCount DESC;
-- 3. How: every blocked session and the lock it waits for
SELECT
ch.HeadSessionId, ch.DirectBlockerId, ch.BlockedSessionId, ch.Depth, ch.WaitMs,
r.wait_type AS WaitType, r.wait_resource AS WaitResource, wl.request_mode AS RequestedMode,
COALESCE(OBJECT_SCHEMA_NAME(p.object_id) + N'.' + OBJECT_NAME(p.object_id),
CASE WHEN wl.resource_type = 'OBJECT'
THEN OBJECT_SCHEMA_NAME(CONVERT(int, wl.resource_associated_entity_id)) + N'.'
+ OBJECT_NAME(CONVERT(int, wl.resource_associated_entity_id)) END) AS ObjectName,
s.login_name AS LoginName, s.host_name AS HostName, s.program_name AS ProgramName,
SUBSTRING(t.text, (r.statement_start_offset / 2) + 1,
((CASE WHEN r.statement_end_offset = -1 THEN DATALENGTH(t.text) ELSE r.statement_end_offset END
- r.statement_start_offset) / 2) + 1) AS BlockedStatement
FROM #Chain AS ch
LEFT JOIN sys.dm_exec_requests AS r ON r.session_id = ch.BlockedSessionId
LEFT JOIN sys.dm_exec_sessions AS s ON s.session_id = ch.BlockedSessionId
OUTER APPLY sys.dm_exec_sql_text(r.sql_handle) AS t
OUTER APPLY (
SELECT TOP (1) tl.request_mode, tl.resource_type, tl.resource_associated_entity_id, tl.resource_database_id
FROM sys.dm_tran_locks AS tl
WHERE tl.request_session_id = ch.BlockedSessionId
AND tl.request_status = 'WAIT'
) AS wl
LEFT JOIN sys.partitions AS p
ON wl.resource_database_id = DB_ID()
AND wl.resource_type IN ('KEY', 'PAGE', 'RID', 'HOBT')
AND p.hobt_id = wl.resource_associated_entity_id
ORDER BY ch.HeadSessionId, ch.Depth, ch.WaitMs DESC;
DROP TABLE IF EXISTS #Chain;
DROP TABLE IF EXISTS #Heads;
Lessons learned
- Nine times out of ten, the head blocker is a
sleepingsession with an open transaction: the application hit a timeout and dropped the request, but never the transaction. The fix belongs to the application (transaction handling after a timeout), not to the database. - The text shown for a
sleepingsession is its last statement, not necessarily the one that took the lock. For the history, see blocking history with Extended Events. - Deadlocks (cycles) have no head blocker and do not show up here: they are in my errors and deadlocks session.
- Before a
KILL, checkLogBytesUsed: killing a transaction that wrote gigabytes of log trades a blocking for a long rollback.