Reconstructing Lock Order from Deadlock Logs: A Step-by-Step Method
Deadlock logs interleave threads, locks, and statements by time, which makes it easy to lose track of who holds what and who is waiting. This article explains a repeatable method for analysis: build a thread-lock table, draw the wait-for graph to find the cycle, then verify against transactions and source code. It covers why logs read as chaos, how to structure the raw records, how to annotate each edge with resources and business actions, how to map the cycle back to code, and how to validate a fix by reproducing the original cycle. Every conclusion must be confirmed by execution plans and source code rather than left as a guess.
Deadlock logs interleave threads, locks, and statements in time order, so readers easily get lost over who holds what and who is waiting. The goal of analysis is not to restate the log but to reconstruct the lock-acquisition order on each resource and find why two paths cross. The steps below are practical: build a table first, then find the cycle, then return to the transactions and code to confirm. A conclusion must be verifiable through execution plans and source code, not left as a text-level guess.
Why the Log Reads as Chaos
The confusion usually comes from three sources, not from the log being “too long.”
First, output order is not causal order. The database prints participants at the moment it detects the deadlock. A holds lock 1 and waits for lock 2; B holds lock 2 and waits for lock 1. The two blocks sit next to each other, but the reader has to connect the cycle. A timeline is good for answering “when did it happen,” not for directly answering “is the order reversed.”
Second, the wait relationship is buried in natural language or fixed templates. Holder, waiter, lock mode (shared, exclusive, intention locks, and so on), and resource identifier are spread across different lines. When the human brain tracks dozens of threads at once, it blends “waiting on a row” and “holding a table” into the same lock.
Third, the log almost never records business intent. It only states that a transaction is blocked on a resource; it does not say whether that lock belongs to placing an order, deducting inventory, or updating an index. Without the business action, you cannot judge why two paths touch the same set of resources in opposite order.
So the core question of deadlock analysis can be stated as: who holds what, what are they waiting for, and which segment of the cycle has reversed order. Once the order is reconstructed, the cause has a place to land. Without the order, any claim about “isolation level too high” or “too much concurrency” is only a guess.
Build the Thread-Lock Table First, No Conclusions Yet
The first step is purely structural; no root-cause judgment. Split each participant record into a row. Include at least: transaction or session identifier, thread or connection identifier, currently held lock (resource type, object, mode), the lock being waited for, wait duration, and the related statement or the fragment already executed within the transaction. When one thread holds multiple locks, give each lock its own column or sub-row; do not cram them into a single paragraph of description.
Follow a few constraints while splitting the table. Keep resource identifiers at a granularity fine enough to distinguish them: table, index, page, row, or key range, instead of writing everything as “some lock.” Record lock modes separately; shared and exclusive locks are not the same class of conflict as intention locks and other table-level locks. Extract only the lock-related part of each statement, and drop business-irrelevant log headers and stack noise first. If multiple deadlock cycles appear in the same log, group them by detection time or transaction number rather than merging them into one large table.
This step can be assisted by a local script or general text analysis, but the assistant only extracts fields. The prompt should be explicit: list held locks, waited locks, and the matching transaction per thread, and do not judge the cause. A human still has to check whether the extraction split lock objects incorrectly. After the table is built, run a consistency check first: can every “wait” find a matching “hold” in another row? When it cannot, the log may be truncated or the lock may already have been cleared by a third party, and you should not force the cycle closed.
An illustrative structure might look like this (field names are for readability only, not a specific product interface):
| Transaction | Held Resource | Held Mode | Waited Resource | Waited Mode | Statement Summary |
|---|---|---|---|---|---|
| T1 | Order row R1 | Exclusive | Inventory row S2 | Exclusive | Update inventory |
| T2 | Inventory row S2 | Exclusive | Order row R1 | Exclusive | Write back order |
Once the table is stable, later discussion should reference only the identifiers in the table and stop flipping back and forth through the raw log.
Reconstruct the Wait-For Cycle by “Who Waits for Whom”
The second step turns the table into a graph. Nodes are transactions (or threads); a directed edge means “waiting for a resource the other side holds.” If the resource T1 waits for is held by T2, draw T1 → T2. A closed loop is the deadlock cycle: T1 waits for T2, T2 waits for T3, T3 waits for T1 again. Two transactions waiting on each other form the most common two-node cycle; multi-node cycles are more easily drowned out by the timeline and must be found through the edges rather than by scanning with the eye.
Annotate each edge of the cycle with the resource and the business action, not just the thread number. After annotation, you can usually see two kinds of crossings.
One kind is the same set of resources locked in reversed order. Path A locks the order first, then inventory; path B locks inventory first, then the order. Each side is reasonable on its own, but together under concurrency they form a cycle. This is the classic ordering deadlock. The fix should first consider a globally agreed lock order, not just retrying one of the statements.
The other kind is a granularity mismatch that makes it “look like a different lock.” One path locks the whole table or a gap, another locks a single row; or one goes through the primary key and another through a secondary index, and both finally land on overlapping key ranges. The resource names differ in the log, but the wait-for graph still closes. Here, unifying only “the order in which table names appear” would fix the wrong place. First confirm whether the lock is on a row, a gap, or a table, and whether a different index choice widened the range.
When marking the crossing point, write clearly: which two transactions, which two (or which class of) resources, and the lock order on each side. Avoid statements like “maybe it’s an ordering problem” that cannot be traced back to code. If the graph has multiple cycles, handle the one with the fewest participating transactions and the most stable statements first; the other cycles are often an amplification of the same ordering problem.
Return to the Code, Then Give a Fix Direction
The cycle only shows what happened at runtime; it does not show which line of code acquires a lock first. The third step must return to transaction boundaries and statement order.
Check three things. First, the real order in which the two paths touch resources: explicit lock statements, foreign-key checks, unique constraints, triggers, and cascading updates can all take locks beyond the business statements. Second, whether the transaction is too long: remote calls or manual confirmation inserted in the middle extend lock-hold time and turn an order that could have been interleaved into a stable deadlock. Third, whether isolation level and indexes turn a lock from a “point” into a “range.” Read Committed and Repeatable Read behave differently with gap locks and next-key locks, and the same statement waits on different resources once its execution plan changes.
The fix direction should match the crossing type, and it should state “do not change the code directly; give a verifiable hypothesis first.”
Ordering conflict: define a global order for the related resources (for example, the table with the smaller primary key first, or inventory before order), and have both paths follow it. The agreement should be written into module boundaries, not only into one interface.
Range too large: add a predicate that lets the query use an index, to avoid locking the whole table or a large gap; if a precise update by primary key is possible, do not use a condition that scans a secondary index. After narrowing the range, check whether the cycle still exists.
Transaction too fat: split out steps that do not need to commit atomically with the preceding writes, to shorten the lock-hold window. Splitting changes consistency, so you must verify whether the business allows an intermediate state to be visible to other transactions.
Retry only: retrying absorbs occasional deadlocks but masks a stable reversed order. If the same pair of statements recurs repeatedly under load testing, change the order or granularity first; keep retry as a fallback with a bounded count to avoid an avalanche.
Adjusting the isolation level should be considered last. Lowering the isolation level may reduce some gap locks, but it may also introduce phantom reads or lost updates, and it should not be treated as the default solution.
Validation and Regression
After the fix, recreate the original cycle with concurrency close to production: two paths, the same resources, and a time window with enough overlap. Success is not “the log temporarily shows no deadlock text,” but that the reversed edge in the wait-for graph disappears, or the lock range shrinks until it no longer overlaps. At the same time, watch error rate, transaction duration, and lock-wait metrics, to avoid trading a deadlock for long-running blocking.
If the code cannot be changed in the short term, at least keep the thread-lock table and the cycle annotations in the incident record: participating transactions, resources, statement summaries, the identified ordering-conflict point, and the reason for deferral. Next time a similar log appears, you can apply the same table directly instead of re-finding the cycle in interleaved text.
Common Misjudgments
Treating detection order as lock order; ignoring lock widening caused by indexes and gaps; inventing a third lock when the log is incomplete; substituting “improve concurrency capacity” for a concrete ordering agreement. All of these make a fix impossible to reproduce and impossible to falsify.
The value of a deadlock log is that the participants and resource relationships are already on the page. Split them into a thread-lock table first, then draw the wait-for cycle and annotate it with business actions, and finally use code and execution plans to confirm the reversed order or the granularity difference. Unifying lock order, narrowing lock range, and splitting transactions are only directions; before rollout, each must be validated against a concurrency scenario to confirm the cycle disappears.
