Reconstruct a Deadlock Wait Cycle from Logs and Verify Lock Order

    Deadlock analysis often stops at the impression that a log “looks cyclic.” This article explains how to turn interleaved lock-and-wait records into a thread-lock table, rebuild a directed wait cycle, and then check the conflicting paths in code and the database before changing anything.

    Deadlock analysis too easily stops at the impression that the log “seems to contain a cycle.” Entries are printed in time order: thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1. Those two records are often separated by unrelated lines, so the reader must keep hold relationships, wait relationships, and transaction boundaries in mind at once. A wait is also not intuitive in text: the log describes events, not a graph. Context is missing as well. Logs usually record locking and waiting, not why one business path locks an order before inventory, or why another path does the reverse.

    The goal is therefore not to retell the log. It is to reconstruct three facts: who holds what, what is being waited for, and which two paths cross to form the cycle. Once the order is restored, the cause has a place to land. Without that order, advice such as “lock in one order” or “split the transaction” is only a slogan.

    Where the confusion comes from

    On-site confusion usually comes from three sources, and the analysis should be split along those sources.

    First, threads and locks are interleaved. Several sessions print at the same time, so the timeline is not a causal line. Treating “appeared first” as “held first” can turn an innocent waiter into a node on the cycle.

    Second, wait relationships are not obvious. Holds and waits are often on different lines. Lock objects appear as internal identifiers, page numbers, or index names, while business keys are buried in parameters. Without a table, you cannot answer who currently holds a given lock.

    Third, business context is missing. Opposite lock order may mean different access paths to the same resources, or inconsistent lock granularity: one side locks a row, the other a gap or a table. When the log does not show the call stack or transaction boundaries, you cannot immediately conclude that the code reversed the order.

    Intelligent coding tools are useful for the first two steps: splitting fields line by line, grouping by thread, and marking candidate cycles. They do not replace checking statement order, isolation level, and the actual execution plan in the code repository and the database. A candidate cycle is not a conclusion until it is confirmed in code, and it should not be used to change production logic directly.

    Step 1: Build a thread-lock table first

    Do not conclude yet. Split one deadlock log into a table, with one row per thread or session and lock objects in their own columns. At minimum, include the session or thread identifier, transaction identifier, locks currently held (object, mode, and granularity), the lock being waited for, wait duration, and any statement or business action that can be matched. If one thread holds several locks in sequence, keep the held locks as a list rather than compressing them into one sentence.

    Follow a few constraints while splitting the log. Extract only fields that can be checked in the log; do not add guesses such as “it is probably placing an order.” Write lock modes explicitly, such as shared, exclusive, or intention, and write granularity as row, page, gap, or table so that different granularities are not treated as the same lock. If the log has only an internal lock identifier, keep it as written and note a possible table or index beside it, marked as pending verification. Use timestamps to order events, not to draw the cycle directly.

    Constrain the process this way: split by thread, list each thread’s held locks, waited-for locks, and transaction, and do not judge the cause yet. Once the table is stable, the later cycle will not change with the narrative.

    The following structure is illustrative. Field names stay generic and are not tied to a particular log format:

    Session | Transaction | Held | Waiting for | Statement clue
    S1 | T1 | Exclusive order row | Exclusive inventory row | Decrement inventory
    S2 | T2 | Exclusive inventory row | Exclusive order row | Write back order status

    The value of this table is that it turns textual events into a resource-occupancy snapshot. A candidate edge exists only when the same lock object appears as held on one row and waited for on another. Mere adjacency in time is not an edge.

    Step 2: Rebuild the cycle by who waits for whom

    With the table, draw each wait as a directed edge from the waiter to the current holder. A waits for a lock held by B, B waits for a lock held by C, and C waits for a lock held by A: that is a closed cycle. Two edges that point at different lock objects do not form a cycle merely because both sides are waiting. Label every lock on the cycle with its business operation. For example, path one is “lock inventory after creating the order,” and path two is “write the order back after reserving inventory.” The crossing point is where those two paths lock in opposite order, not an arbitrary lock on the cycle.

    Exclude false cycles. Compatible shared read locks should not be drawn as mutually exclusive edges. Intention locks and lower-level row locks must be read through the compatibility matrix; holding a table intention lock is not the same as blocking every row lock. A session that timed out or was canceled and has already released its locks should not remain on the current cycle. When several candidate cycles exist, mark the smallest cycle first, then see whether the same pair of resources recurs.

    The output of this step should be the sessions on the cycle, the lock object and mode for each edge, the lock sequence of each path, and the pair of resources whose order is reversed. Still do not write that the root cause is confirmed.

    Step 3: Check the code and the database

    A cycle shows only that resource dependencies form a loop. It does not show which line of business code must change. Return to the corresponding transactions and find the locking statements in real call order, including explicit locks, unique-constraint inserts, foreign-key checks, and gap locks caused by range queries. On the database side, check the isolation level, whether an index makes a scan lock a wider range than expected, and whether the two statements lock the same row or adjacent gaps.

    Conflicts commonly fall into two types. One is the same set of resources in opposite order: path A locks the order before inventory, while path B locks inventory before the order. The other is inconsistent granularity: one side locks a single row by primary key, while the other lacks a suitable index and locks a wider range. It looks like “another lock,” but it actually blocks the row required by the first path.

    Match the repair direction to the conflict type, and leave a verification step rather than changing code immediately. For opposite order, agree on a global lock order—for example, always lock the order primary key before the inventory primary key—and make every entry follow the same comparison rule instead of locking in the order parameters arrive. For an overly wide range, first complete the query predicates and indexes so locks fall on the necessary rows, then consider shortening the transaction: move read-only queries that do not need to live and die with the locks out of the transaction, reducing hold time. If the business allows it, split the two mutually waiting steps into short, compensatable transactions, and use an idempotency key so retries do not amplify lock contention. Changing the isolation level is only a candidate for narrowing gap locks or next-key locks. It must be retested with the same concurrent scenario to confirm that the cycle is gone and that unacceptable phantom reads are not introduced.

    Verification should at least replay the same two production paths concurrently, record whether the new lock waits still close, and confirm that slow-statement and lock-wait metrics fall rather than moving the wait to another table. The release decision, rollout, and rollback still belong to the engineer responsible for that transaction. A model or script can keep comparing edges in the table with order in the code and mark statements that still do not match, but it cannot replace this check.

    Boundary of responsibility

    The table and the cycle solve visibility: they turn an interleaved log into occupancy relationships that can be inspected. Code, execution plans, and concurrent reproduction solve causality: why the order is reversed, and why the locks are wider than expected. A fix is valid only after these three layers agree. If locks on the cycle match no business statement, first add transaction identifiers and SQL summaries to the log. Do not invent a path by guessing.

    Done in this order, deadlock analysis changes from reading a block of opaque text into one table, one cycle, one ordering conflict, and one reproducible verification.