Avoid Recursive Trigger Calls In Salesforce

Recursion occurs when same code is executed again and again. It can lead to infinite loop and which can result to governor limit sometime. Sometime it can also result in unexpected output or the error “maximum trigger depth exceeded”. So, we should write code in such a way that it does not result to recursion.

For example, I’ve a trigger on Account object, which will be execute on before Update and after Update. In after Update I’ve some custom logic to update Account records. So, when I’m updating the Account records in After Update, it is throwing error “maximum trigger depth exceeded”. So, it is a recursion in apex trigger.

To avoid the situation of recursive call, we have to write code in such a way that the trigger will execute one time. To do so, we can create a class with a static Boolean variable with default value true. In the trigger, before executing the code keep a check that the variable is true or not.

Here in below trigger, I want to execute both before and after Update trigger only one time. I’m checking the static Boolean variable is true in both before and after Update trigger, and in after update trigger changed the variable to false. So, if trigger will try to run second time in same request then it will not run.

Apex Class:

public Class RecursiveTriggerHelper{
   public static Boolean runOnce = true;
}

Apex Trigger:

trigger AccountTrigger on Account(before Update, after Update) {
    
    if(Trigger.isBefore && Trigger.isUpdate){
        
        if(RecursiveTriggerHelper.runOnce){
            //Write your logic here
            System.debug('Is Before Update');            
        }
    }
    
    if(Trigger.isAfter && Trigger.isUpdate){
        
        if(RecursiveTriggerHelper.runOnce){
            RecursiveTriggerHelper.runOnce = false;
            Set<String> accIdSet = new Set<String>();
            for(Account acc : Trigger.New){
                accIdSet.add(acc.Id);
            }
			//Write your logic here
            List<Account> accList = [SELECT Id, Name From Account Where Id IN : accIdSet];
            Update accList;
            System.debug('Is After Update');
        }
    }
}

Debug Log: