Sub topic 12
Preventing trigger recursion
This chapter assumes you can read Apex triggers and handler classes, and that you know bulkified patterns with Sets, Maps and Lists. It also assumes you know that Trigger.new and Trigger.oldMap hold up to 200 records per chunk. Here you will learn why triggers re-fire themselves, what Salesforce does when they loop, and how to stop the loop without breaking bulk processing.
Why triggers call themselves
A trigger recurses when its own work causes the same trigger to run again in the same transaction. The usual causes are:
- An
after updatetrigger runs DML on the same object, such as updating the records inTrigger.newto set a field. - Two triggers update each other's objects. An Account trigger updates Contacts, and a Contact trigger updates the Account.
- A workflow field update or a record-triggered flow changes the record. Salesforce then fires the update triggers again for that record.
- A trigger updates a parent record, and a roll-up or other automation on the parent updates the child.
Here is the simplest case:
trigger AccountAfterUpdate on Account (after update) {
List<Account> toUpdate = new List<Account>();
for (Account a : Trigger.new) {
toUpdate.add(new Account(Id = a.Id, Description = 'Touched ' + System.now()));
}
// Anti-pattern: this update fires AccountAfterUpdate again
update toUpdate;
}This code is bulkified. It uses one DML statement for any number of records. It is still broken, because each update re-fires the trigger, which runs another update.
What the platform does about it
Salesforce limits trigger nesting. If triggers call each other in a chain deeper than 16 levels, the transaction fails with Maximum trigger depth exceeded. The whole transaction rolls back, including the user's original save.
The platform often reaches another limit before the depth limit. Each level of recursion uses DML statements, SOQL queries, CPU time and DML rows from the same transaction budget. A recursive trigger can therefore fail with a Too many DML statements or CPU time error instead.
The block above is a placeholder and is not part of the chapter. The real diagram follows.
Static variables as transaction memory
Apex has no built-in "has this trigger already run?" check. The standard tool is a static variable. A static variable is initialized once per transaction. It keeps its value across every trigger invocation and every recursive call in that transaction. It resets when the transaction ends, so the next user save starts fresh.
A static variable only works as a guard if it lives in a class, because a trigger body cannot declare one. This is another reason to use a handler class (see the earlier chapter on trigger structure).
Approach 1: a Boolean flag, and why it is risky
public class AccountTriggerHandler {
private static Boolean hasRun = false;
public static void afterUpdate(List<Account> newList) {
if (hasRun) {
return;
}
hasRun = true;
// ... work and DML ...
}
}This is the version most tutorials show, and it has two problems.
- Chunking. When one DML statement or API call touches more than 200 records, Salesforce runs the trigger once per chunk of 200. All chunks share one transaction and one set of static variables. With a Boolean flag, the first chunk sets
hasRun = trueand chunks 2, 3 and so on are silently skipped. A test with 200 records passes and production with 1,000 records quietly misses 800 of them. - Lost updates. If another process legitimately changes a record later in the same transaction, the flag blocks the trigger. The change is ignored.
> Use a Boolean flag only when you can prove the transaction never has more than one chunk and never needs a second pass. In practice, avoid it.
Approach 2: track processed record Ids
A Set<Id> fixes the chunking problem. Each record is processed once, and a new chunk contains new Ids, so it is not skipped.
public class AccountTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
public static void afterUpdate(List<Account> newList, Map<Id, Account> oldMap) {
List<Account> toUpdate = new List<Account>();
for (Account a : newList) {
if (processedIds.contains(a.Id)) {
continue;
}
Account oldAccount = oldMap.get(a.Id);
if (a.Rating != oldAccount.Rating) {
processedIds.add(a.Id);
toUpdate.add(new Account(
Id = a.Id,
Description = 'Rating changed to ' + a.Rating
));
}
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}
}trigger AccountAfterUpdate on Account (after update) {
if (Trigger.isAfter && Trigger.isUpdate) {
AccountTriggerHandler.afterUpdate(Trigger.new, Trigger.oldMap);
}
}The handler adds an Id to the set only when it acts on that record. The trigger fires a second time because of the Description update. On that pass Rating has not changed and the Id is in the set, so no DML runs and the recursion ends.
The Set guard has one limitation. It blocks every further change to that record in the same transaction, including legitimate ones. A flow or another trigger may change Rating again later in the transaction, and your handler will ignore it. Decide whether "once per record per transaction" matches your business rule.
Approach 3: act only on real changes
The most robust guard is to check whether the field you care about actually changed. The handler above already does this with a.Rating != oldAccount.Rating. When this check is the only guard, the second pass exits because nothing relevant changed. No static state is needed.
This approach also handles later legitimate changes. If Rating changes again, the handler runs again, which is usually what you want. The risk is two triggers that keep changing each other's watched fields back and forth. That loop never settles, and only the depth limit stops it.
The three approaches compare as follows:
| Approach | Safe with more than 200 records | Allows a later legitimate change | Needs static state |
|---|---|---|---|
| Boolean flag | No | No | Yes |
| `Set<Id>` of processed records | Yes | No | Yes |
| Compare old and new values | Yes | Yes | No |
A common production choice is to combine them. Check for a real change first, then use a Set<Id> as a safety net.
Approach 0: avoid the DML entirely
Most recursion bugs come from updating the triggering records in an after trigger. In a before trigger, Trigger.new records are still writable. You can assign fields directly and Salesforce saves them without a second DML statement.
trigger AccountBeforeUpdate on Account (before update) {
for (Account a : Trigger.new) {
Account oldAccount = Trigger.oldMap.get(a.Id);
if (a.Rating != oldAccount.Rating) {
a.Description = 'Rating changed to ' + a.Rating;
}
}
}This version uses no DML, no query, and no recursion. Prefer it whenever the field you set is on the same record that fired the trigger. Keep after triggers for work that needs the record Id on insert, or for changes to other objects.
Recursion across several objects
Cross-object loops are harder to see. An Account trigger updates its Contacts, and a Contact trigger updates the parent Account. A static guard in each handler can break the loop, but the guards must use the right keys:
- Track Ids per object, in the handler for that object.
- Do not share one
Set<Id>between handlers for different objects. Ids are unique across objects, but a shared set makes it harder to reason about which handler has already acted. - Make each handler act only when a field it owns has changed. This is better than blocking everything.
Declarative automation counts as well. If a record-triggered flow updates the same record, Apex triggers fire again after the flow. Your static state persists through that second pass, because it is still the same transaction. Use that to your advantage by testing the guard together with the flow active.
Testing the guard
Test two things: that the trigger does not recurse, and that it works for a full chunk.
@IsTest
private class AccountTriggerHandlerTest {
@IsTest
static void updatesDescriptionOnceForEveryAccount() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Recursion ' + i, Rating = 'Cold'));
}
insert accounts;
for (Account a : accounts) {
a.Rating = 'Hot';
}
Test.startTest();
update accounts;
Integer dmlUsed = Limits.getDmlStatements();
Test.stopTest();
System.assertEquals(
200,
[SELECT COUNT() FROM Account
WHERE Description = 'Rating changed to Hot']
);
System.assert(dmlUsed <= 2,
'Expected one test update and one handler update, got ' + dmlUsed);
}
@IsTest
static void secondChangeInSameTransactionIsSkipped() {
Account acc = new Account(Name = 'Guard demo', Rating = 'Cold');
insert acc;
Test.startTest();
acc.Rating = 'Hot';
update acc;
acc.Rating = 'Warm';
update acc;
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :acc.Id];
System.assertEquals('Rating changed to Hot', result.Description);
}
}The second test documents the limitation of the Set<Id> guard. Both updates run in the same test transaction, so the second change to Rating is ignored. If your rule requires the handler to react to every change, rely on the old/new comparison and drop the Set.
Edge cases to keep in mind
- Governor limits are shared. A guard that stops recursion after one extra pass still costs that second pass. Keep the early exit cheap and put it before any query.
- Partial success. With
Database.update(records, false), failed records may be retried in later chunks or passes. Only add an Id to the processed set when the work is actually attempted, as the handler does. - Async work. Queueable, Batch and
@futuremethods run in a new transaction with fresh static variables. A guard does not carry across them. A trigger that enqueues a Queueable which updates the same records can loop across transactions, and only a data-based check (an old/new comparison or a status field) can break that loop. - Order of execution. Triggers, flows and validation rules run in a fixed order, and "after save" automation can cause a second trigger pass. Use debug logs to see how many times your handler runs.
Summary of the decision
- If you can set the field in a
beforetrigger, do that and remove the DML. - Otherwise, compare old and new values and act only on real changes.
- Add a
Set<Id>of processed records when you need a hard stop per record. - Avoid a plain Boolean flag.
- Test with 200 records and check the DML count.
Exercise
A developer adds private static Boolean hasRun = false; to a handler, sets it to true on the first call, and returns early on later calls. The test with 5 records passes. After deployment, a data load of 1,000 Accounts leaves most records unprocessed. Explain why, and give a fix.
Show answer
Salesforce runs the trigger once per chunk of 200 records, and all chunks share one transaction and its static variables. The first chunk sets hasRun to true, so the remaining chunks (records 201 to 1,000) return early without any work. The fix is to track processed record Ids in a static Set<Id> and skip only Ids already in it, or to compare Trigger.oldMap to Trigger.new and act only on records whose watched field changed.
Exercise
An after update trigger on Contact copies Email into a custom field Email_Copy__c on the same Contact using update. Rewrite the approach so that no recursion is possible and no DML is needed.
Show answer
Move the logic to a before update trigger and assign the field directly on each record in Trigger.new, for example c.Email_Copy__c = c.Email;. Records in Trigger.new are writable in a before trigger and are saved without an extra DML statement, so the trigger does not fire a second time.
Exercise
Why does the Set<Id> guard in this chapter cause the second update in secondChangeInSameTransactionIsSkipped to be ignored, and what would you change if the business rule needs every rating change handled?
Show answer
After the first update the handler adds the Account Id to processedIds, and static state persists for the whole transaction. On the second update the Id is already in the set, so the handler skips it even though Rating changed again. To handle every change, remove the Set and rely on the old/new value comparison alone, which stops the recursive pass because Rating does not change in it.