Md Mominul Islam | Software and Data Enginnering | SQL Server, .NET, Power BI, Azure Blog

while(!(succeed=try()));

LinkedIn Portfolio Banner

Latest

Home Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Wednesday, September 10, 2025

SQL Server Blocking vs Deadlocking: Key Differences & Solutions

 

SQL Server Blocking vs Deadlocking: Key Differences & Solutions

Understanding Blocking vs Deadlocking

Blocking

Blocking occurs when one transaction holds a lock on a resource (e.g., row, page, or table), and another transaction waits for it to be released. This is temporary but can cause significant delays. For example, in a retail system, a long-running update to an Orders table might block a reporting query, delaying dashboards during peak sales.

  • Symptoms: Slow queries, high wait times (e.g., LCK_M_S or LCK_M_X in sys.dm_os_wait_stats), and application timeouts.

  • SQL Server 2025 Feature: Optimized locking reduces escalation, minimizing block duration.

Deadlocking

Deadlocking is a circular wait where two or more transactions each hold locks that the others need, creating a stalemate. SQL Server detects this and kills one transaction (error 1205: "Transaction was deadlocked..."). For instance, in a banking app, one transaction updating account A and waiting for B, while another updates B and waits for A, causes a deadlock, potentially failing a trade.

  • Symptoms: Error 1205, rolled-back transactions, and user errors.

  • SQL Server 2025 Feature: Enhanced lock partitioning and IQP improve concurrency, reducing deadlocks.

Key Differences

  • Nature: Blocking is a wait; deadlocking is a fatal loop.

  • Resolution: Blocking resolves when the lock is released; deadlocking requires SQL Server intervention.

  • Impact: Blocking slows operations; deadlocking aborts them, risking data integrity.

Step-by-Step Detection and Resolution

Step 1: Detect Blocking

Identify sessions causing and affected by blocks.

  • Query DMVs for Blocking:

    SELECT 
        r.session_id AS BlockedSession,
        r.blocking_session_id AS BlockingSession,
        r.wait_type,
        r.wait_time / 1000 AS WaitTimeSec,
        t.text AS BlockedQuery,
        bt.text AS BlockingQuery
    FROM sys.dm_exec_requests r
    CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
    LEFT JOIN sys.dm_exec_requests br ON r.blocking_session_id = br.session_id
    OUTER APPLY sys.dm_exec_sql_text(br.sql_handle) bt
    WHERE r.blocking_session_id <> 0 AND r.wait_type LIKE 'LCK%';
  • Monitor Wait Stats:

    SELECT 
        wait_type,
        wait_time_ms,
        waiting_tasks_count
    FROM sys.dm_os_wait_stats 
    WHERE wait_type LIKE 'LCK%' 
    ORDER BY wait_time_ms DESC;
  • Real-Life Example: In a healthcare system, a batch update to patient records blocked a doctor’s query, delaying treatment decisions. The DMV query pinpointed the update as the blocker.

Pros: DMVs provide real-time insights; no server restart needed. Cons: Requires frequent polling; complex in high-transaction systems. Real-Life and Business Usage: Retail firms use this during sales to ensure checkout queries aren’t delayed, maintaining customer satisfaction and revenue.

Step 2: Detect Deadlocking

Capture deadlock events for analysis.

  • Enable Trace Flag 1222:

    DBCC TRACEON(1222, -1);  -- Logs deadlock graphs to error log
  • Set Up Extended Events:

    CREATE EVENT SESSION DeadlockMonitor ON SERVER
    ADD EVENT sqlserver.xml_deadlock_report
    ADD TARGET package0.event_file (SET filename = 'D:\Logs\DeadlockMonitor.xel')
    WITH (MAX_MEMORY = 4096 KB);
    ALTER EVENT SESSION DeadlockMonitor ON SERVER STATE = START;
  • Analyze Deadlock Graph:

    SELECT 
        XEventData.value('(event/data/value)[1]', 'xml') AS DeadlockGraph
    FROM (
        SELECT CAST(event_data AS xml) AS XEventData
        FROM sys.fn_xe_file_target_read_file('D:\Logs\DeadlockMonitor*.xel', NULL, NULL, NULL)
    ) AS DeadlockEvents;
  • Real-Life Example: In a banking app, a deadlock occurred between two transactions updating accounts (e.g., UPDATE Accounts SET Balance -= 100 WHERE AccountID = 1 and vice versa). The graph showed conflicting KEY locks.

Pros: Detailed XML output; 2025 enhances graph readability. Cons: XML parsing complex; storage needed for event files. Real-Life and Business Usage: Financial systems use deadlock graphs to resolve trade failures, ensuring compliance with millisecond SLAs and avoiding losses.

Step 3: Resolve Blocking

Reduce blocking with optimized queries and configurations.

  • Shorten Transactions:

    BEGIN TRANSACTION;
    UPDATE Orders SET Status = 'Processed' WHERE OrderID = @OrderID;
    COMMIT TRANSACTION;  -- Commit quickly
  • Enable Read Committed Snapshot:

    ALTER DATABASE YourDatabase SET READ_COMMITTED_SNAPSHOT ON;

    This uses row versioning to reduce read-write conflicts.

  • Use 2025 Optimized Locking:

    EXEC sp_configure 'optimized locking', 1;
    RECONFIGURE;
  • Add Indexes: For a blocking query like SELECT * FROM Orders WHERE CustomerID = 123:

    CREATE NONCLUSTERED INDEX IX_Orders_CustomerID ON Orders(CustomerID) INCLUDE (OrderID, Status);

Pros: Cuts wait times by 30-50%; 2025 features reduce manual tuning. Cons: Snapshot isolation increases tempdb usage; indexing adds overhead. Real-Life and Business Usage: A logistics firm reduced blocking on shipment updates, enabling real-time tracking and cutting delivery errors by 20%.

Step 4: Resolve Deadlocking

Prevent circular waits with design changes.

  • Consistent Table Access Order: Ensure transactions access tables in the same order:

    -- Transaction 1 and 2 both do:
    UPDATE Accounts SET Balance -= 100 WHERE AccountID = 1;
    UPDATE Accounts SET Balance += 100 WHERE AccountID = 2;
  • Use Snapshot Isolation for Reports:

    SET TRANSACTION ISOLATION LEVEL SNAPSHOT;
    SELECT * FROM Accounts;
  • Retry Logic in Application:

    DECLARE @Retry INT = 5;
    WHILE @Retry > 0
    BEGIN
        BEGIN TRY
            BEGIN TRANSACTION;
            -- Your transaction here
            COMMIT TRANSACTION;
            BREAK;
        END TRY
        BEGIN CATCH
            IF ERROR_NUMBER() = 1205
            BEGIN
                SET @Retry -= 1;
                WAITFOR DELAY '00:00:01';
            END
            ELSE THROW;
        END CATCH
    END

Pros: Eliminates deadlocks; retry logic ensures completion. Cons: Code changes needed; snapshot isolation risks version bloat. Real-Life and Business Usage: An e-commerce platform used retry logic during flash sales, ensuring order completion and boosting conversions by 15%.

Step 5: Optimize Indexes and Statistics

Both issues benefit from efficient indexing.

  • Update Statistics:

    UPDATE STATISTICS Orders WITH FULLSCAN;
  • Rebuild Fragmented Indexes:

    ALTER INDEX ALL ON Orders REBUILD WITH (ONLINE = ON);
  • Use 2025 Auto-Tuning:

    ALTER DATABASE YourDatabase SET AUTOMATIC_TUNING (FORCE_LAST_GOOD_PLAN = ON);

Pros: Reduces lock scope, cutting conflicts by 20-40%. Cons: Maintenance increases I/O; over-indexing slows writes. Real-Life and Business Usage: A healthcare provider optimized indexes to reduce blocking on patient queries, ensuring timely care and HIPAA compliance.

Step 6: Monitor and Prevent Recurrence

Set up proactive monitoring.

  • SQL Agent Alerts:

    EXEC msdb.dbo.sp_add_alert 
        @name = N'Deadlock Alert',
        @message_id = 1205,
        @severity = 0,
        @enabled = 1;
  • Extended Events for Blocking:

    CREATE EVENT SESSION BlockingMonitor ON SERVER
    ADD EVENT sqlserver.lock_timeout_greater_than_0
    ADD TARGET package0.event_file (SET filename = 'D:\Logs\BlockingMonitor.xel');
    ALTER EVENT SESSION BlockingMonitor ON SERVER STATE = START;

Pros: Early detection prevents escalation; integrates with 2025 tools. Cons: Storage and analysis overhead. Real-Life and Business Usage: A telecom firm used alerts to catch blocking during call surges, maintaining billing accuracy and customer satisfaction.

Real-Life Scenarios and Business Impact

  • E-Commerce: Blocking during a sale delayed checkout queries. Snapshot isolation cut waits, increasing completed orders by 20% and revenue by millions.

  • Finance: Deadlocks in trade updates caused failures. Consistent access order and retry logic ensured trades executed, avoiding losses and regulatory issues.

  • Healthcare: Blocking on patient updates delayed care. Optimized indexes and 2025 locking reduced delays, ensuring compliance and patient safety.

Pros and Cons of Overall Approach

  • Pros: Comprehensive detection with DMVs and Extended Events; 2025 features reduce conflicts; scalable for high-transaction systems.

  • Cons: Setup complexity for monitoring; snapshot isolation needs tempdb monitoring; code changes delay fixes in legacy apps. Business Impact: Resolving these issues ensures uptime, reduces costs, and supports data-driven decisions, critical for competitive industries.

Best Practices for Prevention

  • Schedule regular statistics updates:

    EXEC sp_updatestats;
  • Automate index maintenance:

    ALTER INDEX ALL ON YourTable REORGANIZE;
  • Use Query Store to track regressions:

    SELECT * FROM sys.query_store_plan WHERE is_forced_plan = 1;
  • Design transactions for minimal lock duration and consistent order.

No comments:

Post a Comment

Thanks for your valuable comment...........
Md. Mominul Islam

Post Bottom Ad

Responsive Ads Here