In March 2025 — back when I was still on the agency side, working on fleet projects — a strange pattern started showing up in a logistics company's order system: every day around 14:00, within a five-to-ten-minute window, dozens of "Deadlock found when trying to get lock; try restarting transaction" errors. The rest of the day was spotless. The team had brushed it off for weeks as "it's just the load"; but when we looked at the traffic, 14:00 wasn't even the busiest hour of the day. This case put everything I know about deadlock hunting to the test once again, and in this post I'll walk through, step by step, how we solved it — because the method is more valuable than this specific case.
The first suspect is always the wrong suspect
The first reflex of teams that see a deadlock error is usually to look at the code that threw it. That's natural but misleading, because when InnoDB detects a deadlock, it picks as the victim the transaction that's cheapest to roll back. In other words, the code that sees the error is, more often than not, the innocent party. The culprit is the other transaction, the one that carries on without ever seeing the error.
That's why the first stop isn't the code but the "LATEST DETECTED DEADLOCK" section of the SHOW ENGINE INNODB STATUS output. There you can see the last query each of the two transactions ran, which locks they held and what they were waiting for. In our case, the picture was this: the first transaction was the familiar API code that updates order lines. The second was something nobody had thought of — a batch job for the accounting integration that ran every hour and switched into monthly reconciliation mode at 14:00 that day.
The first lesson here: deadlocks are almost always born at the intersection of two different worlds. Queries written by the same team and living in the same codebase usually acquire locks in a similar order and don't collide. The danger begins where API code meets a batch job, the application meets a manual reporting query, or an old module meets a new microservice.
The culprit was ordering: one from the top, one from below
When we picked apart the status output, a classic pattern emerged. While updating orders, the API code locked rows in ascending order of order line ID. The reconciliation job, on the other hand, touched the same rows with an UPDATE grouped by customer number — which physically means a completely different lock acquisition order. When one starts locking the list from the beginning and the other from the middle, it's only a matter of time before each transaction is waiting on what the other holds.
The first half of the fix is a textbook classic: everyone acquires locks in the same order. We split the reconciliation query so that it first locks the rows to be updated in ID order with SELECT ... FOR UPDATE, and then updates them. The second half is a less-discussed measure: we broke the reconciliation job's single giant transaction into chunks of 500 rows each. The longer a transaction lives, the wider the window in which it holds locks, and the probability of collisions grows not linearly but exponentially. Chunking alone had already cut the number of deadlocks to a tenth.

Gap locks: locks on invisible rows
If the story ended here, it would be a neat case study, but real life doesn't work that way. Two weeks after the fix, a completely different deadlock appeared in the same system, this time once or twice a day. The status output this time showed not two familiar UPDATEs but an INSERT and the phrase "lock_mode X locks gap before rec." A gap lock — InnoDB locking the gap between two records in an index under REPEATABLE READ. Hitting a deadlock because of locks on rows that don't exist is a surreal experience for a developer encountering it for the first time; you search the database for the thing that's locked and can't find it, because there's no row there, only a gap.
In our scenario, two concurrent requests for the same order would each first check whether a record existed and, if not, try to INSERT it. Both placed a gap lock on the same gap, then both waited for the other's lock to be released in order to INSERT. Here the fix was on the schema side, not the query side: the right unique index, and abandoning the check-then-insert pattern entirely in favor of INSERT ... ON DUPLICATE KEY UPDATE. The "check with a SELECT first, insert if it's not there" pattern is a sneaky trap that doesn't work under concurrency but always works in testing; we now flag it automatically in code reviews.

Don't try to eliminate deadlocks, try to make them harmless
I need to call out a goal I don't like here: "let's get rid of deadlocks completely." In any system doing heavy concurrent writes, the possibility of deadlocks lives on; that's precisely why InnoDB's detection mechanism exists. The realistic goal is to make deadlocks rare and harmless. And the way to make them harmless is honest retry logic in the application layer: when a deadlock error is caught, retry the transaction at most two or three times after a short, randomized wait. The error message itself already gives the instruction — "try restarting transaction" — yet a surprising number of codebases settle for surfacing this error to the user as a 500.
One caveat when adding retries: your transaction block must be idempotent, meaning that repeating an attempt that ran halfway and was rolled back must not produce duplicate records. Code that buries irreversible side effects like sending emails inside a transaction will, combined with retries, have your customer sent the same invoice three times. (It happened. Not at our place, but in a codebase that landed in my hands years ago, and the cleanup fell to me.)
The isolation level debate came up at this point too, so let me write down the honest answer: for long queries whose consistency isn't critical at the row level, like reconciliation reads, dropping to READ COMMITTED significantly reduces gap lock friction. But I don't recommend applying it to the whole system as a blanket fix; lowering isolation sometimes doesn't solve the locking problem, it just turns it into a data inconsistency problem, and inconsistency, unlike a deadlock, doesn't have the courtesy to show you an error message. We apply level changes per query, as exceptions with their justification written into the inventory.
Then there's the monitoring side. To see all deadlocks rather than just the latest one, we turned on innodb_print_all_deadlocks and wired the log into centralized monitoring; deadlock count now sits in the weekly report as a metric. At that logistics company, the number was over 200 a week before the intervention; by the time we left it had dropped below three, and all of them were resolved by retries without ever touching the user. Today we track the same metric in the weekly report for our platform's order database as well.

After closing the case, I brought the drill tradition I started back then to my current team as well: we have every new developer deliberately produce a deadlock in the staging environment and read the status output. It may sound like an odd way to spend working hours, but the difference between seeing deadlock output in production for the first time at 03:00 and seeing a format you've already picked apart five times determines how many hours that night will last. For a developer who can comfortably read the lock types, index names and waiting/holding relationships in the output, a deadlock isn't a mysterious disaster but an ordinary maintenance item.
As for the 14:00 mystery, it's completely closed — the reconciliation job still runs at the same time every day, but nobody notices anymore. To me, that's the ultimate sign of good debugging: no trace left except the graph proving the problem was solved. If your system also has locking patterns you can't explain, the method is the same: reading the status output takes half an hour, finding the pattern usually takes a day, and that one day is always cheaper than months of "it blows up now and then" uncertainty. I enjoy talking through cases like these; my contact page is open.