Sub topic 14
Preventing unwanted recursion
This chapter assumes you can write a handler-based trigger, query and update records in bulk, and compare Trigger.new with Trigger.oldMap. It covers how a trigger ends up running itself, how static variables guard against that, and where those guards cause bugs.
How recursion happens
A trigger is recursive when its own work causes the same trigger to fire again inside the same transaction. These are the usual causes:
- An
aftertrigger runs DML on the same object. The new update fires theafter updatetrigger again. - A trigger updates a record, and a workflow field update, flow, or process on that object changes it a second time. Salesforce then re-fires the update triggers once more.
- Two objects have triggers that update each other, such as Account updating Contact and Contact updating Account.
Here is the simplest case:
trigger OpportunityRecursion on Opportunity (after update) {
List<Opportunity> toUpdate = new List<Opportunity>();
for (Opportunity o : Trigger.new) {
toUpdate.add(new Opportunity(Id = o.Id, Description = 'Reviewed'));
}
update toUpdate; // fires this trigger again
}Each update fires the trigger again. The nesting stops when Salesforce reaches its maximum trigger depth of 16 and throws a System.DmlException that reads "maximum trigger depth exceeded". You may hit a different limit first. Every pass consumes DML statements and CPU time from the same transaction budget.
Remove the cause first
A guard is the last resort. Check whether the recursion can be designed away.
If a trigger only changes fields on the records that are firing it, use a before trigger. Edits to Trigger.new in a before context are saved without another DML statement, so nothing re-fires.
trigger OpportunityRecursion on Opportunity (before update) {
for (Opportunity o : Trigger.new) {
o.Description = 'Reviewed';
}
}An after trigger is needed when you must write to related records or use the record Id on insert. In that case, make the work idempotent. Compare old and new values, as in the previous chapter on detecting changes, and act only when the relevant field changed. On the second pass the field has not changed again, so the trigger does nothing.
public static void markReviewed(List<Opportunity> newOpps, Map<Id, Opportunity> oldMap) {
List<Opportunity> toUpdate = new List<Opportunity>();
for (Opportunity o : newOpps) {
Boolean stageChanged = oldMap != null
&& o.StageName != oldMap.get(o.Id).StageName;
if (stageChanged) {
toUpdate.add(new Opportunity(Id = o.Id, Description = 'Stage changed'));
}
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}The second pass sees an unchanged StageName and stops. This approach is self-limiting and has no hidden state. Use it whenever a single field decides whether work is needed.
Static variables as guards
When no field reliably tells you whether work is done, record it in memory. A static variable in an Apex class keeps its value for the whole transaction. Every trigger invocation in that transaction sees the same value, including nested ones. The value is lost when the transaction ends.
flowchart TD
A[Opportunity after update fires] --> B{Id already in processedIds?}
B -- No --> C[Add Id to processedIds]
C --> D[Run logic and update records]
D --> E[Trigger fires again for same records]
E --> B
B -- Yes --> F[Skip record]I'll render this in the required format below, then show the code.
The handler keeps a Set<Id> and filters each batch against it:
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;
}
}The trigger passes its batch through the filter before doing any work:
trigger OpportunityTrigger on Opportunity (after update) {
List<Opportunity> fresh =
OpportunityTriggerHandler.filterUnprocessed(Trigger.new);
if (!fresh.isEmpty()) {
// handler logic using only 'fresh'
}
}Both the filter and the work stay bulk-safe. The guard is one loop over a collection, with no queries and no DML.
Why a Boolean flag is the wrong guard
Many examples online use a single flag:
public static Boolean hasRun = false;The trigger runs once, sets hasRun = true, and skips every later invocation. This breaks in two ways.
- Batches larger than 200. A bulk operation on 500 records is split into chunks of 200, 200, and 100. Each chunk invokes the trigger separately, in the same transaction. A Boolean flag lets the first chunk through and silently skips the other 300 records. A Set of IDs treats each chunk correctly, because the later chunks contain different IDs.
- Legitimate second changes. If a workflow field update changes a value after your trigger has run, a Boolean flag hides that change from your logic.
An Id set fixes the first problem. The second is covered in the next section.
Gotchas with Id-based guards
The Set records that you saw an Id. It does not record that the record is in its final state. Consider this sequence in one transaction:
- A user updates an Opportunity to
Closed Won. Your trigger runs and its Id goes into the Set. - A flow on Opportunity then changes
Amount. The update triggers fire again. - Your guard skips the record, even though your logic might need the new
Amount.
You have three ways to handle this:
- Track Ids per rule, with a separate Set for each piece of logic, so unrelated logic is not blocked.
- Store the field value you acted on, for example a
Map<Id, String>of Id to stage, and skip only when the value is unchanged. This combines the Set approach with change detection. - Accept the skip, if the logic really should run only once per record per transaction.
Other behaviours to keep in mind:
- Asynchronous work starts a new transaction. A Queueable job or
@futuremethod sees a fresh set of static variables. A trigger that enqueues a job which updates the same records can still loop, through separate transactions. Guard the enqueue condition with a field change. - Each test method is its own transaction. Static state is not carried between test methods.
Test.startTest()andTest.stopTest()do not reset it either. - Static state is per transaction, not per user or per org. Do not use it to enforce rules between transactions. That needs a field on the record.
Testing the guard
Test the filter directly, and test the trigger with a real DML operation that exercises the re-entry path.
@IsTest
private class OpportunityRecursionTest {
@IsTest
static void filterReturnsEachRecordOnce() {
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 5; i++) {
opps.add(new Opportunity(
Name = 'Guard ' + i,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
));
}
insert opps;
List<Opportunity> first = OpportunityTriggerHandler.filterUnprocessed(opps);
List<Opportunity> second = OpportunityTriggerHandler.filterUnprocessed(opps);
System.assertEquals(5, first.size(), 'First pass should include every record');
System.assertEquals(0, second.size(), 'Second pass should skip every record');
}
}Add a test that updates 200 or more records with your real trigger active. Then assert that the expected side effects occurred once per record, for example one Task each. If the guard is wrong, that test shows duplicates or missing records. If recursion is not controlled, it throws the depth error.
Choosing an approach
| Situation | Preferred approach |
|---|---|
| Changing fields on the triggering records | `before` trigger, no DML needed |
| Work depends on one field changing | Compare `Trigger.new` with `Trigger.oldMap` |
| Work must run once per record per transaction | Static `Set<Id>` guard |
| Work depends on the last value processed | Static `Map<Id, value>` guard |
| Looping through separate transactions | Field-based condition on the enqueue |
Exercise
A trigger on Contact uses private static Boolean hasRun = false;. A data load updates 450 Contacts in one DML statement. What happens, and how should the guard change?
Show answer
Salesforce splits the 450 records into chunks of 200, 200, and 50, and invokes the trigger once per chunk in the same transaction. The first chunk sets hasRun = true, so the second and third chunks (250 records) are skipped with no error. Replace the Boolean with a static Set<Id> of processed record IDs and filter each chunk against it, so every chunk is processed once. Where possible, also compare old and new field values so the logic is naturally idempotent.
Exercise
Why does a before update trigger that edits fields on Trigger.new not need a recursion guard, while an after update trigger that runs update on the same records does?
Show answer
Changes made to Trigger.new in a before context are saved as part of the original operation, with no new DML statement, so no further trigger invocation occurs. An after trigger must issue its own update, which starts a new save of the same records. That save fires the after update trigger again, until a guard stops it or the trigger depth limit of 16 is exceeded.