Why does an X++ select forUpdate deadlock when I update a related table inside the same loop? (locking order)
In an X++ job (non-SSRS), I run a while select forUpdate over TableA and, for each record, I update a related record in TableB inside the loop.
Intermittently, concurrent runs deadlock in SQL. I suspect the lock acquisition order is inconsistent across sessions because the update touches TableB while the forUpdate holds locks on TableA.
For example:
TableA a;
TableB b;
while select forUpdate a
where a.Status == Status::Open
{
b = TableB::findByA(a.RecId, true); // updates TableB
ttsbegin;
b.Status = Status::Processed;
b.update();
ttscommit;
}What’s the correct way to structure the locking so this pattern doesn’t deadlock (e.g., locking order / whether forUpdate should be on both tables, or whether the update should be done outside the forUpdate loop) in D365FO/X++?
1 answer
Write an answerWhy it deadlocks#
Your while select forUpdate a holds update/intent locks on TableA for the duration of each iteration (until the row is updated/transaction ends depending on how/where you commit). Inside the same loop you call TableB::findByA(..., true) and then b.update(), which acquires locks on TableB.
With concurrent sessions, the deadlock usually comes from inconsistent lock acquisition order:
- Session 1: locks
TableA(row1)first, then tries to lockTableB(row1) - Session 2 (different data/order): locks
TableA(row2)(orTableB(row2)via its own processing path) first, then tries to lock the other table
SQL detects the circular wait and picks a victim.
Even if your sample loop always looks the same, real systems often have:
- different iteration order due to missing/changed ordering
- other code paths locking
TableBbeforeTableA - different numbers of rows locked per transaction depending on commit scope
Correct approach: lock a single “driving” set with consistent order#
In D365FO/X++ the safest pattern is:
- Build the workset first (deterministic ordering if needed).
- Then lock/update in a consistent order.
- Keep the lock scope small (short transactions).
Concretely, avoid holding forUpdate locks on TableA while you also go and lock/update TableB via find... inside the loop.
Option A (usually best): don’t use forUpdate on TableA; instead lock TableB in the same transaction#
Drive the processing from the table you actually update.
Status aStatus = Status::Open;
TTSLevel ttsLevel = 1; // optional illustrative; use normal ttsBegin/ttsCommit
while select forUpdate b
where b.Status == Status::Open // or whatever condition implies the work
{
ttsbegin;
b.Status = Status::Processed;
b.update();
ttscommit;
}Then (if you still need TableA state) read TableA without forUpdate after or based on what you already locked, e.g. a = TableA::find(b.TableARecId); (no locking if you don’t require it).
This works because now SQL always acquires locks in the same order: only TableB is locked for update by this routine.
If you truly must decide eligibility based on
TableAfields, make the eligibility part of theselectused to findTableBrows (join/filter), so the routine still locks only one updated table.
Option B: if you must lock both, lock them explicitly in a fixed order#
If your algorithm requires both tables to be locked, you must ensure every session acquires locks in the same order, and do not rely on findByA(..., true) to “do the right thing”.
Typical pattern:
- Explicitly select
arows in a deterministic order. - For each
a, first lock the correspondingbwithforUpdate(orselect forUpdate b where b.Key == ...). - Only then update.
Example skeleton:
TableA a;
TableB b;
while select a
order by a.RecId
where a.Status == Status::Open
{
ttsbegin;
// Lock TableB first (fixed order across sessions)
select firstOnly forUpdate b
where b.ARecId == a.RecId;
// Do updates
b.Status = Status::Processed;
b.update();
ttscommit;
}Key points:
- Don’t hold
forUpdateonTableAwhile trying to lockTableB. - Lock
TableBin a consistent order (here: by processingadeterministically, and locking the singlebrow pera).
You could lock TableA first and then TableB—but that’s exactly what often causes deadlocks when other code paths lock in the reverse order. Pick one order and make it uniform.
Important refinements#
- Keep transactions short. Your sample opens/closes
ttsinside the loop (good). However, thewhile select forUpdatemay still hold locks longer than you think depending on how the kernel batches/holds row locks. The safest change is: avoidforUpdateonTableAentirely in this pattern (Option A), or at least ensure you’re not holding locks onTableAwhile waiting onTableB. - Deterministic processing order. Add
order byon the driving cursor (e.g.,order by a.RecId). Without it, concurrent sessions can touch records in different orders, increasing deadlock probability. - Avoid “update via find() with locking side effects”.
TableB::findByA(..., true)(with a boolean that likely means forUpdate) can be convenient, but it hides the locking behavior. Prefer an explicitselect forUpdatefor the table you update so lock acquisition is obvious.
Summary#
- Deadlock happens because your routine effectively acquires locks in different sequences across concurrent sessions (
TableAviaforUpdate, thenTableBviafind...(..., true)/update). - Fix it by driving/locking from the table you update (Option A), or by explicitly locking both tables in one consistent order and using deterministic cursor ordering (Option B).
If you share the real relationship (keys) between TableA and TableB and whether TableB has a status flag you can filter on, I can suggest the most robust join/filter so you only lock TableB.
Know the solution?
Sign in to contribute an answer and build your community reputation.
Sign in to answer