الانتقال إلى المحتوى
قواعد البياناتالـ Transactions والـ Concurrency· 8 دقائق للقراءة

Deadlocks Are a Design Problem: Why They Happen and How to Make Them Rare

Two sessions are enough for a deadlock. Lock order, transaction length and indexes decide how often you get one, and a retry handles the rest.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

The order service logs Msg 1205 a few times a week, always at busy hours, and the ticket says "SQL Server deadlock bug under load". Checkout reserves stock and then updates the shipment; the cancellation job updates the shipment and then releases the stock. In a test on SQL Server 2022, two sessions ran those two transactions 300 ms apart, each pausing one second between its two updates. Run three times, it deadlocked three times, with no other load on the server, and the victim was the checkout twice and the cancellation once. With both transactions in the same order, it never deadlocked: the second one simply waited about 0.7 seconds.

The common misconception

The belief: deadlocks are a database malfunction that only happens under extreme load, and application design can't prevent them.

Deadlocks show up at random, mostly in production and mostly when traffic peaks. The error comes from the database and reads as if the engine decided to kill your request. The locks themselves are invisible in ORM code, so nothing in a code review hints at a problem. There's a grain of truth: more traffic means more overlapping transactions, and Microsoft's deadlocks guide says deadlocks can't be completely avoided. But the cycle itself is built by your access pattern, and load only decides how often two requests walk into it.

What actually happens

A deadlock is a cycle, not a slowdown

Blocking ends on its own: the transaction holding the lock finishes and the waiter continues. A can't end that way, because each transaction waits for the other. SQL Server's lock monitor searches for such cycles every 5 seconds by default, and the interval drops to as low as 100 milliseconds while it keeps finding them. It picks the by DEADLOCK_PRIORITY, then by which transaction is cheaper to roll back, rolls it back and returns error 1205. In the tests, the cycle was broken about 3.5 and 3.3 seconds after it formed in the first two runs, and about 0.8 seconds in the third, which came right after them. PostgreSQL waits deadlock_timeout, one second by default, before checking, and its docs warn that which transaction gets aborted is difficult to predict. The same test on PostgreSQL 18 failed with ERROR: deadlock detected, and the DETAIL line showed the two processes waiting on each other.

Cause 1: the same locks in different orders

The hook is the classic shape. Checkout locks the stock row, then wants the shipment row; cancellation locks the shipment row, then wants the stock row. PostgreSQL's docs name the fix plainly: the best defense is to make sure all applications acquire locks on multiple objects in a consistent order. Pick one order per pair of tables, such as stock before shipments, and update rows within a table in ascending key order. Then the second transaction waits instead of forming a cycle, which is what the same-order runs showed.

Cause 2: transactions that stay open

Every lock is held until commit, so a longer transaction is a wider target. Microsoft's guide says deadlocks typically occur when several long-running transactions run concurrently, because update and exclusive locks are held longer. In the test, the one-second pause between two updates is what made the overlap certain. In real code, that pause is an HTTP call, a message publish or a user's decision made inside the transaction.

Cause 3: scans lock rows you didn't mean to touch

An UPDATE filtering on a column without an index has to read every row to find its targets, and it locks rows as it checks them. Microsoft's locking guide advises accessing the least amount of data possible in a transaction, which lessens the number of locked rows. In the test, a 1,000-row table had no index on OrderNumber. Session A updated order 900 and, a second later, order 1; session B updated order 100. Three different rows, yet both runs deadlocked: B's scan stopped at A's row 900, and A's second scan stopped at B's row 100. After adding an index on OrderNumber, B committed in 4 ms without waiting at all.

Higher isolation adds deadlocks

REPEATABLE READ and SERIALIZABLE hold shared locks to the end, so two transactions that read a row and then update it can deadlock, as the lost updates article showed. Microsoft's deadlocks guide recommends avoiding those levels when they aren't required, and using row versioning, such as READ_COMMITTED_SNAPSHOT, to minimize deadlocks between reads and writes.

Fix the order, then retry the rare victim

C#
using Microsoft.EntityFrameworkCore;// Checkout updates Inventory, then Shipments. This job does the reverse.static async Task CancelAsync(ShopDb db, int orderId, int productId){    await using var tx = await db.Database.BeginTransactionAsync();    await db.Shipments.Where(s => s.OrderId == orderId).ExecuteUpdateAsync(        s => s.SetProperty(x => x.Status, "Cancelled"));    await db.Inventory.Where(i => i.ProductId == productId).ExecuteUpdateAsync(        s => s.SetProperty(i => i.Reserved, i => i.Reserved - 1));    await tx.CommitAsync(); // Test: one of the two failed with 1205}

The retry matters even after the order is fixed, since other code paths can still collide. Microsoft's guide tells applications to handle error 1205 and resubmit after a short, randomized pause. EF Core's SQL Server with EnableRetryOnFailure treats 1205 as transient, and its docs require a transaction you start yourself to run inside ExecuteAsync, so the whole block is replayed. In a test with EF Core 10 and two opposite-order transactions, the victim was retried and committed on its second attempt; without EnableRetryOnFailure, it failed with InvalidOperationException wrapping the 1205.

MythReality
Deadlocks mean the server is overloaded or buggyTwo sessions and no other load deadlocked in 3 runs out of 3
The database should just wait longerA cycle never ends by waiting; one transaction has to fail
Application design can't prevent themSame lock order: no deadlock in 3 runs. An index: no wait at all
Retrying is a hackMicrosoft's guide tells applications to handle 1205 and resubmit

Before changing code, read the deadlock graph. SQL Server's default system_health session already records every deadlock as an xml_deadlock_report event, with the statements and the locks involved:

SQL recent-deadlocks.sql
SELECT x.e.value('@timestamp', 'datetime2') AS [When],       x.e.query('.') AS ReportFROM (SELECT CAST(t.target_data AS xml) AS data      FROM sys.dm_xe_session_targets AS t      JOIN sys.dm_xe_sessions AS s ON s.address = t.event_session_address      WHERE s.name = N'system_health'        AND t.target_name = N'ring_buffer') AS rbCROSS APPLY rb.data.nodes('//event[@name="xml_deadlock_report"]') AS x(e);

How to apply it in your project

  1. Collect the graphsRun the query above, or check the PostgreSQL server log, and group deadlocks by the pair of statements involved.
  2. Write down a lock orderFor each pair of tables updated together, choose one order and use it everywhere; within a table, update rows by ascending key. Shared data-access code or stored procedures make the order hard to break.
  3. Shorten the transactionsDo reads, calculations and external calls before BEGIN, and keep only the writes inside.
  4. Index what writes filter onCheck the plans of UPDATE and DELETE statements for scans, and index the columns in their WHERE clauses.
  5. Retry the victimUse EnableRetryOnFailure with CreateExecutionStrategy, or catch error 1205 in SQL Server or SQLSTATE 40P01 in PostgreSQL and rerun the transaction after a short random pause.

Key takeaways

  • A deadlock is a cycle between transactions, which the engine breaks by failing one: error 1205 in SQL Server, deadlock detected in PostgreSQL.
  • Two sessions were enough: opposite update orders deadlocked in every test run, and the same order never did.
  • Long transactions and scans caused by missing indexes widen the window; an index removed a deadlock between three different rows.
  • Avoid REPEATABLE READ and SERIALIZABLE when not needed, and use row versioning for reads.
  • Deadlocks can't be eliminated, so retry the whole transaction with a short random pause and watch how often it happens.

📚 المصادر

  1. Deadlocks guide — SQL Server, Microsoft Learn
  2. Transaction locking and row versioning guide — SQL Server, Microsoft Learn
  3. Connection resiliency — EF Core, Microsoft Learn
  4. Explicit Locking: Deadlocks — PostgreSQL 18 documentation
  5. Lock Management: deadlock_timeout — PostgreSQL 18 documentation

التعليقات (0)