
Deadlocks Are a Design Problem: Why They Happen and How to Make Them Rare
- كاتب موثّق
محتويات المقال
The common misconception
What actually happens
A deadlock is a cycle, not a slowdown
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
Cause 2: transactions that stay open
Cause 3: scans lock rows you didn't mean to touch
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
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}using Microsoft.EntityFrameworkCore;// Context registered with UseSqlServer(cs, o => o.EnableRetryOnFailure())static async Task CancelAsync(ShopDb db, int orderId, int productId){ var strategy = db.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async () => { // Same order as checkout: Inventory first, then Shipments await using var tx = await db.Database.BeginTransactionAsync(); await db.Inventory.Where(i => i.ProductId == productId) .ExecuteUpdateAsync(s => s.SetProperty(i => i.Reserved, i => i.Reserved - 1)); await db.Shipments.Where(s => s.OrderId == orderId) .ExecuteUpdateAsync(s => s.SetProperty(x => x.Status, "Cancelled")); await tx.CommitAsync(); // A rare 1205 reruns this whole block });}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.
system_health session already records every deadlock as an xml_deadlock_report event, with the statements and the locks involved:
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
Collect the graphs Run the query above, or check the PostgreSQL server log, and group deadlocks by the pair of statements involved. Write down a lock order For 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. Shorten the transactions Do reads, calculations and external calls before BEGIN, and keep only the writes inside.Index what writes filter on Check the plans of UPDATEandDELETEstatements for scans, and index the columns in theirWHEREclauses.Retry the victim Use EnableRetryOnFailurewithCreateExecutionStrategy, or catch error 1205 in SQL Server or SQLSTATE40P01in 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 detectedin 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 READandSERIALIZABLEwhen 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.
التعليقات (0)