Skip to main content

Salesforce Row Locking and how to avoid it (UNABLE_TO_LOCK_ROW)

Error : UNABLE_TO_LOCK_ROW, unable to obtain exclusive access to this record or N records 

When a record is updated or created, A lock will be placed on that record and its related record to prevent another operation from updating  the records at the same time and causing inconsistencies on the data.

These locks normally last for a few seconds and when the lock is released, other operations can resume processing they are supposed to do on the record in question. However, a given transaction can only wait a maximum of 10 seconds for a lock to be released, otherwise it will time out.

Common Reasons

  1. When record update happens, that record and its related records will be locked to allow roll back incase of exception
  2. Ownership change on Parent will trigger sharing recalculation on every child. Due to Dataskew,  This recalculation can take a lot of time.  Also When the child records are updated as part of multiple parallel batches, Each batch will try to lock the parent records and causing this row_lock errors.
  3. Explicit Locking the record using "For Update" statement in the query

Solutions:

  • Bulk API
    • If the records are processed in bulk, try to reduce the size.
    • In case the parallel mode is used in bulk API, try changing to serial mode.
    • Sort main records based on their parent record, to avoid having different child records of same parent in different batches when using parallel mode.
  • Dataskew
    • If the dataskew is found (Any parent record having more than 10k children), Split the parent account into multiple records and distribute the children .
  • Optimize your code and check if some functionality can be changed as asynchronous

Comments