D365FO X++: When to use `while select forUpdate` vs optimistic concurrency to avoid deadlocks
In Dynamics 365 Finance and Operations (X++), what are the correct patterns for updating rows that are first selected inside a while select loop using forUpdate (or selectForUpdate), and how can I avoid deadlocks/lock escalation when multiple transactions update the same records?
Context:
- I’m implementing a service method that loops through rows (e.g., order lines / inventory transactions) and updates fields before calling
update(). - Sometimes I see deadlocks or long waits when running the job concurrently.
Specifically:
- What is the recommended syntax/usage for
while select forUpdatevsselectForUpdatein X++ (including any gotchas)? - When should I prefer optimistic concurrency (e.g., retry on update conflict using
ttsBegin/ttsCommit,selectwithoutforUpdate, orupdate()exception handling) instead of pessimistic locking? - Are there best practices for ordering records, scoping the transaction (
tts), and limiting selected fields to reduce locking footprint?
1 answer
Write an answer1) while select forUpdate vs selectForUpdate: what to use and gotchas#
Default recommendation (most service patterns):
- Use
while select forUpdatewhen you’re going to update the records you iterate, and you can keep the transaction scope and locking footprint small.
// PESSIMISTIC: row locks are taken as the cursor reads the records
ttsBegin;
while select forUpdate myTable
where myTable.Status == Status::Open
&& myTable.Qty > 0
{
myTable.LockField = myValue();
myTable.update();
}
ttsCommit;selectForUpdate / selectForUpdate (single-record pattern):
- Use it when you need to lock one row (or a small known set) rather than iterating a cursor.
- This is functionally similar to
select ... forUpdate, but used for single-row scenarios.
ttsBegin;
MyTable t;
select firstOnly forUpdate t
where t.RecId == recId;
if (t.RecId)
{
t.LockField = myValue();
t.update();
}
ttsCommit;Gotchas / important details
- Don’t do heavy work inside the locked loop. Anything that takes time (extra queries, remote calls, complex calculations, calling other services that query/lock other resources) increases deadlock probability.
- Transaction scope matters more than the keyword. If you hold locks for a long
ttsBegin/ttsCommitwindow, you increase lock contention and deadlocks. - Cursor read order affects deadlocks. If two transactions lock records in different orders, deadlocks are much more likely.
- Avoid selecting more rows than needed. Even if only a few rows are updated, the lock footprint depends on what the database has to read to satisfy your
wherepredicates and ordering.
Note: In X++ you’ll often see both phrases in the wild; the key practical distinction is cursor vs single-row usage and—critically—how long the locks are held.
2) When to prefer optimistic concurrency (retries) vs pessimistic locking#
Use pessimistic locking (forUpdate) when:
- You must guarantee correctness under concurrent updates (e.g., you cannot safely re-evaluate later).
- You are updating a small, well-filtered set.
- The processing is short and deterministic.
Use optimistic concurrency when:
- You expect collisions to be relatively rare.
- Your work can be safely re-read and retried.
- You want to minimize lock duration/footprint.
Practical optimistic pattern:
- Select without
forUpdate, compute intended changes, then callupdate(). - If
update()fails due to optimistic concurrency (typical symptom: record no longer matches what you thought / optimistic conflict), catch, re-select, and retry.
A common service approach looks like:
const int maxRetries = 3;
int retry = 0;
while (true)
{
try
{
ttsBegin;
// Read the row WITHOUT forUpdate to avoid holding locks while computing
MyTable t;
select firstOnly t
where t.RecId == recId;
if (!t.RecId)
{
ttsCommit;
break; // nothing to update
}
// Apply changes based on the latest data
t.LockField = myValue();
t.update();
ttsCommit;
break;
}
catch (Exception::UpdateConflict) // placeholder: use your environment's actual conflict exception type
{
ttsAbort;
retry++;
if (retry >= maxRetries)
{
throw;
}
// Optional short backoff
}
}Important: the exact exception type for optimistic concurrency conflicts depends on the runtime/framework behavior. If you’re not 100% sure which exception type to catch, human review is needed in your codebase.
Edge cases with optimistic
- If your logic assumes fields won’t change between read and update, you must re-validate before updating (or be prepared to retry).
- If you update the same record many times in a single batch, optimistic retries can become a throughput bottleneck.
Deadlock reduction via optimistic:
- Optimistic avoids holding locks during the “read/compute” phase. You only lock briefly during the update statement.
3) Best practices: ordering, scoping tts, limiting footprint#
A) Order records consistently#
When multiple workers/processes iterate the same dataset, ensure they lock in the same order.
Example: always order by RecId (or another stable unique key):
ttsBegin;
while select forUpdate myTable
order by myTable.RecId
where myTable.Status == Status::Open
{
myTable.LockField = myValue();
myTable.update();
}
ttsCommit;If two jobs both lock RecId ascending, you drastically reduce cyclic wait.
B) Keep tts blocks small#
- Don’t wrap the entire batch (possibly minutes) in one
ttsBegin/ttsCommit. - Consider committing per record or in small batches, especially if you’re using
forUpdate.
Example “per record” pattern:
while select forUpdate myTable
order by myTable.RecId
where myTable.Status == Status::Open
{
ttsBegin;
myTable.LockField = myValue();
myTable.update();
ttsCommit;
}This can increase commit frequency but often reduces deadlock likelihood.
C) Limit selected rows and fields#
X++ selection typically translates to SQL selecting needed columns. Still, you can:
- Tighten
whereclauses (include all relevant keys/partitions). - Avoid broad ranges that require scanning.
- Where possible, restrict to only what you must use in computation.
In many cases, the bigger lever is predicate selectivity and stable ordering, not micro-optimizing column lists.
D) Avoid cross-resource locking inside the loop#
Deadlocks often happen when A locks record set X and then tries to lock resource Y, while another transaction locks Y first and then X.
Mitigations:
- Don’t query/update other tables that will require locks while you already hold locks on the first set.
- If you must, enforce a global lock ordering (always acquire locks in the same sequence across all code paths).
E) Consider processing in batches by key ranges#
If jobs run concurrently, splitting the workload deterministically reduces collisions.
Common approach:
- Process “by RecId range” or “by partition key” where each worker gets a disjoint subset.
(Exact implementation depends on your data model; the key idea is partition work deterministically.)
Quick decision guide#
- Small, selective set + very short processing + need guaranteed correctness:
while select forUpdate ... { update(); } - Collisions are expected and you can retry safely: optimistic (no
forUpdate, retry on conflict) - High concurrency + deadlocks today:
- Add consistent
order by(stable key) - Shorten
ttsscope - Reduce work under lock
- If still problematic, switch to optimistic + retry for conflict cases
- Add consistent
Questions for you / where I need human confirmation#
- What exact table(s) are you updating (and are there unique constraints/financial dimensions/etc.)?
- Are deadlocks happening during
forUpdateread, duringupdate(), or in downstream logic you call inside the loop? - If you pursue optimistic retry: which exception type(s) do you currently observe for update conflicts in your environment? (I can tailor the catch block if you provide the observed exception/log text.)
Know the solution?
Sign in to contribute an answer and build your community reputation.
Sign in to answer