Sub topic 18
Recursion and re-entry guards
This chapter assumes you can write a basic Apex trigger, know what DML is, and have read the earlier chapters on before and after triggers and on workflow field updates. Here you will learn why a trigger can run more than once in one transaction, and how to stop it from repeating work.
Why triggers run again
A single save does not always mean a single trigger run. Several things can cause the same object's triggers to fire again inside the same transaction:
- A workflow field update changes a field on the record. Salesforce then re-fires the before update and after update triggers once more.
- Your own trigger runs DML on the same object, for example updating other Account records.
- A record-triggered flow updates the record or a related record, which fires that object's triggers.
- A trigger on a child object updates its parent, and the parent's trigger updates the child.
Each re-entry is a new trigger invocation, but it is in the same transaction. Governor limits are shared, and so are static variables.
Why this is a problem
Re-entry is harmless when your logic is idempotent, meaning that running it twice gives the same result as running it once. It becomes a problem when the logic is not. Common failures include:
- Creating duplicate child records, such as two follow-up Tasks for one Account.
- Sending duplicate emails.
- Looping until you hit a limit, such as "Maximum trigger depth exceeded" or too many SOQL queries.
- Adding to a number on every pass, such as incrementing a counter.
The static variable guard
A static variable in Apex lives for the whole transaction. A class holds the guard, and the trigger checks it. This is the pattern from the topic's code example:
public class TriggerGuard {
public static Set<Id> processed = new Set<Id>();
}
trigger AccountAfterUpdate on Account (after update) {
List<Account> toProcess = new List<Account>();
for (Account a : Trigger.new) {
if (!TriggerGuard.processed.contains(a.Id)) {
TriggerGuard.processed.add(a.Id);
toProcess.add(a);
}
}
// Work only with toProcess here
}The guard stores record Ids, not a single true/false flag. The next section explains why that matters.
Why a Set of Ids and not a Boolean
A Boolean flag such as hasRun = true is the most common version of this guard, and it has a flaw. Salesforce processes large saves in batches of up to 200 records. A data load of 500 records runs the trigger three times in the same transaction. A Boolean set during the first batch of 200 would cause the trigger to skip the remaining 300 records entirely.
A Set of Ids avoids this. Each record is handled once, and records in later chunks are still processed because their Ids are not in the Set yet.
The limit of an Id-based guard
The Id guard has its own gap. If a record is legitimately changed a second time in the same transaction, for instance by a workflow field update that sets a value your logic needs, the guard skips it. Your logic never sees the final value.
You can fix this by recording what you processed, not only that you processed it. Compare the current value with the value stored at the time of the first pass:
public class StatusGuard {
// Maps record Id to the Status value already handled
public static Map<Id, String> handledStatus = new Map<Id, String>();
}
trigger OpportunityStatusSync on Opportunity (after update) {
List<Opportunity> toProcess = new List<Opportunity>();
for (Opportunity o : Trigger.new) {
String previous = StatusGuard.handledStatus.get(o.Id);
if (previous == null || previous != o.StageName) {
StatusGuard.handledStatus.put(o.Id, o.StageName);
toProcess.add(o);
}
}
// Work only with toProcess here
}This version runs again only when StageName differs from the last handled value. That also stops infinite loops, because a record that stops changing stops re-triggering.
Alternatives to a static guard
A guard is a patch. Where you can, make the logic safe by design.
- Compare old and new values. In an update trigger,
Trigger.oldMapholds the previous values. Run logic only when a field of interest has changed. - Make the operation idempotent. Use
upsertwith an external Id instead ofinsert, so a second run updates instead of duplicating. - Avoid DML on the same object from its own trigger. In a before trigger, change
Trigger.newdirectly, which needs no DML and no re-entry. - Move field updates into before-save flows or before triggers. Same-record changes made there do not cause a second trigger run.
The first option is often the cleanest:
trigger AccountRatingChange on Account (after update) {
List<Task> tasks = new List<Task>();
for (Account a : Trigger.new) {
Account oldAcc = Trigger.oldMap.get(a.Id);
if (a.Rating != oldAcc.Rating) {
tasks.add(new Task(Subject = 'Rating changed', WhatId = a.Id));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}If a workflow field update re-fires the trigger and Rating has not changed since the previous pass, no second Task is created. Salesforce supplies Trigger.oldMap on each pass.
Gotchas
- Statics reset between transactions. The guard protects only within one transaction. A new save starts with an empty Set.
- A rollback does not reset statics. If you catch an error and the transaction continues after a partial rollback, the guard still remembers records that were rolled back. Use
Database.setSavepoint()andDatabase.rollback()with care, and clear the guard if you roll back. - Tests share statics inside a test method. If one test method performs two saves in the same context, the second save may be skipped by the guard. Reset the static at the start of each logical step.
- Guards hide bugs. A guard that silently skips work can make a trigger look fine while a record is left in the wrong state. Log skipped records while debugging.
- Trigger depth is limited. Triggers that fire each other in a chain stop with an error at a depth of 16.
Choosing an approach
| Approach | Best when | Weakness |
|---|---|---|
| Compare `Trigger.oldMap` values | Logic depends on a field change | Does not help if the logic must run on every save |
| Static Set of Ids | Work must happen once per record per transaction | Misses later legitimate changes |
| Static Map of Id to value | Work must run again only when a value changes | More code to maintain |
| Idempotent operation (upsert) | Repeating the work is safe | Needs a suitable key |
Exercise
A trigger uses a static Boolean alreadyRun. It is set to true on the first run. A data load of 450 Accounts saves successfully, but only the first 200 get the expected change. Why, and what is the fix?
Show answer
Salesforce runs the trigger in chunks of up to 200 records within the same transaction. The first chunk sets alreadyRun to true, so the second and third chunks (250 records) are skipped. Replace the Boolean with a static Set<Id> of processed record Ids, or compare Trigger.oldMap and Trigger.new so the logic runs only for records whose relevant field changed.
Exercise
A workflow field update causes your after update trigger to run twice for the same Account, and you create two Tasks. Name two ways to prevent the duplicate.
Show answer
Compare Trigger.oldMap with Trigger.new and create the Task only when the field of interest changed, or keep a static Set<Id> of processed Account Ids and skip those already in it. Either approach lets the second pass do nothing.