I have a scenario where I have an Apex code that runs two inserts on my custom objects, and they can't be bulkified because the Id of the first insert is used in the second one.

I have an after trigger that updates some fields. To avoid recursion, i used a static variable pattern.

Turns out, when we do

insert obj1;
insert obj2;

Those are still the same transaction, so static variable is not reset. Apart from manually resetting it in my code (which i can do, but any other packages/code using my custom object unaware of this won't know to do this) is there a way to reset this or some other way to avoid recursion?


Recursion is typically handled through several means.

Rising Edge Logic

This means that you only perform the action when the record did not previously meet the criteria, and now it does. This breaks out of infinite recursion loops, and is the preferred method for preventing excessive recursion.

Temporary Recursion Lock

Use a static variable, but instead of "set and forget it", you set it specifically when you expect recursion in order to avoid it:

insert accountRecords;

Using a design like this breaks recursion without breaking your business logic. Note that the caller must set recursion lock. This is ideal when you need logic that runs every trigger execution but would cause infinite recursion.

  • Yeah i sort of put together what you illustrate as the Temporary Recursion Lock as well. Still feels incredibly meh but at least it got me past that problem. Thank you!
    – zaitsman
    Aug 11 '20 at 2:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.