how did Record lock in salesforce in my scenario and how to avoid it?

we have a scenario where User role is changes we have to update Account field then Account’s trigger will update 5 related objects so their triggers also fire 🙂 . Earlier we have used process builder at Account level but we are hitting CPU limit so we are switching to Asynchronous (via trigger) .

As I am going through the cheat sheet and understood that if I am modifying a child record and in the same time my Account is getting updated from User trigger it will get locked. so my trigger update may failed because it is already locked.

So is there only one way I can live batch at non working hours? and asking users to wait for the update till tomorrow 🙁


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

A lock occurs for the entire transaction. For example, the following code does not produce a deadlock:

Account a = [SELECT Id FROM Account LIMIT 1 FOR UPDATE];
Account b = [SELECT Id FROM Account WHERE Id = :a.Id FOR UPDATE];

This is true regardless of if this happens immediately (as demonstrated above), or even several recursive trigger contexts deep; the lock is tied to the same transaction.

Typically speaking, if a user gets a “row locked” error, they can usually immediately try again and things will be okay.

In general, you should use FOR UPDATE in a query to obtain exclusive access before attempting to update a record. This will cause a lock delay while the system waits to obtain exclusive access to the record.

If the lock delay isn’t long enough, you might also consider using a spin lock in your asynchronous code while you wait for any pending updates:

SObject[] records;
while(records == null) {
    try {
        records = [SELECT ... FOR UPDATE];
    } catch(QueryException e) {

This will allow you to wait up to about 9 minutes while waiting to acquire the lock. Using this in your asynchronous code should allow at least semi-real-time updates.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x