I have a scenario where an external system is calling Salesforce API, causing a trigger to run. That trigger needs to delete EmailMessage records where the RelatedTo field is an Account.
We're getting UNABLE_TO_LOCK_ROW errors when the external system's API calls overlap and the trigger attempts to delete multiple emails on the same Account at the same time.
This is totally understandable based on how [record-locking works][1]. RelatedTo is either a required lookup or a Master-Detail so deleting the EmailMessage would require a lock on the related Account.
I tried to solve the problem by adding FOR UPDATE to the query in the trigger where it fetches the EmailMessage records.
But, we still observe UNABLE_TO_LOCK_ROW as a DmlException (if it were a QueryException, then that might be due to the 10-second limit timing out).