Sub topic 14
Preventing unwanted recursion
This chapter assumes you can write a basic Apex trigger, use Trigger.new and Trigger.oldMap, and follow the handler class pattern from the previous chapters.
How recursion happens
A trigger runs again when its own work causes another save of the same object. Take an after update trigger on Opportunity that updates other Opportunity records, or a workflow field update that re-saves the record. The second save fires the trigger again inside the same transaction. Each pass uses SOQL queries and DML statements from the same pool of governor limits. Apex also stops the transaction if triggers nest more than 16 levels deep, so an uncontrolled loop ends in an error.
The diagram shows one transaction where a trigger fires itself a second time.
Why a static Set works
A static variable in Apex lives for the whole transaction. Each trigger invocation shares it, so the handler can record what it has already processed. A Set of record IDs is the safest choice.
public with sharing class OpportunityTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
public static List<Opportunity> filterUnprocessed(List<Opportunity> opps) {
List<Opportunity> toProcess = new List<Opportunity>();
for (Opportunity opp : opps) {
if (!processedIds.contains(opp.Id)) {
processedIds.add(opp.Id);
toProcess.add(opp);
}
}
return toProcess;
}
}Call filterUnprocessed at the top of the handler method, then work only on the list it returns. If the trigger re-fires with the same records, the returned list is empty and the handler does nothing.
Avoid the Boolean flag
A common first attempt is private static Boolean hasRun = false;. This breaks bulk behavior. A transaction can run a trigger more than once for different chunks of records. For example, a data load of 500 records reaches the trigger in batches of 200, 200, and 100. A Boolean set during the first chunk makes the handler skip the other 300 records.
The ID Set avoids this. Each chunk contains different IDs, so each chunk is processed once.
Limits of the pattern
- The guard skips a record for the rest of the transaction. If a legitimate second change to the same record needs handling, the guard hides it.
- It does not apply across transactions. Asynchronous work such as Queueable Apex runs in a new transaction with fresh static values.
- In
beforetriggers, records do not have IDs on insert. The guard only helps inaftertriggers or on update.
A narrower option is to track the specific change, not the record. Store the ID together with the value you reacted to, or compare Trigger.new with Trigger.oldMap. Then only a real change to the field triggers the work.
Common errors
| Symptom | Likely cause |
|---|---|
| "maximum trigger depth exceeded" | Two triggers or flows update each other's records with no guard |
| Only the first 200 records are processed in a large load | A static Boolean guard blocks later chunks |
| Guard never skips anything | The static variable is declared inside the method, so it resets each call |
Exercise
A data load inserts 400 Opportunities, and your handler uses a static Boolean hasRun to prevent recursion. Only some records get their follow-up tasks. Why, and what should you use instead?
Show answer
The load reaches the trigger in chunks of up to 200 records. The first chunk sets hasRun to true, so the second chunk is skipped entirely. Use a static Set<Id> and process only IDs that are not in the Set yet.