Stop Reading Deadlock Logs Line by Line: Tabulate, Find the Cycle, Locate the Conflicting Locks

    Deadlock logs are usually complete but hard to follow because holders and waiters are scattered across threads. This article explains how to flatten InnoDB-style deadlock output into one row per lock state, turn waits into a directed graph, locate the cycle and conflicting locks, map them back to code, and keep reproduction and production evidence within safe bounds.

    1. Why reading a deadlock log line by line gets lost

    Deadlock logs are usually complete. The problem is that the structure is loose. Dozens of threads and several locks appear interleaved, and hold and wait relationships sit on different lines. Readers have to keep several states in mind at once, so it is hard to see where they close into a loop.

    A simple example: line 3 says thread A is waiting for lock 2, and only line 40 shows thread B holding lock 2. Unrelated records fill the gap. Halfway through, the earlier state is often forgotten.

    A different reading order is much clearer. Put the holder and the waiter of each lock on the same row, and “thread A waits for lock 2” and “thread B holds lock 2” sit side by side.

    The confusion mainly comes from three things:

    1. Threads and locks are mixed. The log is written in time order, so the two sides of the same conflict can be far apart.
    2. Wait relationships exist only as prose. As the thread count grows, the number of relationships grows quickly, and manual reasoning becomes error-prone.
    3. Business context is missing. The log records locking, waiting, and rollback, but not which API or job those actions belong to.

    Analyzing a deadlock therefore means answering three questions: who holds what, who is waiting for what, and where the cycle is. The three steps below match those questions.

    2. The four necessary conditions for deadlock

    Textbooks usually summarize deadlock formation as four necessary conditions. A deadlock can occur only when all four hold at the same time:

    • Mutual exclusion: a resource can be held by only one thread at a time.
    • Hold and wait: a thread already holds at least one lock while waiting for others.
    • No preemption: a lock that has been acquired cannot be taken back by force; only the holder can release it.
    • Circular wait: several threads form a loop, each waiting for a resource held by the next.

    These four conditions explain why a deadlock can happen. They are not a troubleshooting procedure. What you actually need from the log is the cycle that satisfies circular wait. In a database the first three conditions are generally already true, so the investigation focuses on circular wait.

    Deadlock detection and rollback differ by database, and so do field names. The rest of this article uses MySQL InnoDB as the main example. Differences in other databases are covered in section 4.

    3. Step 1: Split the log into a table so holders and waiters share a row

    The point of the table is to turn scattered log records into one format. Use the template below. Each row is one transaction’s state on one lock.

    Field Meaning Where to read it in the log
    Lock ID The contended resource, such as a record on an index of a table The index or lock description in the lock section
    Holding transaction Transaction ID that already has the lock The HOLDS THE LOCK(S) section
    Waiting transaction Transaction ID waiting for the lock The WAITING FOR THIS LOCK TO BE GRANTED section
    Thread Session or thread ID for the transaction mysql thread id in the transaction section
    SQL The statement the transaction is running, or ran while holding the lock The query text in the transaction section
    State Holding, waiting, or rolled back Inferred from the sections above

    Here is a redacted log fragment. Unrelated fields are omitted, and table names and primary-key values have been replaced:

    1. *** (1) TRANSACTION:
    2. TRANSACTION 100001, ACTIVE 3 sec starting index read
    3. mysql thread id 31, query: UPDATE order_item SET status = 2 WHERE id = 101
    4. *** (1) HOLDS THE LOCK(S): ... index PRIMARY of table `shop`.`order_item` trx id 100001 lock_mode X locks rec but not gap
    5. *** (1) WAITING FOR THIS LOCK TO BE GRANTED: ... index PRIMARY of table `shop`.`order_item` trx id 100001 lock_mode X waiting
    6. ...
    7. *** (2) TRANSACTION:
    8. ...
    9. *** WE ROLL BACK TRANSACTION (2)

    After the split, the three transactions look like this:

    Transaction Lock already held Lock being waited for
    T1 R1 (order_item id=101) R2 (order_item id=205)
    T2 R2 R3 (stock id=3008)
    T3 R3 R1

    The chain is visible across the three rows: T1 waits for T2, T2 waits for T3, and T3 waits for T1.

    Two rules while building the table. First, record only what the log states explicitly; do not fill gaps from memory. Second, if the log is truncated, the table will be missing rows and any cycle you find may be incomplete. Confirm that the log is complete before going further.

    4. Step 2: Find the cycle by drawing waits as a directed graph

    Turn the table into a directed graph. Nodes are transactions. Each edge is a wait, from the waiter to the holder. If T1 is waiting for a lock held by T2, draw T1 → T2.

    If a transaction is waiting for a shared lock, there may be several holders, so one node can have several outgoing edges. A cycle in the graph means a deadlock.

    Finding a cycle by hand is straightforward: start at any transaction, follow the wait direction, and record the path. If you return to a transaction already on the path, the segment from that transaction back to itself is the cycle.

    To find a cycle in code, use depth-first search. A Python example:

    1. def find_cycle(edges):
    2. graph = {}
    3. for waiter, holder in edges:
    4. graph.setdefault(waiter, []).append(holder)
    5. visited = set()
    6. stack = []
    7. def dfs(node):
    8. if node in stack:
    9. return stack[stack.index(node):] + [node]
    10. if node in visited:
    11. return None
    12. visited.add(node)
    13. stack.append(node)
    14. for nxt in graph.get(node, []):
    15. cycle = dfs(nxt)
    16. if cycle:
    17. return cycle
    18. stack.pop()
    19. return None
    20. for start in list(graph):
    21. cycle = dfs(start)
    22. if cycle:
    23. return cycle
    24. return None
    25. edges = [("T1", "T2"), ("T2", "T3"), ("T3", "T1")]
    26. print(find_cycle(edges)) # ['T1', 'T2', 'T3', 'T1']

    Once the cycle is found, the lock on each edge of the cycle is a conflicting lock. When you locate it, look at which lock each transaction on the edge holds and which it waits for. Transaction IDs alone are not enough.

    A few distinctions matter:

    • A lock-wait timeout is not a deadlock. Only one transaction is waiting, and the graph has no cycle. Check the wait-timeout setting and slow transactions, not a deadlock chain.
    • Gap locks can produce a deadlock with no obvious business-level cycle. Under InnoDB’s repeatable-read isolation level, a range query and an insert can wait on each other’s gap locks even when the rows they touch look different.
    • Database differences change how you read the log. InnoDB detects deadlocks automatically and rolls back one transaction as the victim. PostgreSQL detects deadlocks after deadlock_timeout and also rolls back one process. SQL Server shows the cycle in a deadlock graph and chooses the victim by deadlock priority. Oracle records ORA-00060 details in a trace file. Use the official documentation for the version you run for exact field names and defaults.

    5. Step 3: Go back to the code

    After the conflicting locks are identified, confirm the lock order in code. Map each transaction’s SQL on the cycle to the code that issued it.

    Useful mapping clues usually fall into three groups: table names and predicates in the SQL itself, request IDs or thread names in application logs, and stack traces. If that context is missing, add a comment to the SQL, for example /* biz=order-cancel */, so the database log carries a business tag. The next deadlock then points directly at an API or job.

    After you have a location, check the common fix directions below. Each item includes how to find it and how to verify it.

    Fix How to locate it How to verify it
    One lock order List every transaction that updates several tables or rows together, and record the actual update order Compare order across code paths, then use a concurrency test to confirm the deadlock does not return
    Smaller lock scope Find remote calls, loops, or large batch updates inside a transaction Move non-database work outside the transaction and check whether wait time and hold time drop
    Missing indexes Run EXPLAIN on the deadlock SQL and see whether the WHERE clause uses an index Run EXPLAIN before and after the change, confirm fewer rows are scanned, and validate on a test database first
    Transaction boundaries Look for nested transactions and same-class internal calls that disable annotations Use unit or integration tests to confirm commit and rollback scope match the intended boundary
    Retry and timeout Find where the deadlock error code is caught and whether retry logic already exists Inject a deadlock error and confirm retries are capped, use backoff, and the operation can be repeated safely

    A single lock order is usually the most effective fix. If every path updates the order table before the stock table, the two transactions will not wait on each other. That order has to live in a coding standard or a shared method; otherwise new code will break it.

    Retry only hides occasional deadlocks. It does not replace fixing the order. If the same API hits deadlocks often, fix the cause first.

    6. Where reproduction ends and production evidence begins

    Reproduce on a test database. Match the production database version, isolation level, and main indexes, and use redacted data. Two sessions can cross statements like this:

    1. -- session A
    2. BEGIN;
    3. UPDATE t_account SET balance = balance - 1 WHERE id = 1;
    4. -- run after a pause
    5. UPDATE t_account SET balance = balance - 1 WHERE id = 2;
    6. -- session B
    7. BEGIN;
    8. UPDATE t_account SET balance = balance - 1 WHERE id = 2;
    9. -- run after a pause
    10. UPDATE t_account SET balance = balance - 1 WHERE id = 1;

    The two sessions lock in opposite order. The database detects the deadlock and rolls one of them back. Keep this script so the same steps can verify the fix.

    On production, collect read-only evidence only. Allowed actions include:

    • Run SHOW ENGINE INNODB STATUS to see the latest deadlock.
    • Query information_schema.innodb_trx for current transactions. This usually requires the PROCESS privilege.
    • Query performance_schema.data_locks for lock information. This requires read access to that schema.

    The following must be approved first. The person investigating should not run them directly:

    • KILL any session or transaction.
    • Change the isolation level, lock-wait timeout, or similar parameters.
    • Run DDL, add indexes, or change business data.

    Redact logs before sharing them. Replace user IDs, phone numbers, order numbers, and parameter values inside SQL. If privileges are insufficient, request the minimum needed. Do not borrow an administrator account temporarily.

    7. Checklist before you hand it off

    • The log is redacted and keeps only table names, primary keys, and status fields.
    • Production was queried with read-only statements only.
    • Every transaction on the cycle has a matching code location.
    • Lock order has been checked against the code path by path.
    • A regression or concurrency test covers the fix.
    • Deadlock retries are capped, and the retried operation can be repeated safely.