Avoid Recursive Trigger in Apex Salesforce

Recursion is the process when a trigger calls itself repeatedly and leads to an infinite loop. There may be a chance to hit the governor limit with Recursive Triggers. We always wanted to avoid Recursive Triggers but many Apex Triggers, Process Builder, Record-Triggered Flow, and Work Flow are there on Single Object with parent-child updates then we can easily face the recursive trigger issue. 

So today I will share a few methods using which we can easily avoid recursive triggers. Let's go in deep:

How to avoid recursion in triggers? 

There are different ways to solve the recursion in the trigger. We will go through each way one by one:

1. Use Static Boolean Variable

We can use the Static boolean variable to avoid recursion. Initially set this boolean variable to true and once execution is completed set it to false. In the trigger, before executing your code keep a check that the variable is true or not. Once you check make the variable false.

Apex Class 

Apex Trigger

Static in Salesforce is per transaction, so the value will be true only for the current transaction. This practice is good for less than 200 records. It will update the first 200+ records then it will skip. PLEASE DON'T USE IT.

2. Use Static Set or Map

Instead of using Boolean Variable, we can use Set or Map to store all executed record ids. So, when next time it will execute again, we can check record Id is already executed or not. Let's see how we can use it:

2.1 Use Static Set

Let's try the above code for more than 200 records and see the result. The use of Set is not perfect because it is possible that you may get both insert and update within the same transaction.

2.2 Use Static Map

By using Map, you can handle all events using the same map.

3. Follow Best Practices for Triggers

Follow best practices and trigger frameworks to avoid recursion.

  1. One Trigger per Object so you don't have to think about the execution order as there is no control over which trigger would be executed first.
  2. Logic-less Triggers - use a helper class to handle logic
  3. Code coverage 100%
  4. Handle recursion - To avoid the recursion on a trigger, make sure your trigger is getting executed only one time. You may encounter the error: 'Maximum trigger depth exceeded if recursion is not handled well.
Conclusion:
There are different ways to handle recursion. You can use anyone according to your business case. But I highly recommend you to go with Trigger Framework and one trigger per object to avoid recursion. 

That's all for today! This is how we can avoid Recursive Triggers in Apex. Still, if you have any further suggestions, thoughts, and questions, then just make sure to comment down.

Thank You!

Comments