Sub topic 7
The static Boolean flag guard
This chapter assumes you can write a basic Apex trigger, you know insert and update DML, and you know what a static variable is in Apex. You should also know that triggers run inside a transaction with governor limits. Earlier chapters showed how a trigger can fire itself again. Here you add the first guard that stops it: a static Boolean flag.
The idea
A static variable in Apex belongs to the class, not to an instance. Its value lasts for the whole transaction. Every piece of code in that transaction sees the same value, including a trigger that fires a second time because of DML issued by the first run.
That gives a simple guard:
- Declare
private static Boolean hasRun = false;in a class. - At the start of the logic, return if
hasRunistrue. - Otherwise set
hasRun = trueand do the work.
The first run sets the flag and issues DML. That DML re-fires the trigger. The second run sees true and returns before it can issue more DML. The chain ends after one extra, harmless run.
The unguarded problem
Here is the trigger that causes the failure:
trigger AccountTrigger on Account (after update) {
List<Account> toUpdate = new List<Account>();
for (Account acc : Trigger.new) {
toUpdate.add(new Account(Id = acc.Id, Description = 'Reviewed'));
}
update toUpdate; // fires this trigger again, with no guard
}The update inside an after update trigger is itself an update on Account. It fires the trigger again, which runs another update, and so on. Salesforce stops the chain with a "maximum trigger depth exceeded" error and rolls back the transaction.
A guarded handler
Put the logic in a handler class so the flag has a clear home:
public class AccountTriggerHandler {
private static Boolean hasRun = false;
public static void afterUpdate(List<Account> newList) {
if (hasRun) {
return;
}
hasRun = true;
List<Account> toUpdate = new List<Account>();
for (Account acc : newList) {
toUpdate.add(new Account(Id = acc.Id, Description = 'Reviewed'));
}
update toUpdate;
}
}The trigger itself only routes to the handler:
trigger AccountTrigger on Account (after update) {
if (Trigger.isAfter && Trigger.isUpdate) {
AccountTriggerHandler.afterUpdate(Trigger.new);
}
}Handler classes are covered in more detail in a later chapter. For now, notice that the trigger holds no logic and the flag lives in one place.
What happens, step by step
The extra DML is not avoided. It still happens once, and the trigger still runs twice. The flag only prevents the third, fourth, and later runs.
Why a static variable and not an instance variable
Trigger code is invoked fresh on every run. If you stored the flag in an instance variable, each run would get a new object with hasRun = false, and the guard would never trigger. A static variable is stored once per transaction, so the second run sees what the first run wrote.
| Storage | Survives a re-fired trigger? | Works as a guard? |
|---|---|---|
| Local variable in the trigger | No, recreated each run | No |
| Instance variable on a new handler object | No, new object each run | No |
| Static variable on a class | Yes, lasts for the transaction | Yes |
Edge cases to know before you use it
Share one flag across contexts and you skip real work
A trigger often has several contexts, such as before update and after update. If both use the same flag, the before run sets it and the after run returns early without doing its work. Use one flag per context:
public class AccountTriggerHandler {
private static Boolean beforeUpdateRan = false;
private static Boolean afterUpdateRan = false;
public static void beforeUpdate(List<Account> newList) {
if (beforeUpdateRan) {
return;
}
beforeUpdateRan = true;
// before-update logic
}
public static void afterUpdate(List<Account> newList) {
if (afterUpdateRan) {
return;
}
afterUpdateRan = true;
// after-update logic
}
}The same applies across operations. Insert and update logic should not share a flag, because one transaction can insert a record and then update it.
The flag blocks every later run, not only the recursive one
The guard cannot tell the difference between "my own DML re-fired me" and "something else legitimately updated Accounts later in this transaction." Consider a flow or another trigger that updates a different set of Accounts after your handler ran. With the flag set, your logic skips those records. The flag treats every second entry as recursion.
It can skip records in bulk operations
This is the most important limit of the Boolean flag. When a single DML statement affects more than 200 records, Salesforce passes them to the trigger in chunks of up to 200. Each chunk is a separate trigger invocation in the same transaction. With a flag:
- Chunk 1 (records 1 to 200) runs and sets
hasRun = true. - Chunk 2 (record 201 onward) sees
trueand returns without being processed.
If you update 201 Accounts, the 201st never receives Description = 'Reviewed', and no error tells you so. The next chapter covers this problem in full and shows a fix. Until you have that fix, treat the Boolean flag as safe only when you know a transaction cannot touch more than 200 records of that object. That is rarely a safe assumption, because data loads, batch jobs, and integrations all send large sets.
Static state is not rolled back
If you catch an exception in the same transaction, or roll back to a savepoint, database changes are undone but static variable values are not. Suppose you set hasRun = true, your DML fails, you catch the exception, and the transaction continues. The flag stays true, so later calls skip the logic. Set the flag as late as is practical, or reset it in a finally block if you intend the logic to be retryable within the transaction.
Test methods start with fresh statics
Each test method runs in its own transaction, so statics start at their initial values in every method. Test.startTest() and Test.stopTest() give you a fresh set of governor limits but do not reset static variables. If your test needs the guard to be reset between steps, you need an explicit reset method, which is a reason to prefer the Set of Ids approach covered later.
Asynchronous work starts clean
Queueable, future, and batch jobs run in new transactions. Static variables start at their defaults there. A flag set in your trigger does not stop a queueable job from updating the same records and firing the trigger again with hasRun = false. The flag guards one transaction only.
Optional: expose the flag for deliberate re-entry
Sometimes you want the logic to run again on purpose. Add a reset method rather than making the field public:
public class AccountTriggerHandler {
private static Boolean hasRun = false;
@TestVisible
private static void resetGuard() {
hasRun = false;
}
public static void afterUpdate(List<Account> newList) {
if (hasRun) {
return;
}
hasRun = true;
// logic
}
}@TestVisible lets test classes call the method while keeping it private to production code. Resetting inside production code defeats the guard, so keep that to a deliberate and documented case.
Verifying the guard
A test should prove two things: no depth error occurs, and the work ran:
@IsTest
private class AccountTriggerHandlerTest {
@IsTest
static void updateRunsGuardedLogicWithoutDepthError() {
Account acc = new Account(Name = 'Test Account');
insert acc;
Test.startTest();
acc.Rating = 'Hot';
update acc;
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :acc.Id];
System.assertEquals('Reviewed', result.Description);
}
}This test uses one record. It passes with a Boolean flag but says nothing about the 200-record limit. Testing larger volumes is part of a later chapter.
Summary
- A static Boolean flag lasts for one transaction, so a re-fired trigger can read what the first run wrote.
- Set the flag after the check, then do the work. The re-fired run returns early.
- Use a separate flag for each trigger context and operation.
- The flag cannot distinguish recursion from legitimate later entry, and it is not undone by rollbacks.
- It skips records in chunks after the first 200, silently.
- It does not carry over into queueable, future, or batch transactions.
Exercise
A data loader updates 450 Account records in one DML statement. Your after update handler uses a single static Boolean hasRun. How many records does the handler process, and why?
Show answer
Only the first 200. Salesforce passes the 450 records to the trigger in chunks (200, 200, 50) within the same transaction. The first chunk sets hasRun = true. The second and third chunks see true and return early, so 250 records are skipped with no error.
Exercise
A trigger uses one static Boolean named hasRun shared by its before update and after update logic. The before logic runs first and sets the flag. What goes wrong, and how do you fix it?
Show answer
The after update logic sees hasRun = true and returns without running, even though it never ran before. Fix it by using a separate flag for each context, such as beforeUpdateRan and afterUpdateRan.