🧩 SQL Server Deadlocks – Deep Dive with Real Production Solutions

Deadlocks are scary.

Suddenly, your application throws this error:

Transaction (Process ID 52) was deadlocked on lock resources with another process 
and has been chosen as the deadlock victim.

But here’s the truth:

πŸ‘‰ Deadlocks are not bugs.
πŸ‘‰ Deadlocks are not crashes.
πŸ‘‰ Deadlocks are SQL Server protecting your data.

Let’s understand them properly.


1️⃣ What is a Deadlock?

A deadlock happens when:

  • Session A holds Lock 1 and waits for Lock 2
  • Session B holds Lock 2 and waits for Lock 1

Neither can proceed.

SQL Server automatically kills one transaction (victim) to resolve it.

In Microsoft SQL Server, this happens instantly.


2️⃣ Simple Deadlock Example

Session 1:

BEGIN TRAN;
UPDATE Orders SET Amount = 100 WHERE OrderId = 1;
WAITFOR DELAY '00:00:05';
UPDATE Customers SET Name = 'A' WHERE CustomerId = 1;
COMMIT;

Session 2:

BEGIN TRAN;
UPDATE Customers SET Name = 'B' WHERE CustomerId = 1;
WAITFOR DELAY '00:00:05';
UPDATE Orders SET Amount = 200 WHERE OrderId = 1;
COMMIT;

Boom πŸ’₯ Deadlock.


3️⃣ Why Deadlocks Happen

βœ” Different table access order
βœ” Long transactions
βœ” Missing indexes
βœ” High isolation level (SERIALIZABLE)
βœ” Large updates


4️⃣ Deadlock vs Blocking

FeatureBlockingDeadlock
Waits?YesYes
Automatically resolved?NoYes
Error thrown?NoYes

Deadlock throws error.
Blocking just waits.


5️⃣ Capturing Deadlocks

Option 1: Extended Events (Best Way)

CREATE EVENT SESSION DeadlockMonitor
ON SERVER
ADD EVENT sqlserver.xml_deadlock_report
ADD TARGET package0.event_file;

Option 2:

Check system health session (default).


6️⃣ Reading Deadlock Graph

Deadlock graph shows:

βœ” Victim process
βœ” Lock types
βœ” Resources involved
βœ” Execution details

In SSMS, open .xel file and view the graph visually.


7️⃣ How SQL Server Chooses Victim

SQL Server picks the transaction with:

  • Lower rollback cost
  • Or based on DEADLOCK_PRIORITY

Set priority:

SET DEADLOCK_PRIORITY LOW;

Options:

  • LOW
  • NORMAL
  • HIGH
  • Numeric (-10 to 10)

8️⃣ Fixing Deadlocks – Proven Solutions

βœ… 1. Access Tables in Same Order

Always update tables in consistent order across procedures.

Example:

  • First Orders
  • Then Customers

Never reverse it.


βœ… 2. Add Proper Indexes

Missing index = longer locks = more deadlocks.

Check execution plans.


βœ… 3. Keep Transactions Short

❌ Avoid:

BEGIN TRAN
-- user input
-- complex logic
-- delays
COMMIT

βœ” Move logic outside transaction.


βœ… 4. Use READ COMMITTED SNAPSHOT

ALTER DATABASE MyDatabase
SET READ_COMMITTED_SNAPSHOT ON;

Reduces read-write deadlocks significantly.


βœ… 5. Retry Logic in Application

Deadlocks can still happen.

Best practice:

  • Catch error 1205
  • Retry transaction

Example (pseudo logic):

If deadlock
Retry up to 3 times

9️⃣ Real Production Scenario

❌ Issue

Payment API randomly failing.

πŸ” Root Cause

Two stored procedures updating:

  • Payments
  • Accounts
    in opposite order.

βœ… Fix

Standardized table access order.
Deadlocks disappeared.


πŸ”Ÿ Monitoring Deadlocks

SELECT *
FROM sys.dm_tran_locks;

Also monitor:

  • Wait stats
  • Blocking sessions
  • Long-running transactions

1️⃣1️⃣ Deadlock Prevention Checklist

βœ” Keep transactions short
βœ” Access tables in consistent order
βœ” Use proper indexing
βœ” Avoid unnecessary SERIALIZABLE isolation
βœ” Enable RCSI in high concurrency systems
βœ” Implement retry logic


1️⃣2️⃣ Important Truth

Deadlocks are normal in high-concurrency systems.

Goal is not to eliminate them completely.

Goal is:
βœ” Minimize
βœ” Detect
βœ” Handle gracefully


✍️ Conclusion

If you understand deadlocks, you understand:

  • Locking
  • Isolation
  • Concurrency
  • Real production behavior

That makes you a serious backend professional πŸ’ͺ


Your blog series now covers:

βœ” Security
βœ” Query Store
βœ” Isolation Levels
βœ” Deadlocks

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top