If one deadlock log entry is from a background batch job and another from a user order, is staggering their run times enough?
An occasional Deadlock found during inventory deduction: retries can get the current request past the error, but they do not address the root cause. An InnoDB deadlock happens when two transactions hold locks in opposite order and wait for each other to release them; after detecting a circular wait, InnoDB rolls back one of them, and earlier writes in that transaction are lost as well. Based on common 2026 delivery experience, first use the deadlock log to confirm lock order and lock scope, then decide whether to switch to a single-row conditional update, unify the lock order, or adjust the batch timing; keep only 2–3 retries as a fallback. When one log entry comes from a background batch job and another from a user order, simply staggering their run times usually only reduces how often the issue reproduces.
1. A deadlock is not the same as a lock wait timeout; mixing them up makes fixes messier
An InnoDB deadlock is a circular wait: two transactions each hold one lock and are both waiting for the other one. After detecting the cycle, the database chooses the lower-cost side to roll back, and the application usually sees error code 1213. A lock wait timeout is a one-way wait: one side waits until innodb_lock_wait_timeout expires and then reports 1205. One is mutual waiting; the other is one-sided waiting. The troubleshooting direction and retry parameters are different.
Treat it as a separate problem because a deadlock rolls back the entire transaction. Catching it at the outer layer and retrying may make the success rate look better, but each rollback pays the full cost of a connection and computation again; during peak hours it lengthens P99 and can keep covering up the real ordering problem for a long time.
- Deadlock (1213): both sides hold locks and wait for each other; the database actively rolls back one side, usually returning within tens of milliseconds, rather than hanging indefinitely.
- Lock wait timeout (1205): one side waits for the other to release a lock and reports an error only after the parameter threshold; the default value is commonly in the range of tens of seconds.
- Focus of handling: for deadlocks, prioritize changing lock order and lock scope; for lock wait timeouts, prioritize checking long transactions, uncommitted sessions, and connection usage.
2. Do not rush to change code; first read the deadlock log clearly
Deadlock logs are information-dense. If you do not read them in a fixed order, it is easy to stare only at your own SQL and jump to a conclusion. Reading in the wrong order also makes it easy to misjudge an index problem as a code ordering problem.
- Look at the locks: what each transaction holds and what each is waiting for, and whether two SQL statements lock in opposite order.
- Look at the scope: which table and index are involved, and whether the number of scanned and locked rows is far larger than actually needed.
- Look at the pattern: isolation level, whether range conditions are present, and whether there are batch IN clauses or concurrent inserts of the same unique key.
- Assign responsibility: determine whether the issue lies in code order, a missing index, or a timing conflict between batch processing and online transactions.
The second step is often skipped, but it determines whether the later solution will work: a large scanned row count means the lock scope has already been amplified, so adding an index or rewriting the condition first brings more direct benefit than reordering locks. Only when both paths are confirmed to be doing precise row locking is lock ordering the right remedy.
A common set of constraints at a delivery site looks like this: the budget is limited and the timeline is compressed to about two weeks; the inventory and order paths are written by different engineers, and each path uses the primary key index, but one path updates orders before inventory while the other does the reverse—the deadlock rate is not high under load testing and only shows up in production during a major promotion. The approach is to unify both paths to update inventory before orders, and change the deduction step to a conditional single-row update. The cost is touching three existing interfaces and about two days of regression; the gain is that deadlock alerts drop from several per day to occasional, and the retry logic becomes a fallback. For such refactoring, common 2026 delivery practice usually reserves 2–5 days for mapping and regression, depending on the number of write paths; this is a typical range, not a fixed value.
3. Root causes mostly fall into three categories; choose convergence measures by cost
When online deadlocks are categorized, most fall into three places: ordering problems about who goes first, locking rows or gaps that should not be locked, and batch processing colliding with online requests in the same time window. The first two can be fixed at the root by changing code or indexes; the third often requires scheduling offsets or queue-based convergence.
- Opposite order: path A updates orders before inventory, while path B does the reverse; even if both use indexes, they still wait for each other.
- Amplified lock scope: the update condition does not use an index, so rows can only be locked one by one over a wide range, and unrelated business operations may also collide.
- Gap locks: under RR isolation, range conditions lock the gaps between records, making insert-heavy business operations prone to conflict with them.
- Batch and online crossing: scheduled jobs update in ascending primary key order in batches, while online requests update in business order; the directions are naturally inconsistent.
A common counterexample is to simply lower the isolation level from RR to RC and stop there. This can indeed reduce gap-lock-related conflicts, but if the log shows that the two paths lock rows in opposite order, lowering the isolation level only reduces how often the issue reproduces; the root cause remains.
For choosing measures, here is a reference based on experience ranges commonly seen in 2026 projects:
- Single-row conditional update: combine “check stock, evaluate, then update” into one UPDATE ... WHERE id = ? AND stock >= n, keeping the lock set constant. The modification cost is commonly half a day to two days, suitable for single-row numeric deductions such as inventory and balances; however, you must check the affected row count and treat 0 as insufficient stock.
- Fixed lock order: when multiple paths involve the same few tables, write uniformly in primary key or fixed-field order. This requires mapping all write paths and commonly takes 2–5 days; suitable for multi-table coordination among orders, inventory, and accounts.
- Optimistic lock version number: read with a version and write with a version condition. It is more cost-effective when the conflict rate is not high; a high conflict rate can create a retry storm and instead amplify pressure.
- Pessimistic lock or serial consumption: SELECT ... FOR UPDATE or single-threaded queue consumption. Throughput is limited; suitable for scenarios requiring strong consistency and controllable concurrency, such as fund changes for a single account.
In terms of sequence, first see whether a single-row update can eliminate the lock set; if not, then consider global lock ordering. Optimistic and pessimistic locking are trade-offs in the concurrency model and involve larger changes. These measures are not mutually exclusive; in practice, a combination of lock ordering plus fallback retries is common.
4. What qualifies as acceptable retry code, and when a major change is unnecessary
Retries have their own cost. If written incorrectly, they introduce a second class of failures: duplicate deductions, duplicate messages, or continuing to build SQL after the transaction has rolled back. The boundary for acceptable retries has three points: whether the catch scope is explicit, whether side effects are idempotent, and whether there are observable counters.
- Catch only explicit deadlocks such as 1213; do not catch all exceptions and retry uniformly.
- Keep retries to 2–3 times (experience range); if it still fails beyond that, the issue is not occasional and you should go back to the log.
- Before each retry, confirm that the transaction has fully rolled back, and do not continue operating within a failed transaction.
- Add backoff and random jitter, commonly in the range of tens of milliseconds, to avoid multiple machines colliding again at the same moment.
- The retried method must be idempotent: move side effects such as sending messages and calling external APIs to after transaction commit, or deduplicate by business order number.
- Observe deadlock count, retry success rate, and the number of failures after retry on a daily basis; these three metrics show whether the issue is truly converged better than “whether an error was reported.”
A typical counterexample: uniform try-catch retry at the outer layer of a business method; the transaction rolls back, but a message written inside the transaction has already been sent. The user sees one error followed by one success, while the backend sees two identical notifications. Whether such side effects are moved out of the transaction is almost never exposed in test environments and only appears in a concentrated way under major-promotion concurrency; it should be listed as a must-check item during acceptance.
Applicable and non-applicable boundaries: the first candidates for governance are concurrent writes to the same batch of rows from multiple paths, mixed batch and online workloads, and deduction-type operations. Major changes are unnecessary for admin backends, low-frequency single-row updates, and read-heavy, write-light query paths; an occasional retry is enough. It is not advisable to lower the overall isolation level just to eliminate deadlocks without assessing the consistency impact, or to change concurrency to single-threaded serial processing and trade throughput for removing deadlock errors. One independently quotable boundary: when a path updates only one row and the condition includes the primary key, it usually will not deadlock; if reports still appear at that point, first check whether another transaction has performed a range update on the same row or in the same interval.
5. Frequently asked questions
How many times should a deadlock error be retried?
The experience range is 2–3 times with tens of milliseconds of backoff. If it still fails beyond that, lock order or lock scope has a problem; go back to the log to locate it rather than increasing the retry count further.
If I change the isolation level from RR to RC, will deadlocks disappear?
It only reduces one class of conflict: gap locks. Opposite lock order and lock-scope amplification from missing indexes can still happen; before changing it, first confirm which root cause the log records.
If the background batch job and user orders run at staggered times, does that bypass the problem?
In most cases, it only reduces how often the issue reproduces. If the two paths themselves lock in opposite order, staggering just makes them collide less often; the root cause remains, and you still need to unify lock order or switch to a single-row conditional update.
When using UPDATE with stock >= 1 to deduct inventory, do I still need to lock and query first?
Usually you do not need a separate locking query; one conditional update is enough to prevent overselling. However, check whether the affected row count is 1; if it is 0, treat it as insufficient stock and return a clear message.
Can retries cause inventory to be deducted twice?
Yes, if the retry wraps the entire business method and side effects are not deduplicated. Move operations such as sending messages and calling payment to after transaction commit, and make them idempotent by business order number.
If you currently have a path with occasional deadlocks, you can do three things first: read the deadlock log in a fixed order, confirm the lock order of the two paths, and assess whether they can be changed to a single-row conditional update. Low-frequency deadlocks with controllable retries can be scheduled for later; high-frequency deadlocks or those involving funds and inventory should be prioritized. The thresholds and timelines above are based on common project delivery experience; in practice, verify them against your own concurrency volume, database version, and consistency requirements.
-
Inventory and orders update at the same time and occasionally report Deadlock found—can increasing retry counts alone suppress it?
Date: Sep 24, 2026 Read: 57
-
Detail page images looked fine at launch, but days later customers see broken images—are private bucket signed links expiring?
Date: Nov 23, 2026 Read: 4
-
Order time shows 1970 in the order list but exports correctly to Excel: fix the page first or unify the API unit first?
Date: Nov 22, 2026 Read: 8
-
After the certificate is renewed and replaced, why does the client’s phone still show “not secure”—is the cache not refreshed?
Date: Nov 21, 2026 Read: 12
-
Invoice PDF only flashes when tapped in WeChat, but opens normally in a mobile browser—do we still need to change anything?
Date: Nov 20, 2026 Read: 17




