Sub topic 16
Recursion and re-entry guards
This chapter assumes you can write a basic Apex trigger, know DML (insert, update, delete), and know that workflow field updates can fire triggers again.
Why triggers run more than once
A save is one transaction, but the order of execution can run inside it more than once. Recursion happens when automation inside a transaction causes the same trigger to fire again for the same record.
A common cause is a workflow field update. If a workflow rule changes a field on a record that was updated, the before update and after update triggers fire once more. Your own code can cause it too. An after update trigger that updates the same object starts the cycle again.
Each pass uses the same governor limits. Unchecked recursion can exhaust them, and Salesforce stops a transaction whose triggers nest too deeply.
A static variable guard
Static variables in Apex live for the whole transaction. A static set of record Ids works as a re-entry guard. The trigger records which records it has handled and skips them on later passes.
public class TriggerGuard {
public static Set<Id> processed = new Set<Id>();
}
trigger AccountAfterUpdate on Account (after update) {
List<Account> toProcess = new List<Account>();
for (Account a : Trigger.new) {
if (!TriggerGuard.processed.contains(a.Id)) {
TriggerGuard.processed.add(a.Id);
toProcess.add(a);
}
}
// Work only with toProcess here
}The trigger tracks Ids, not a single Boolean. A Boolean flag such as hasRun would skip every record after the first batch. In a bulk operation of more than 200 records, Salesforce calls the trigger once per chunk of 200 inside one transaction. The flag would block the later chunks. A set of Ids handles each record once and still lets new records through.
Limits of the guard
The guard is simple, but it has trade-offs.
- It skips a record even if a later pass changed a field you care about. The second pass may need to run.
- It lasts for the transaction only. Separate transactions start with an empty set.
- Tests that run several operations in one context share the static state, so reset it between steps.
If the second pass matters when a specific field changes, compare values instead of blocking the record:
trigger AccountStatusChange on Account (after update) {
for (Account a : Trigger.new) {
Account old = Trigger.oldMap.get(a.Id);
if (a.Status__c != old.Status__c) {
// React only when Status__c actually changed
}
}
}This pattern ends the loop naturally. When the field stops changing, the logic stops running.
Exercise
A trigger uses a static Boolean hasRun to avoid recursion. A data load updates 600 Accounts in one transaction. What goes wrong, and what is the fix?
Show answer
The trigger runs in chunks of 200. The first chunk sets hasRun to true, so the second and third chunks are skipped. Replace the Boolean with a static Set<Id> and process only the records whose Ids are not yet in it.