0% found this document useful (0 votes)
47 views

SQL Server Blocking and Deadlocks

SQL Server Blocking and Deadlocks

Uploaded by

Rofiq Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

SQL Server Blocking and Deadlocks

SQL Server Blocking and Deadlocks

Uploaded by

Rofiq Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

https://www.sqldbachamps.

com
Praveen Madupu - +91 98661 30093
Sr SQL Server DBA, Dubai
[email protected]

SQL Server Blocking and Deadlocks: Resolutions in Detail

Blocking:

Blocking occurs in SQL Server when one session holds a lock on a resource (such as a row, page, or table) and
another session requests a conflicting lock type on the same resource, forcing the second session to wait until the
first session releases the lock. Blocking is common and often not harmful if it resolves quickly, but prolonged
blocking can lead to performance issues.

Deadlocks:

A deadlock occurs when two or more sessions hold locks on resources and each session is waiting for the other
to release the lock, resulting in a circular dependency. SQL Server automatically detects deadlocks and resolves
them by killing one of the sessions, known as the deadlock victim.

Key Differences Between Blocking and Deadlocks

- Blocking: One session is waiting for another session to release a lock. Blocking can resolve itself when the
blocking session completes its transaction.

- Deadlock: Two sessions are waiting for each other to release locks. Deadlocks never resolve themselves, and

https://www.sqldbachamps.com
SQL Server must intervene to break the cycle by terminating one session.

SQL Server Blocking: Diagnosis and Resolution

How Blocking Works

SQL Server uses a lock manager to manage access to database resources. There are various types of locks:

- Shared Locks (S): Allow multiple sessions to read the same data but prevent other sessions from modifying it.

- Exclusive Locks (X): Prevent other sessions from reading or modifying the data.

When session A acquires an exclusive lock on a row, table, or page, and session B requests a conflicting lock
(such as another exclusive lock or a shared lock), session B is blocked until session A releases the lock.

How to Identify Blocking

1. sys.dm_exec_requests: View sessions currently waiting on a resource.

2. sys.dm_tran_locks: View active locks held by transactions.

3. sys.dm_exec_sessions: View session information like blocking session ID.


https://www.sqldbachamps.com
Praveen Madupu - +91 98661 30093
Sr SQL Server DBA, Dubai
[email protected]
Sample Query to Identify Blocking:

SELECT

blocking_session_id,

session_id,

wait_type,

wait_time,

wait_resource,

transaction_isolation_level,

text AS query_text

FROM

sys.dm_exec_requests

CROSS APPLY

https://www.sqldbachamps.com
sys.dm_exec_sql_text(sql_handle)

WHERE

blocking_session_id <> 0;

- blocking_session_id: The session ID of the blocking session.

- session_id: The ID of the session that is being blocked.

Resolving Blocking

1. Identifying and Ending the Blocking Session:

- Use the KILL command to terminate the blocking session. Example:

KILL <blocking_session_id>;

However, terminating a session can lead to rollback of uncommitted transactions, so it should be used with
caution.
https://www.sqldbachamps.com
Praveen Madupu - +91 98661 30093
Sr SQL Server DBA, Dubai
[email protected]
2. Improve Transaction Design:

- Keep Transactions Short: Long-running transactions increase the likelihood of blocking. Ensure that
transactions are kept as short as possible.

- Batch Large Operations: Break large operations into smaller batches to avoid holding locks for an extended
period.

- Use Appropriate Isolation Levels: Lower isolation levels (like READ COMMITTED or READ COMMITTED
SNAPSHOT) reduce locking conflicts but may allow some level of dirty reads or non-repeatable reads.

3. Optimize Indexes:

- Lack of indexes can cause SQL Server to lock more resources than necessary (e.g., entire tables or pages).
Ensure queries are optimized and properly indexed to minimize locking.

4. Consider Lock Escalation:

- SQL Server may escalate row or page locks to table locks under heavy load. Review sys.dm_tran_locks to
detect lock escalation, and try to prevent it by optimizing queries to reduce the number of locks acquired.

Preventing Blocking

https://www.sqldbachamps.com
- Use Snapshot Isolation Level:

- The READ COMMITTED SNAPSHOT ISOLATION (RCSI) level allows readers to access a version of the
data, avoiding blocking issues with writers. Enable it using:

ALTER DATABASE <database_name> SET READ_COMMITTED_SNAPSHOT ON;

- NoLock Hint:

- For reporting queries that don't require strict accuracy, use the WITH (NOLOCK) hint to avoid blocking, though
this may allow reading uncommitted (dirty) data.

SELECT FROM <table_name> WITH (NOLOCK);


https://www.sqldbachamps.com
Praveen Madupu - +91 98661 30093
Sr SQL Server DBA, Dubai
[email protected]
SQL Server Deadlocks: Diagnosis and Resolution

How Deadlocks Work

In a deadlock, two or more sessions are waiting for each other to release locks, creating a circular dependency.

SQL Server has a deadlock detection mechanism that periodically checks for deadlocks and selects a session
(the deadlock victim) to terminate.

The victim session's transaction is rolled back, allowing the other session(s) to proceed.

How to Identify Deadlocks

1. Deadlock Graph: SQL Server can log a deadlock graph, which provides a detailed view of the resources
involved in a deadlock.

- Use Extended Events or SQL Server Profiler to capture deadlock graphs.

2. Trace Flags:

- Trace Flag 1204: Provides detailed deadlock information in the SQL Server error log.

https://www.sqldbachamps.com
- Trace Flag 1222: Provides an enhanced deadlock graph in the error log.

To enable these trace flags:

DBCC TRACEON(1204, 1222, -1);

3. Extended Events for Deadlocks:

- Extended Events is the recommended tool for deadlock detection in modern SQL Server versions.

Example of creating a session to capture deadlocks:

CREATE EVENT SESSION DeadlockMonitor

ON SERVER

ADD EVENT sqlserver.deadlock_graph

ADD TARGET package0.event_file(SET filename=N'Deadlocks.xel')

WITH (STARTUP_STATE=ON);

GO

This session captures deadlock graphs and saves them to a .xel file for later analysis.
https://www.sqldbachamps.com
Praveen Madupu - +91 98661 30093
Sr SQL Server DBA, Dubai
[email protected]
Resolving Deadlocks

1. Terminate the Deadlock Victim:

- SQL Server automatically terminates the session identified as the deadlock victim. You don't need to intervene
in this process.

- The victim’s transaction is rolled back, and the other transaction can proceed.

2. Analyze and Resolve Deadlock Patterns:

- Use the deadlock graph to identify the deadlock resources and queries involved.

- Look for patterns, such as two sessions trying to update resources in different orders, and rewrite queries to
avoid these conflicts.

Strategies to Prevent Deadlocks

1. Consistent Locking Order:

- Ensure that all queries accessing the same set of resources do so in a consistent order. For example, if
session A locks table 1 and then table 2, all other sessions should lock tables in the same order.

https://www.sqldbachamps.com
2. Minimize Lock Time:

- Similar to blocking, keeping transactions short and efficient reduces the chances of deadlocks. Avoid
long-running transactions that hold locks on multiple resources simultaneously.

3. Use Lower Isolation Levels:

- If appropriate, use a lower isolation level (such as READ COMMITTED or READ COMMITTED SNAPSHOT)
to reduce lock contention.

4. Lock Hints:

- In some cases, using lock hints like WITH (ROWLOCK) or WITH (UPDLOCK) can reduce deadlocks by
acquiring more granular or specific locks. However, these hints should be used judiciously and tested thoroughly.

5. Increase Deadlock Priority:

- SQL Server allows you to set the deadlock priority for sessions. A session with a higher deadlock priority is
less likely to be chosen as the deadlock victim.

SET DEADLOCK_PRIORITY LOW | NORMAL | HIGH;


https://www.sqldbachamps.com
Praveen Madupu - +91 98661 30093
Sr SQL Server DBA, Dubai
[email protected]
Alternatively, you can assign a numeric value (-10 to 10), where higher numbers have higher priority.

Example: Resolving a Deadlock by Adjusting Transaction Code

In the following example, two sessions attempt to update resources in a different order, leading to a deadlock:

-- Session 1

BEGIN TRAN;

UPDATE Orders SET Quantity = 10 WHERE OrderID = 1;

UPDATE Customers SET Name = 'John' WHERE CustomerID = 1;

COMMIT;

-- Session 2

BEGIN TRAN;

UPDATE Customers SET Name = 'Jane' WHERE CustomerID = 1;

UPDATE Orders SET Quantity = 20 WHERE OrderID = 1;

https://www.sqldbachamps.com
COMMIT;

Here, both sessions lock the Orders and Customers tables in a different order, causing a deadlock. To resolve
this, ensure both sessions update the resources in the same order:

-- Session 1 and 2 (same order of operations)

BEGIN TRAN;

UPDATE Customers SET Name = 'John' WHERE CustomerID = 1;

UPDATE Orders SET Quantity = 10 WHERE OrderID = 1;

COMMIT;

By enforcing a consistent order, you prevent the deadlock.


https://www.sqldbachamps.com
Praveen Madupu - +91 98661 30093
Sr SQL Server DBA, Dubai
[email protected]
Conclusion

- Blocking is a common issue in SQL Server that can be minimized by optimizing queries, improving transaction
design, and using appropriate isolation levels.

- Deadlocks are more severe and occur when two sessions are waiting for each other to release resources. SQL
Server automatically resolves deadlocks by choosing a victim, but preventing deadlocks requires careful
transaction design, consistent resource access, and sometimes lock hints.

Proper diagnosis using system views, trace flags, or Extended Events allows you to understand the root causes
of blocking and deadlocks, and apply best practices to prevent them from recurring.

https://www.sqldbachamps.com

You might also like