Sub topic 9
Guarding against repeated trigger execution
This chapter assumes you can read Apex, you know the handler pattern from the earlier chapters (a logic-less trigger calling a handler that dispatches on Trigger.operationType), and you know the basics of governor limits and DML. It covers why a trigger can fire again inside the same transaction, how to stop that with static state, and where static state fails.
Why triggers run more than once
A transaction is one unit of work, from the first DML statement or request until the commit or rollback. A trigger does not run only once per transaction. It runs once per DML statement on its object, and the handler's own DML counts.
Consider an after update handler on Account that updates Accounts again. Each update fires the trigger, the trigger calls the handler, and the handler issues another update. Salesforce stops this at a trigger depth of 16 and throws Maximum trigger depth exceeded. The whole transaction rolls back.
Other things also cause repeat execution:
- A handler on one object updates a second object, and that object's trigger updates the first. This is an indirect loop through two triggers.
- A workflow field update on the object makes the before and after update triggers fire one more time in the same transaction.
- A record save in a Flow or process can update the same record again.
- Salesforce splits a DML statement of more than 200 records into chunks of 200 and runs the trigger once per chunk.
The last case is not a loop, but it matters for how you design the guard. We come back to it below.
An unguarded handler
This handler produces the loop. It reacts to every after update event by writing to the same Account.
public with sharing class AccountTriggerHandler {
public void run() {
switch on Trigger.operationType {
when AFTER_UPDATE {
afterUpdate((List<Account>) Trigger.new);
}
when else {
// Other operations are not handled yet.
}
}
}
private void afterUpdate(List<Account> newAccounts) {
List<Account> toUpdate = new List<Account>();
for (Account acc : newAccounts) {
toUpdate.add(new Account(Id = acc.Id, Description = 'Synced'));
}
update toUpdate; // fires the trigger again, which runs afterUpdate again
}
}The handler is bulk-safe, with one DML statement outside the loop, but it is not safe against itself.
The static Set guard
A static variable in Apex lives for the whole transaction, no matter how many times the trigger runs. This makes it a good place to remember which records the handler has already processed. A Set<Id> fits well because Set.add returns false when the value is already present, so the check and the bookkeeping happen in one call.
public with sharing class AccountTriggerHandler {
@TestVisible
private static Integer processedCount = 0;
private static Set<Id> processedIds = new Set<Id>();
public void run() {
switch on Trigger.operationType {
when AFTER_UPDATE {
afterUpdate((List<Account>) Trigger.new);
}
when else {
// Other operations are not handled yet.
}
}
}
private void afterUpdate(List<Account> newAccounts) {
List<Account> toUpdate = new List<Account>();
for (Account acc : newAccounts) {
// Set.add returns false when the Id was already in the set.
if (processedIds.add(acc.Id)) {
processedCount++;
toUpdate.add(new Account(Id = acc.Id, Description = 'Synced'));
}
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}
}Here is what happens when a user updates one Account:
- The first
after updatepass adds the Id toprocessedIds, soaddreturnstrue. The handler queues the record and updates it. - The update fires the trigger a second time.
addreturnsfalse, sotoUpdatestays empty and the handler skips the DML. - The recursion ends after one extra pass, with no exception.
The guard does the check per record, not per call. If the second pass contains records the handler has not seen, it processes those and skips only the known ones.
Why not a Boolean flag
Many examples online use a single static Boolean hasRun. It is simple and it has two flaws.
First, it blocks legitimate work. A transaction that updates 201 Accounts in one DML statement runs the trigger twice, once for 200 records and once for 1. A flag set during the first chunk makes the handler skip the second chunk, so one record is never processed. This is a data bug that tests with small data do not reveal.
Second, it blocks any later, unrelated update on the same object in the transaction. Imagine a Flow that updates a different set of Accounts after the first save. The flag treats it as a repeat.
| Guard | Skips repeats of the same record | Processes other records in later passes | Handles chunks of 200 correctly |
|---|---|---|---|
| `static Boolean` flag | Yes | No | No |
| `static Set<Id>` | Yes | Yes | Yes |
| Change check on a field | Only if the field stops changing | Yes | Yes |
Choosing what to track
An Id set answers "have I touched this record in this transaction?" Sometimes the better question is "has this record changed in the way I care about?" Comparing old and new values is a guard that needs no static state:
private void afterUpdate(List<Account> newAccounts, Map<Id, Account> oldMap) {
List<Account> renamed = new List<Account>();
for (Account acc : newAccounts) {
if (acc.Name != oldMap.get(acc.Id).Name) {
renamed.add(acc);
}
}
// Work on renamed only.
}If the handler's own DML does not change Name, the second pass finds nothing to do and the loop ends by itself. This is the more precise guard when you can use it, because it also skips needless work on ordinary updates. It fails when the handler's DML changes the very field it watches, for example when it writes back a normalized name. Then each pass sees a change and the loop continues.
The two approaches combine well. Use the change check to decide what is relevant, and use the Id set to guarantee that a record is processed at most once.
Limits of the Id set
An Id guard is simple, so its trade-offs are easy to miss.
- Before triggers. On
before insert, records have no Id yet, soacc.Idisnull. Do not use Id tracking there. Before triggers rarely recurse, because they change records in memory and issue no DML. - Second legitimate update. If a record is updated twice in a transaction, and the second update changes data the handler should react to, the guard skips it. If this matters, key the set on a value that includes the state, such as a string made from the Id and the field value, or clear the entry when the relevant field changes.
- Scope of the state. Static variables are reset between transactions, so a guard never leaks across users or requests. Within one test method, all DML shares one transaction, so a second update on the same record in a test can be skipped. Reset the state or use a fresh record when you test this.
- Per class, not per object. The set lives in one handler class. Two handlers that call each other through different objects each need their own guard, or a shared one in the base class (a later chapter).
Testing the guard
Test two things: that the work runs exactly once, and that the transaction does not fail with a depth error. The @TestVisible counter in the handler lets the test observe how many records were processed.
@IsTest
private class AccountTriggerHandlerRecursionTest {
@IsTest
static void afterUpdateProcessesEachRecordOnce() {
Account acc = new Account(Name = 'Original');
insert acc;
Test.startTest();
acc.Name = 'Renamed';
update acc;
Test.stopTest();
Account saved = [SELECT Description FROM Account WHERE Id = :acc.Id];
Assert.areEqual('Synced', saved.Description);
Assert.areEqual(1, AccountTriggerHandler.processedCount,
'The record should be processed once, not again by its own update');
}
}If you remove the processedIds.add check from the handler, this test fails with a Maximum trigger depth exceeded exception. That failure shows the test covers the guard.
You can also test the chunk case by updating 201 Accounts in one statement and asserting that processedCount is 201. This is the test that would catch a Boolean flag.
Summary of the decision
- Make the handler do as much as possible in
beforeevents, where no extra DML is needed. - In
afterevents that must issue DML on the same object, filter to the records that actually changed. - Add a
static Set<Id>to guarantee each record is processed at most once per transaction. - Avoid a global static Boolean unless you are sure the transaction never touches more than 200 records or more than one batch of work.
Exercise
A handler uses private static Boolean hasRun = false;. It returns early if hasRun is true and sets it to true on its first pass. A data load updates 450 Accounts in one DML statement. How many records does the handler process, and why?
Show answer
It processes only the first 200. Salesforce runs the trigger once per chunk of 200 records (200, 200, 50) within the same transaction. The first chunk sets the flag, and the other two chunks return early, so 250 records are skipped. A static Set<Id> fixes this because the Ids in later chunks are not yet in the set.
Exercise
An after update handler writes a normalized value back to the same Name field it watches for changes, and it uses only a "has the Name changed" check as its guard. Why can this still recurse, and what do you add?
Show answer
Each pass changes Name through the handler's own update, so the next pass sees a difference between old and new values and runs again. Adding a static Set<Id> guard makes the handler process each Id once, which stops the loop. You can also compare the new value against the normalized form and skip records that are already normalized.