Summary
The sneakiest performance problem is lock waiting. Because the query is not slow, CPU is not high, disk is not full. The query is just waiting. It cannot start because another transaction has not finished. In SQL Server this appears a bit differently than in other engines: With LCK_M_ waits, blocking chain, and deadlock graph. In this guide you will learn how to recognize a lock problem in SQL Server, how to find blocking and blocked queries in 5 minutes, how to safely release a lock, how to diagnose deadlocks, and how to prevent locks from recurring. This article completes the SQL Server leg of the Performance Pillar.
Scenario
Time is 14:07. The application team writes: Pages do not open, but database CPU usage is 15%. Disk is healthy, memory is enough, no slow query. Everything looks normal but nothing works. The DBA looks at sys.dm_exec_requests and sees the truth: 40 sessions look active but all are in LCK_M_X waiting. So 40 queries are not working, they are waiting. All of them wait for one transaction. That transaction has been open for 2 hours, contains an UPDATE, its owner went to lunch. One open transaction locked the whole system. This runbook shows what to do at that moment.
Concept: What Is a Lock, Why Does It Exist?
A lock is the mechanism the database uses to protect consistency. If two people update the same row at the same time, one must wait. Otherwise data corrupts. So a lock is not a bad thing. When used correctly, a lock protects the system.
The problem is a lock lasting longer than necessary. A short lock is normal, a long lock is a disaster.
Most common lock types in SQL Server:
- •Shared (S): Read lock. Taken when a transaction reads a row. Another transaction can also read the same row but cannot update it.
- •Exclusive (X): Write lock. Taken when a transaction updates a row. No other transaction can read or update that row.
- •Update (U): Update intent lock. First reads, then converts to Exclusive lock if it will update. Exists to reduce deadlocks.
- •Intent (IS, IX, IU): Intent lock. At a higher level, announces that a lock will be taken at a lower level. Taken at table level.
- •Schema (Sch-S, Sch-M): Schema lock. Related to table structure. During
ALTER TABLE, Sch-M is taken, nobody can access the table. - •Key-Range: Range lock. At
SERIALIZABLEisolation level, prevents new rows in a range.
There are 3 root causes of lock problems:
- 1Long transaction: As long as the transaction stays open, the lock stays open. If there is an HTTP call, sleep, user waiting inside the transaction, the lock lasts for hours.
- 2Wrong access order: If two transactions access the same tables in different order, deadlock occurs.
- 3Too many locked rows: An unindexed
UPDATElocks 1 million rows instead of 1 row. Everyone waits.
Step 1: Is the System Locked? Understand in 60 Seconds
First check if anyone is waiting.
SELECT
wait_type,
COUNT(*) AS cnt,
AVG(wait_time / 1000.0) AS avg_wait_sec,
MAX(wait_time / 1000.0) AS max_wait_sec
FROM sys.dm_exec_requests
WHERE session_id > 50
GROUP BY wait_type
ORDER BY cnt DESC;▸How to Interpret the Output?
- •If there is no waiting starting with
LCK_M_, you have no lock problem. Look elsewhere. - •If
LCK_M_Scount is low and short-lived, it is normal. Every system has momentary locks. - •If
LCK_M_Xcount is over 10 and increasing, a lock crisis has started. - •If
LCK_M_Xcount is over 30, you are already in crisis. Go to Step 2 immediately.
Interpret wait types:
| Wait | Meaning |
|---|---|
LCK_M_S | Waiting for shared lock, read waiting |
LCK_M_X | Waiting for exclusive lock, write waiting |
LCK_M_U | Waiting for update lock |
LCK_M_SCH_M | Waiting for schema modification lock, DDL running |
LCK_M_SCH_S | Waiting for schema stability lock |
If you see LCK_M_SCH_M, someone is changing table structure. Probably ALTER TABLE is running. Until that operation finishes, nobody can access the table.
Step 2: Who Blocks Whom? Find the Blocking Chain
This is the main query of this runbook. It shows the chain between blocking and blocked.
SELECT
r.session_id AS blocked_session,
r.blocking_session_id AS blocking_session,
r.wait_type AS wait_type,
r.wait_time / 1000.0 AS wait_sec,
r.cpu_time / 1000.0 AS cpu_sec,
r.logical_reads AS logical_reads,
LEFT(st.text, 150) AS blocked_query,
LEFT(bt.text, 150) AS blocking_query
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) st
LEFT JOIN sys.dm_exec_requests br
ON br.session_id = r.blocking_session_id
OUTER APPLY sys.dm_exec_sql_text(br.sql_handle) bt
WHERE r.blocking_session_id <> 0
ORDER BY r.wait_time DESC;▸How to Read the Output?
The table tells you this:
- •
blocked_session: Waiting query. Innocent, just waiting its turn. - •
blocking_session: Query holding the lock. Usually the real culprit. - •
blocking_query: What the locking query is.
Most of the time when you look at the table you see 20 rows but blocking_session is always the same. So 20 queries wait for one query. If you solve that one query, 20 queries are saved at once.
▸Find the Root Blocker — Head of the Chain
Sometimes the chain is long. A waits for B, B waits for C, C waits for D. The root blocker is D. Without finding D, the chain does not resolve.
-- Find the root blocker: session with blocking_session_id = 0 but waited by others
WITH BlockingChain AS (
SELECT
session_id,
blocking_session_id,
wait_type,
wait_time,
0 AS level
FROM sys.dm_exec_requests
WHERE blocking_session_id <> 0
UNION ALL
SELECT
r.session_id,
r.blocking_session_id,
r.wait_type,
r.wait_time,
bc.level + 1
FROM sys.dm_exec_requests r
JOIN BlockingChain bc ON bc.blocking_session_id = r.session_id
)
SELECT DISTINCT session_id, blocking_session_id, wait_type, level
FROM BlockingChain
ORDER BY level DESC;More practical way is to use a tool like sp_WhoIsActive. But if there is no tool, the query above shows the head of the chain.
▸Look at Lock Details
Which table, which lock mode is held?
SELECT
request_session_id AS session_id,
resource_type AS resource_type,
resource_database_id AS database_id,
OBJECT_NAME(resource_associated_entity_id) AS table_name,
request_mode AS lock_mode,
request_status AS status,
request_owner_type AS owner_type
FROM sys.dm_tran_locks
WHERE request_session_id > 50
ORDER BY request_session_id;Look at request_mode values:
- •
S: Shared lock. - •
X: Exclusive lock. - •
U: Update lock. - •
IX: Intent exclusive lock. - •
Sch-M: Schema modification lock. - •
Sch-S: Schema stability lock.
If you see Sch-M, DDL is running. If there are many X locks and the table is the same, there is unindexed UPDATE suspicion.
Step 3: Which Table and Which Lock Type?
Check which table, which mode the lock is held in.
SELECT
OBJECT_NAME(l.resource_associated_entity_id) AS table_name,
l.request_mode AS lock_mode,
COUNT(*) AS cnt
FROM sys.dm_tran_locks l
WHERE l.request_session_id > 50
GROUP BY OBJECT_NAME(l.resource_associated_entity_id), l.request_mode
ORDER BY cnt DESC;▸Understand Lock Modes
| Mode | Meaning | Danger |
|---|---|---|
| Key / Row | Row lock | Low, normal write |
| Page | Page lock | Medium, multiple rows |
| Table | Table lock | High, blocks everything |
| Schema | Structure lock | Highest, DDL + DML conflict |
| Intent | Intent lock | Low, announcement purpose |
If you see a table lock, someone locks the table. Probably ALTER TABLE, TRUNCATE, or TABLOCK hint was used.
Step 4: Decide — 3 Options
In a lock crisis you have 3 options. Which one you choose depends on what the blocking query is.
▸Option A: Wait — Safest Option
If the blocking query has been running for less than 10 seconds and is a normal operation, wait. Because the query will finish, the lock will release, the queue will empty. Intervention can make it worse.
Waiting rule: If the blocking query has been running for less than 2 minutes and shows progress, wait. Do not kill in panic.
▸Option B: Warn the Blocking Query Owner — Communicate with the App Team
If the blocking query has been running for more than 10 minutes and belongs to an application session, first notify the application team. Because if you kill that query, there may be a half-finished operation on the application side.
The sentence you say must be clear:
Warning without numbers does not work. Say Session ID, duration, and waiting count.
▸Option C: Kill — Last Resort
If the blocking query has been running for more than 30 minutes, its owner is unreachable, and the system is at a standstill, you must kill it.
-- First verify the session
SELECT session_id, login_name, host_name, program_name, status, cpu_time, reads, writes
FROM sys.dm_exec_sessions
WHERE session_id = 123;
-- Then kill it
KILL 123;▸3 Rules When Killing
- 1Never kill in bulk. Kill 1 blocking query, not 20 waiting queries. If you kill waiters, the blocker still stands and new waiters come.
- 2First verify the session ID. If you kill the wrong session, you kill an innocent report or backup.
- 3Monitor after kill. After killing, verify locks released. If not, there is a second blocker in the chain. Also the killed transaction is rolled back. Rollback can take as long as the transaction itself. Monitor
ROLLBACKprogress afterKILL.
-- Monitor rollback progress
SELECT session_id, percent_complete, estimated_completion_time / 1000.0 AS remaining_sec
FROM sys.dm_exec_requests
WHERE command = 'KILLED/ROLLBACK';Step 5: Deadlock — Two Transactions Wait for Each Other
Deadlock is a special case of locking. Two transactions wait for each other, neither progresses. SQL Server automatically detects deadlock and chooses one as victim.
-- Deadlock error example:
-- Error 1205: Transaction was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.To diagnose deadlock, look at the last deadlock info. There are 3 ways:
▸Way 1: Deadlock Graph with Extended Events
-- Capture deadlock graph with Extended Events
SELECT
xed.event_data
FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL) AS xed
WHERE xed.event_data.value('(/event/@name)[1]', 'varchar(50)') = 'xml_deadlock_report';Deadlock graph shows which two transactions waited for each other, which locks conflicted, and which one was chosen as victim. You can open the graph visually in SSMS.
▸Way 2: Write to Log with Trace Flag 1222
DBCC TRACEON(1222, -1);This setting writes every deadlock to the error log. It is recommended to be on in production.
▸Way 3: System Health Session
SQL Server's default System Health session automatically records deadlocks. In SSMS, open Extended Events, System Health session, see deadlock graphs.
The root cause of deadlock is usually access order. If two transactions access the same tables in different order, deadlock occurs.
Example:
Transaction A: First Orders, then Customers
Transaction B: First Customers, then OrdersBoth wait for each other. Solution is to use the same order in all transactions. Always first Orders, then Customers. Order standard reduces deadlock by 90%.
Step 6: Prevent Recurrence — Permanent Solutions
You survived the crisis. Now take 5 permanent measures so it does not repeat.
▸1. Keep Transactions Short
Transactions must not contain:
- •HTTP calls
- •External API waiting
- •User confirmation waiting
- •Sleep, waiting, long loops
- •File reading, email sending
A transaction should only do database work. Nothing else. Open the transaction, do the work, close it. A transaction longer than 3 seconds is suspicious. A transaction longer than 30 seconds requires an alarm.
▸2. Do Not Do Unindexed UPDATE
An unindexed UPDATE locks the whole table. Because SQL Server scans the table to find which row to update and locks every row it scans.
-- Bad: If CustomerID is unindexed, the whole table is locked
UPDATE Orders SET Status = 'Shipped' WHERE CustomerID = 123;
-- Good: First check the plan
SET SHOWPLAN_ALL ON;
UPDATE Orders SET Status = 'Shipped' WHERE CustomerID = 123;If plan output shows Clustered Index Scan, that UPDATE will lock the table. First add the index, then do the UPDATE.
▸3. Review Isolation Level
SQL Server's default isolation level is READ COMMITTED. But in some systems READ COMMITTED SNAPSHOT is more suitable. Because READ COMMITTED SNAPSHOT prevents read operations from waiting for write locks. Reading reads the old version, does not wait for writing.
-- Check at database level
SELECT name, snapshot_isolation_state_desc, is_read_committed_snapshot_on
FROM sys.databases
WHERE name = 'ProductionDB';If is_read_committed_snapshot_on = 1, read operations do not wait for locks. This is ideal for most web applications. But it increases tempdb load. Check tempdb capacity before changing.
▸4. Set a Lock Timeout
Prevent a query from waiting forever. The LOCK_TIMEOUT setting terminates a query if it waits longer than the set time for a lock.
-- At session level
SET LOCK_TIMEOUT 10000; -- 10 secondsThis setting prevents waiting queries from staying in queue forever. A query waiting 10 seconds gets an error and returns. The application can retry. But the system does not lock up.
▸5. Set an Access Order Standard
Rule for the whole team: Tables will always be accessed in the same order in transactions.
Example standard:
- 1First
Customers - 2Then
Orders - 3Then
OrderItems - 4Then
Payments
This order will be the same in all code. Code accessing in a different order will be rejected in code review.
Verification: Did the Lock Release?
After intervention, run the same queries again:
SELECT
wait_type,
COUNT(*) AS cnt
FROM sys.dm_exec_requests
WHERE session_id > 50
GROUP BY wait_type
ORDER BY cnt DESC;Success criteria:
- •Did
LCK_M_count return to 0 or normal? - •Did long transaction count drop?
- •Did waiting queries start working?
- •Did application error rate return to normal?
If you cannot say yes to these questions, there is a second blocker in the chain. Go back to Step 2, find the new blocker.
7 Common Mistakes
First mistake: Killing waiting queries. Waiters are innocent. Kill the blocker. If you kill waiters, the problem continues.
Second mistake: Judging a lock by its type. Not lock type, but duration is the problem. A 1-second table lock is normal. A 2-hour row lock is a disaster.
Third mistake: Making HTTP calls inside a transaction. A transaction is opened for database work. The outside world is not waited for.
Fourth mistake: Not setting LOCK_TIMEOUT. Without this setting, one bad query can lock the whole system.
Fifth mistake: Thinking deadlock is a database error. Deadlock is an application design error. Without fixing access order, deadlock does not end.
Sixth mistake: Doing unindexed UPDATE. An unindexed UPDATE locks the whole table. First check with the plan.
Seventh mistake: Thinking a lock problem is a memory or CPU problem. If the system stops while CPU is 15%, the first place to look is the lock screen. Look at waiting, not CPU.
Checklist
LCK_M_count checked- Long transaction count and longest duration checked
- Blocking and blocked sessions identified
- Root blocker found
- Lock mode and table determined
- Blocking query duration and owner verified
- If shorter than 2 minutes, waited, not killed in panic
- If long, application team notified
- If needed,
KILLused, session verified first - After kill, locks released verified
- Rollback progress monitored
- If deadlock, access order checked
LOCK_TIMEOUTsetting checkedTRACEON(1222)is on checked- Long transaction alarm set up
- Access order standard shared with team
- Root cause fixed in code
Conclusion
A lock is not the fault of the database. A lock is the mirror of transaction design. With short transactions, correct access order, no unindexed UPDATE, and timeout settings, lock crises can be almost completely prevented. After reading this article, when the system stops you will look not at CPU, but at waiting. You will find not the waiter, but the blocker. And you will not only solve the crisis, but prevent it from recurring.
Performance Pillar Completed — SQL Server Leg
With this article, the SQL Server leg of the Performance Pillar is complete.
Completed Articles:
- •Pillar Hub: Performance Guide
- •[Universal] N+1, EXPLAIN ANALYZE, Connection Pool, Partitioning
- •[PostgreSQL] pg_stat_statements, Vacuum, Index Selection, Memory Tuning, Lock Diagnosis
- •[MySQL] Performance Schema, Buffer Pool + Redo Log, Purge + Undo, Lock Diagnosis
- •[SQL Server] Query Store, Memory Tuning, Lock Diagnosis
Total: Pillar + 15 Clusters
Next Phase:
- •Oracle: AWR, SGA / PGA Tuning, Lock Diagnosis
Related Articles
- •Pillar: Performance Guide — Performance & Query Optimization
- •Cluster: [SQL Server] Finding the 20 Most Expensive Queries with Query Store
- •Cluster: [SQL Server] Memory Tuning — Buffer Pool and Memory Grant
- •Cluster: [PostgreSQL] Lock Diagnosis — pg_locks + pg_stat_activity in 5 Minutes
- •Cluster: [MySQL] Lock Diagnosis — InnoDB Lock Waits
- •Next: [Oracle] Most Expensive Queries with AWR