Sub topic 12
Preventing Trigger Recursion
This chapter assumes you can write Apex triggers and handler classes, and that you know the before and after trigger events, DML, and the per-transaction governor limits covered earlier in this tutorial.
Why recursion happens
A trigger can cause itself to run again. An after update trigger on Account might update Accounts. That DML fires the trigger a second time inside the same transaction. If the logic is not guarded, it fires a third time, and so on, until Salesforce stops the transaction.
Recursion also happens indirectly. A trigger on Account updates a Contact. A trigger on Contact updates the parent Account. The two triggers call each other in a loop.
Salesforce limits trigger nesting to a maximum stack depth of 16. Before it gets there, a recursive trigger usually runs into the SOQL query limit, the DML limit, or the CPU time limit. Every recursive pass spends from the same transaction budget.
Static variables last for one transaction
A static variable in Apex keeps its value for the whole transaction. Every trigger invocation in that transaction sees the same value. When the transaction ends, the value is discarded. This makes a static variable a good guard against re-entry.
The simplest guard is a Boolean flag in a helper class.
public class TriggerGuard {
public static Boolean hasRun = false;
}trigger AccountAfter on Account (after update) {
if (TriggerGuard.hasRun) {
return;
}
TriggerGuard.hasRun = true;
List<Account> toUpdate = new List<Account>();
for (Account a : Trigger.new) {
if (a.Rating == null) {
toUpdate.add(new Account(Id = a.Id, Rating = 'Warm'));
}
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}The second run, started by the update toUpdate statement, sees hasRun as true and returns immediately.
A weakness of the simple flag
The Boolean flag blocks every later run in the transaction, not only the recursive one. That causes problems in two common cases:
- A transaction updates more than 200 records. Salesforce processes them in chunks of 200, and each chunk fires the trigger. The flag set by the first chunk makes the trigger skip all the other chunks.
- A transaction legitimately updates different records in a second step, for example in a test or in a flow that runs after your code. Those records are silently skipped.
Skipped records are hard to debug because nothing fails. The data is just not processed.
Track record Ids instead
A safer guard stores the Ids of records already processed. The trigger then handles only records it has not seen.
public class TriggerGuard {
private static Set<Id> processedIds = new Set<Id>();
public static List<SObject> filterUnprocessed(List<SObject> records) {
List<SObject> fresh = new List<SObject>();
for (SObject record : records) {
if (!processedIds.contains(record.Id)) {
processedIds.add(record.Id);
fresh.add(record);
}
}
return fresh;
}
}trigger AccountAfter on Account (after update) {
List<Account> accounts =
(List<Account>) TriggerGuard.filterUnprocessed(Trigger.new);
if (accounts.isEmpty()) {
return;
}
List<Account> toUpdate = new List<Account>();
for (Account a : accounts) {
if (a.Rating == null) {
toUpdate.add(new Account(Id = a.Id, Rating = 'Warm'));
}
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}This version works with chunks of 200, because each chunk contains different Ids. It also stays bulk-safe: it uses one loop and one DML statement.
A trade-off remains. If a later update to the same record in the same transaction needs processing, the Id guard skips it. Choose the guard that matches your requirement.
Better: avoid the recursive update
A guard treats the symptom. Often you can remove the cause.
- Use a before trigger to change fields on the records in
Trigger.new. Changes made in a before trigger are saved without a new DML statement, so they do not fire the trigger again. - Update only when a value actually changes. Compare
Trigger.oldMapwithTrigger.newand skip records where the field of interest is the same. - Do not write to a record if the new value equals the current value.
trigger AccountBefore on Account (before update) {
for (Account a : Trigger.new) {
Account oldAccount = Trigger.oldMap.get(a.Id);
if (a.Rating == null && oldAccount.Rating != null) {
a.Rating = oldAccount.Rating;
}
}
}Common errors
| Symptom | Likely cause |
|---|---|
| Error: maximum trigger depth exceeded | The trigger updates records that fire it again, with no guard |
| Only the first 200 records are processed | A single Boolean flag skips later chunks |
| Records are not updated and no error appears | A guard flag stays set and blocks a legitimate second pass |
| Guard works in production but fails in a test | The test calls `Test.startTest()` and `Test.stopTest()`, and asynchronous code runs in a new transaction with fresh static values |
Exercise
A trigger on Opportunity uses one static Boolean flag to prevent recursion. A data load updates 600 Opportunities in one operation, and only the first 200 are processed. Why does this happen, and how would you fix it?
Show answer
Salesforce runs the trigger once for each chunk of up to 200 records, all in the same transaction. The first chunk sets the static flag to true, so the second and third chunks see the flag and return without doing any work. Fix it by storing the Ids of processed records in a static Set<Id> and handling only records whose Ids are not in the set. Where possible, also remove the recursive update by using a before trigger or by comparing Trigger.oldMap and acting only on real changes.