Sub topic 13
Choosing the right strategy
This chapter helps you pick a recursion-prevention technique for a given trigger. It assumes you can read Apex triggers and handler classes, and that you know the earlier techniques from this tutorial: before-trigger field updates, changed-field checks, the static Boolean flag, and the static Set<Id>. It also assumes you know that static variables last for one transaction.
Start with the cause, not the guard
A recursion guard hides a symptom. Before choosing one, ask why the trigger runs again. There are three common answers:
- Your trigger issues DML on the same object it fires on, so it re-fires itself.
- A workflow field update changes the record after your trigger ran, so Salesforce fires the before and after triggers one more time.
- Two objects update each other, so trigger A fires trigger B, which fires trigger A.
Each cause has a cheapest fix. Work through the options in the order below and stop at the first one that fits.
The decision order
- Remove the DML. If the trigger only changes the records that fired it, use a
beforetrigger and assign toTrigger.newdirectly. No DML statement runs, so nothing re-fires. - Filter by changed values. If the logic only matters when specific fields change, compare
Trigger.newwithTrigger.oldMapand skip the rest. - Track processed records. If the logic must run for each record at most once per transaction, keep a static
Set<Id>. - Use a Boolean flag only for once-per-transaction work. This fits work that is not per record, and you should use it deliberately.
- Add a bypass switch. If some code paths must re-enter the trigger on purpose, give the handler a way to turn the guard off.
Comparing the options
| Strategy | Stops recursion by | Handles 200+ record chunks | Main risk |
|---|---|---|---|
| Before trigger, no DML | Never issuing DML | Yes | Only works for the triggering records, and you cannot use it for related records |
| Changed-field check | Skipping records with no relevant change | Yes | Misses cases where a different field change should also matter |
| Static `Set<Id>` | Skipping Ids already handled | Yes | Skips a record that legitimately changes again in the same transaction |
| Static Boolean flag | Returning early after the first run | No, it skips later chunks | Silent data loss in bulk operations |
| Bypass switch | Letting callers disable the guard or the logic | Not applicable | Someone forgets to reset it |
The first two rows prevent recursion without any shared state. Prefer them whenever they fit, because state that lives across trigger invocations is the usual source of hard-to-reproduce bugs.
Why the Boolean flag ranks low
Salesforce processes a bulk operation on more than 200 records in chunks of up to 200, and all chunks run in one transaction. A static Boolean set during the first chunk is still true when the second chunk arrives. The handler returns early and the remaining records are never processed. The failure is silent: no exception, no log, and the bug only appears with large data loads.
The flag is correct in a narrow case. Use it when the work is genuinely once per transaction and does not depend on which records arrive. Examples are sending one summary notification, or writing a single audit record. If you can describe the work as "for each record," use the Set<Id> instead.
The Set of Ids and its trade-off
The Set<Id> guard handles chunking correctly, because each chunk adds only its own Ids. Its weakness is that it treats "seen once" as "done forever" for the rest of the transaction.
Consider a record that your trigger handles, and then a workflow field update changes another field that your logic also depends on. The second pass is skipped, because the Id is already in the set. If that second change matters, the set is the wrong tool. Combine it with a changed-field check, or key the guard on something narrower than the Id.
A common refinement is to store the Id together with the value you care about, for example a Map<Id, String> of Id to the Rating you processed. The record is skipped only if you already handled that same value.
Combining techniques in a handler
In practice, the guards layer. The handler below skips records whose Rating did not change, skips Ids already processed, and has a bypass switch for code that needs to re-enter on purpose.
public class AccountTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
public static Boolean bypass = false;
public static void afterUpdate(List<Account> newList, Map<Id, Account> oldMap) {
if (bypass) {
return;
}
List<Account> toUpdate = new List<Account>();
for (Account acc : newList) {
Account oldAcc = oldMap.get(acc.Id);
if (acc.Rating == oldAcc.Rating) {
continue;
}
if (processedIds.contains(acc.Id)) {
continue;
}
processedIds.add(acc.Id);
toUpdate.add(new Account(Id = acc.Id, Description = 'Reviewed'));
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}
}trigger AccountTrigger on Account (after update) {
if (Trigger.isAfter && Trigger.isUpdate) {
AccountTriggerHandler.afterUpdate(Trigger.new, Trigger.oldMap);
}
}The update re-fires the trigger. On that second run the Rating has not changed, so the changed-field check skips every record before the Id set is even consulted. The set is a second layer: if something else changes the Rating again in the same transaction, the record is still processed only once.
Bypass switches
A bypass switch is a public static flag, or a custom setting or custom permission, that the handler checks first. Use it when a caller needs the trigger logic off, such as a data migration, or a utility that updates the same records and handles the follow-up itself.
Keep these rules:
- Set the switch in a
tryblock and reset it infinally, so an exception cannot leave the logic disabled for the rest of the transaction. - Do not use a bypass to cover for a recursion bug. It is for deliberate re-entry only.
- If the switch is a static variable, it only affects the current transaction. A custom setting persists and affects every user, so use one with care.
AccountTriggerHandler.bypass = true;
try {
update accountsToFix;
} finally {
AccountTriggerHandler.bypass = false;
}Async boundaries reset your guards
Static variables live for one transaction. A @future method, a Queueable, and each batch execute call all start a new transaction, so static guards start empty there. This has two consequences.
First, a static guard cannot stop a loop that crosses a transaction boundary. Suppose a trigger enqueues a Queueable, and the Queueable updates the same records. The update fires the trigger in a new transaction, with fresh statics, and the trigger enqueues the job again. The loop continues until a limit stops it. The fix is a data-based condition, such as a changed-field check or a status field on the record, because that state is stored in the database and survives the boundary.
Second, you can detect the context. System.isFuture(), System.isQueueable(), and System.isBatch() return true inside those contexts, and a handler can use them to skip enqueuing more async work.
Common mistakes when choosing
- Reaching for the Boolean flag first. It is the simplest guard to write and the one most likely to skip records in bulk.
- Using an
aftertrigger to change the triggering record. This forces a DML statement and a re-fire. Abeforetrigger does the same job with none. - Guarding by Id when the logic depends on a value. The record is skipped even when the relevant field changes a second time.
- Leaving a bypass on. A missing
finallyturns off business logic for the remainder of the transaction. - Not testing with more than 200 records. Chunking bugs only show up with bulk data, so a test with one record proves nothing about them.
Exercise
Exercise
An after-update trigger on Opportunity creates one Task per Opportunity whose StageName changed, and then updates a field on the same Opportunity records. Users load 1,000 Opportunities with Data Loader. A teammate proposes a static Boolean hasRun. Which strategy would you choose instead, and why?
Show answer
Use a changed-field check on StageName, optionally combined with a static Set<Id> of processed Opportunity Ids. The Boolean flag would be set during the first chunk of 200, so the remaining 800 records would be skipped with no error. The changed-field check also stops the re-fire caused by the field update, because StageName is not changed in that second run. If the extra field update only touches the triggering records, moving it into a before trigger would remove the DML and the re-fire altogether.
Exercise
A trigger enqueues a Queueable that updates the same Account records. A static Boolean guard in the handler does not stop the loop. Why not, and what do you use instead?
Show answer
The Queueable runs in a new transaction, so static variables are reset and the guard is empty each time. Use state that persists in the database, such as a changed-field check or a status field on the record that the trigger tests before enqueuing the job.