Sub topic 14
Preventing Recursive Trigger Execution
This chapter assumes you can write a basic Apex trigger, read Trigger.new and Trigger.oldMap, and know that a trigger receives up to 200 records per invocation. You should also know what governor limits are. The chapter shows how a trigger ends up running itself, how to stop it, and where the common stopping techniques fail.
How recursion happens
A trigger recurses when its own DML fires the same trigger again. This is the usual chain:
- An
after updatetrigger on Account runs. - The trigger updates Accounts, either the same records or others.
- That update fires the
after updatetrigger on Account again. - The second run does the same thing, and the loop continues.
Indirect recursion is harder to spot. An Account trigger updates Contacts, and a Contact trigger updates the parent Account. Neither trigger calls itself, but together they loop.
Salesforce stops runaway loops with a trigger stack depth limit. If a chain nests too deeply, the transaction fails with a "maximum trigger depth exceeded" error. The loop usually exhausts the SOQL or DML limits before that. Either way the user sees a failed save.
First defense: design the trigger so it converges
A guard is a patch. Start by making the trigger stop on its own:
- Use a
beforetrigger when you only change fields on the records being saved. Changes toTrigger.neware saved without DML, so nothing re-fires. - Act only when a field changed. Compare
Trigger.oldMapwith the new value, as in the earlier chapter on detecting changes. If your update sets a field to a value that fails the change check on the next pass, the loop ends. - Skip DML when the value is already correct. Build the update list only from records that need it.
Use a guard when these are not enough, for example when the update is unconditional or two objects update each other.
The static Boolean guard and its flaw
A static variable keeps its value for the whole transaction. That makes it a natural run-once flag:
public class TriggerGuard {
private static Boolean hasRun = false;
public static Boolean shouldRun() {
if (hasRun) {
return false;
}
hasRun = true;
return true;
}
}This works for a single record. It fails with bulk data.
A trigger fires once per chunk of up to 200 records, and all chunks of one DML statement belong to the same transaction. Suppose a data load updates 450 Accounts. The trigger runs for records 1 to 200 and sets hasRun to true. It then returns early for records 201 to 400 and 401 to 450. Those 250 records are silently skipped, with no error and no log entry.
Better guard: track processed record Ids
Track which records the trigger has handled instead of whether it has run. The guard then skips only records it has already processed:
public class AccountRecursionGuard {
private static Set<Id> processedIds = new Set<Id>();
public static List<Account> unprocessed(List<Account> accounts) {
List<Account> result = new List<Account>();
for (Account a : accounts) {
// Set.add returns true only if the Id was not already in the set.
if (processedIds.add(a.Id)) {
result.add(a);
}
}
return result;
}
}The trigger asks the guard which records are new to it:
trigger AccountRecursionTrigger on Account (after update) {
List<Account> toProcess = AccountRecursionGuard.unprocessed(Trigger.new);
if (toProcess.isEmpty()) {
return;
}
List<Account> updates = new List<Account>();
for (Account a : toProcess) {
updates.add(new Account(
Id = a.Id,
Description = 'Updated by trigger'
));
}
update updates;
}Here is the sequence for 250 records, with no recursion and no skipped chunk:
On the first pass, records 1 to 200 are new, so they are processed and updated. That update re-fires the trigger with the same 200 Ids. The guard filters out all of them and the trigger returns. The platform then delivers records 201 to 250, which are new Ids, so they are processed normally.
You can verify the bulk behavior in a test:
@isTest
private class AccountRecursionTriggerTest {
@isTest
static void allChunksAreProcessed() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 250; i++) {
accounts.add(new Account(Name = 'Account ' + i, Rating = 'Cold'));
}
insert accounts;
for (Account a : accounts) {
a.Rating = 'Hot';
}
Test.startTest();
update accounts;
Test.stopTest();
Integer updated = [
SELECT COUNT()
FROM Account
WHERE Id IN :accounts AND Description = 'Updated by trigger'
];
System.assertEquals(250, updated, 'Every chunk should be processed');
}
}If you replace the guard with the static Boolean, this test fails with a count of 200. That makes it a useful regression test.
Guarding per event
One guard set covers one trigger context. If the same trigger handles before update and after update, a shared set causes trouble. The before run adds the Ids, and the after run then sees them as already processed and skips them.
Keep a separate set for each event you guard. A map keyed by System.TriggerOperation does this:
public class RecursionGuard {
private static Map<System.TriggerOperation, Set<Id>> seen =
new Map<System.TriggerOperation, Set<Id>>();
public static Boolean firstTime(System.TriggerOperation op, Id recordId) {
if (!seen.containsKey(op)) {
seen.put(op, new Set<Id>());
}
return seen.get(op).add(recordId);
}
}Inside a trigger you call RecursionGuard.firstTime(Trigger.operationType, a.Id) for each record and skip the ones that return false.
Where Id-based guards go wrong
An Id guard assumes a record should be processed once per transaction. That is not always true.
- Legitimate second pass. Workflow field updates can cause
before updateandafter updatetriggers to run a second time in the same transaction. If your logic must see the values that the workflow wrote, the guard blocks that second run. In that case, guard on the specific field change instead of on the Id. - Insert has no Id in
before.Trigger.newrecords inbefore inserthave a null Id, so an Id set cannot track them. Guardbefore insertlogic by design, not by Id, or move it toafter insert. - Stale values. A guard keyed only by Id ignores later edits within the same transaction. If another process changes the record after your first pass, your trigger does not re-evaluate it.
- Shared state in tests. Statics last for the whole test method, so one test method that runs several scenarios may find Ids already marked. Run separate scenarios in separate test methods, or add a reset method on the guard that only tests call.
A common compromise is to key the guard on the Id plus the value that matters, for example storing a Map<Id, String> of the last processed Rating. The trigger then reprocesses a record only when the relevant value differs from the one it last handled.
Choosing a technique
| Situation | Technique |
|---|---|
| Only changing fields on the saved records | `before` trigger, no DML |
| Update is conditional on a field change | Compare `Trigger.oldMap` to `Trigger.new` |
| Unconditional DML on the same object | Id-based static guard |
| Two objects update each other | Id-based guard on each side, or redesign the data flow |
| One flag for a whole transaction | Avoid. It skips later chunks |
Exercise
A data load updates 600 Accounts. An after update trigger uses a single static Boolean hasRun to avoid recursion. Roughly how many records does the trigger body process, and what fix keeps the recursion protection without the loss?
Show answer
The trigger body processes only the first chunk of 200 records. The platform delivers the other 400 records in later chunks of the same transaction, and hasRun is already true, so the trigger returns early for them without any error. The fix is to track processed record Ids in a static Set<Id>, using Set.add to filter the records so each Id is handled once. Records re-fired by the trigger's own DML are skipped, and records from later chunks are new Ids, so they are processed.
Exercise
Why can an Id-based guard not protect logic in a before insert trigger?
Show answer
Records in Trigger.new during before insert have not been saved yet, so their Id is null. A set of Ids cannot tell them apart. Use a design that does not depend on the Id, or move the logic to after insert, where the Ids exist.