All articles

Platform

Salesforce record locking: why UNABLE_TO_LOCK_ROW fires and how to design it out

The error almost never names the record that is really stuck. It names a child, while something else holds the parent two objects away. Here is how Salesforce locks records, why parallel loads and racing automation collide, and the patterns that stop the retries.

A nightly integration loads ten thousand order lines, and a few hundred fail with UNABLE_TO_LOCK_ROW. You rerun the failed rows and they pass. The data is fine. The job is not, because tomorrow night it fails again on a different few hundred.

Record locking is the contention nobody designs for until it shows up in a load log. The fix is rarely the row the error names. Group your writes by parent, keep each lock short, and retry with backoff off the main thread. Do that and the error stops being a nightly chore.

A lock protects a record for the length of a transaction

Salesforce locks a record while a transaction writes to it, so two transactions cannot change the same row at the same time and leave it half-updated. A second transaction that wants the same lock waits. If the wait runs long, Salesforce gives up and throws the error rather than hang forever.

The wait is short. A blocked write holds for about ten seconds before it fails, which is why a rerun so often works: by the time you look, the other transaction finished and the lock is gone. A retry that succeeds is not proof the problem is gone. Two writes overlapped for a moment, and they will overlap again.

The piece people miss is which record gets locked, and it is usually not the one you wrote.

The parent is the record that is really locked

When you insert or update a detail record in a master-detail relationship, Salesforce locks the master record too, to keep the rollup and the referential integrity consistent. The Bulk API planning guidance spells this out: child DML locks the parent for the length of the transaction.

So the collision is structural. Two order lines that belong to the same order are two child writes that both need the same parent lock. Load them in parallel and one waits on the other. The error names an order line, but the contended row is the order.

The same thing happens through lookups set to lock the parent, through junction objects between two masters, and through ownership changes that trigger sharing recalculation across a role hierarchy. A change of owner on a parent account can cascade into locks on records you never touched, because the platform is recomputing who can see what.

The rule to carry: a write locks more than the row you wrote, and the blast radius follows your relationships and your sharing.

Why parallel loads collide

The Bulk API processes batches in parallel by default. Parallelism is what makes it fast, and it is also what manufactures lock contention when two batches hold children of the same parent.

Picture a batch of order lines sorted by the order they arrived in. Lines for order A are scattered across batch 1, batch 3, and batch 7, and those batches run at once. Three transactions reach for the lock on order A, two of them lose, and the rows come back as failures. Nothing is wrong with the data. The arrangement is wrong.

Two levers fix most of it:

  • Sort the input by the parent ID before you load, so all of a parent’s children land in the same batch and are written by one transaction instead of racing across several. This single change removes the most common source of bulk-load locking.
  • Fall back to serial mode when sorting is not enough. Bulk API 1.0 accepts a Serial concurrency mode that runs batches one after another, trading throughput for the guarantee that two batches never fight over a parent. Bulk API 2.0 does not expose that switch, so a job that needs serial processing is a reason to stay on 1.0 for that load. Serial still carries a small residual risk if other automation writes the same records at the same time.

These are load-design choices, not code. Most locking on data migrations and nightly syncs is solved before a line of Apex, by changing how the rows are ordered and batched. The Bulk API 2.0 mechanics are worth knowing in full when you are moving millions of records.

FOR UPDATE: locking on purpose, and its two traps

Inside Apex you can take a lock deliberately. Append FOR UPDATE to a SOQL query and Salesforce locks the rows you selected until the transaction ends, so nothing changes them between your read and your write. The Apex locking statements reference is the canonical description of the keyword.

// Read the counter, then update it, with no one changing it in between.
Account a = [SELECT Id, Active_Sessions__c FROM Account WHERE Id = :accId FOR UPDATE];
a.Active_Sessions__c = (a.Active_Sessions__c == null ? 0 : a.Active_Sessions__c) + 1;
update a;

Use that for a read-modify-write on a record several processes increment. The keyword also carries two traps.

The first trap is ordering. If one transaction locks record X then Y, and another locks Y then X, they can deadlock, and the platform kills one. Lock rows in a consistent order (by Id works) everywhere you use FOR UPDATE, so two transactions never hold each other’s next lock.

The second trap is callouts. The lock a FOR UPDATE query takes is released when the transaction makes a callout, so a long HTTP call inside a locked section stops protecting the record the way the top-to-bottom code suggests.

Do the callout first, then take the lock and write in a tight window at the end. Mixing callouts and FOR UPDATE in one stretch of logic is how a lock you thought you held turns out to be gone.

Racing automation is the other half

Data loads are the obvious cause. The quieter one is your own org writing to the same records from two directions at once.

A record-triggered flow and an Apex trigger that both update a parent, an aggregation that recomputes on every child change, a scheduled job that sweeps the same objects a user is editing: each is a transaction competing for the same locks. More automation on a hot object means more contention, and the symptom is intermittent locking that nobody can reproduce on demand.

Two habits keep this down. Keep one automation path per object so updates flow through a single ordered place instead of several racing handlers, which is the whole argument for a disciplined trigger framework. And push non-urgent recomputation off the synchronous transaction, so the user’s save is not holding a lock while a rollup grinds. Staying inside the governor and concurrency budget is the same muscle.

Retry, but retry correctly

Some contention is unavoidable, so the write has to survive a lost lock. The wrong retry loops in the same transaction, holds its own locks while it sleeps, and makes the pile-up worse. The right retry hands the work to a fresh transaction.

public class LockAwareUpdate implements Queueable {
    private List<SObject> records;
    private Integer attempt;

    public LockAwareUpdate(List<SObject> records, Integer attempt) {
        this.records = records;
        this.attempt = attempt;
    }

    public void execute(QueueableContext ctx) {
        try {
            update records;
        } catch (DmlException e) {
            // Retry only lock failures, and only a bounded number of times.
            if (e.getMessage().contains('UNABLE_TO_LOCK_ROW') && attempt < 3) {
                // A new Queueable is a new transaction, after a back-off delay,
                // so the original lock is long gone before this runs.
                System.enqueueJob(new LockAwareUpdate(records, attempt + 1));
            } else {
                throw e;
            }
        }
    }
}

Three rules make a retry safe rather than a denial-of-service against your own org. Bound the attempts, so a stuck record fails loudly instead of enqueueing forever. Retry only lock errors, never validation or a null pointer, which no amount of waiting fixes.

And retry in a new transaction. A Queueable runs after the current one commits, so the lock that blocked you is already released, and chaining them spaces the attempts out instead of slamming the same instant.

What I would check first

Start with the shape of the load before you touch code. Sort the file by parent ID, confirm children of one parent are not split across parallel batches, and drop to serial mode for the handful of objects where contention persists. That removes most bulk-load locking for free.

Then look at your automation. Count how many things write the parent object on a normal save, collapse them toward one ordered path, and move anything that does not have to be synchronous off the user’s transaction. For the deliberate read-modify-write cases, use FOR UPDATE, lock in a consistent order, and keep callouts out of the locked window.

Keep retries as the safety net, not the strategy. If your job only works because it retries half its rows every night, the contention is still there and the load is one busy evening away from failing for real. The durable fix is to stop two writes from wanting the same lock at the same time, and most of that is design you control. Untangling an org where racing automation makes every data load a gamble is a large part of our managed services and org-rescue work.

Understanding the basics

What causes UNABLE_TO_LOCK_ROW in Salesforce?

Two transactions tried to write the same record, or the same parent record, at the same time. One took the lock, the other waited about ten seconds, and then failed. The most common sources are parallel Bulk API batches holding children of the same master-detail parent, several automations updating one object at once, and ownership changes that trigger sharing recalculation across a role hierarchy.

Why does the error name a record I did not change?

Because a child write locks its parent. When you insert or update a detail record in a master-detail relationship, Salesforce also locks the master to keep rollups and referential integrity consistent. The transaction that loses the race reports a failure on the child it was writing, while the contended record is the parent two objects away.

How do I stop record locking on a large data load?

Sort the input by parent ID so all of a parent’s children are written in one batch instead of racing across parallel batches. If that is not enough, run the load in serial mode, which Bulk API 1.0 supports through a Serial concurrency mode. Serial trades speed for far less contention, so reserve it for the objects that still collide after sorting.

Should I retry UNABLE_TO_LOCK_ROW in Apex?

Yes, but in a new transaction and only for lock errors. Catch the DmlException, confirm it is a lock failure, and re-enqueue the work as a Queueable so the retry runs after the current transaction commits and its locks release. Bound the number of attempts so a stuck record fails visibly instead of retrying forever.


Chasing intermittent UNABLE_TO_LOCK_ROW failures that no one can reproduce? Finding the racing automation and the load design behind the contention, and fixing it so the retries stop, is the kind of org work we do every week. Talk to us.

Keep reading

All articles