Sub topic 9
Guarding against repeated trigger execution
This chapter assumes you can read basic Apex, know the DML operations (insert, update, delete, undelete), and have met governor limits. You should also know the one-trigger-per-object handler from the earlier chapters.
Why triggers run more than once
A trigger can cause its own re-execution. An after update trigger on Account might update a related record, and a workflow field update, a flow, or another trigger might then update the same Account. That second update fires the Account trigger again, inside the same transaction.
Each pass costs SOQL queries and DML statements against the same governor limits. A loop of repeated passes can hit those limits, or it can produce duplicate side effects such as two follow-up Tasks for one Account.
The diagram shows the cycle.
Static state lasts for the transaction
Apex static variables keep their values for the whole transaction. A trigger firing a second time sees the same static values as the first pass. This makes a static field a good place to remember which records you have already handled.
A static Boolean such as hasRun is the simplest guard, but it is too coarse. If a transaction updates 400 records, Salesforce runs the trigger in two batches of 200. A Boolean set during the first batch would make the handler skip the second batch. A Set of record Ids avoids this.
A guard based on a Set of Ids
public with sharing class AccountTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
private void afterUpdate(List<Account> newAccounts) {
List<Account> toProcess = new List<Account>();
for (Account acc : newAccounts) {
// Set.add returns false when the Id was already in the set.
if (processedIds.add(acc.Id)) {
toProcess.add(acc);
}
}
// Work on toProcess only.
}
}Set.add returns true when the value was new and false when it was already present. The if therefore does two jobs: it records the Id and it filters out records seen before.
The handler works only on toProcess. Each record passes through the logic once per transaction, and the rest of the batch continues normally.
Common errors
- Using one Boolean for the whole class. It skips legitimate records in later batches of 200, so some records are silently never processed.
- Putting the guard in the trigger file. The trigger should stay logic-less. Keep the static state in the handler.
- Guarding every event the same way. Before-context logic usually edits
Trigger.newin memory and does not cause re-entry. Add guards where you do DML on the same object, typically in after-context methods. - Skipping real changes. An Id guard blocks a record even when a later update changes it in a way you care about. If your logic must react to a second, different change, compare field values against
Trigger.oldMapinstead of relying only on the Id. - Expecting state to survive between transactions. Static values reset when the transaction ends, so the guard never carries over to the next save.
Choosing between guard styles
| Guard | Handles batches of 200 | Reacts to later changes | Best use |
|---|---|---|---|
| Static Boolean | No | No | Rarely suitable |
| Static Set of Ids | Yes | No | Run logic once per record |
| Compare with `Trigger.oldMap` | Yes | Yes | Run logic only when a field changed |
Exercise
A transaction updates 400 Accounts. Your handler uses a static Boolean hasRun as its recursion guard. What goes wrong, and what replaces it?
Show answer
Salesforce runs the trigger in batches of 200. The first batch sets hasRun to true, so the second batch of 200 Accounts is skipped. Replace the Boolean with a static Set<Id> and use processedIds.add(acc.Id) to filter records, so each Account is processed once and every batch is still handled.
Exercise
Why should a guard not be applied to a before update method that only sets Description on Trigger.new records?
Show answer
Changes to Trigger.new in a before trigger happen in memory and do not cause a new DML statement, so the trigger does not fire again. A guard there adds no protection and risks skipping records that need the change.