Sub topic 11
Bypass switches for deliberate re-entry
This chapter assumes you can write an Apex trigger that delegates to a handler class. It also assumes you know the guards from earlier chapters: the static Boolean flag, the static Set<Id>, and changed-field checks. Here you learn the opposite problem. Sometimes you want a trigger to run again, or you want it to stay out of the way for one operation.
Why guards sometimes get in the way
A recursion guard is blunt. It says "this logic runs once per record per transaction" and never asks why the trigger fired. Several legitimate situations break that assumption:
- Your own code updates records and the trigger should not react. An internal repair routine fixes a field on Accounts, and the Account logic would only add noise or consume governor limits.
- A second pass is needed. The first run changes a field, and that change means the logic must evaluate the record again.
- Tests need a clean setup. Test data creation should not run the full trigger logic every time.
- Data loads and migrations. An administrator loads thousands of historical records and the business rules should not apply.
A bypass switch is a flag that the handler checks before doing any work. The caller sets it on purpose. This is different from a recursion guard, which sets itself automatically.
A minimal bypass class
Keep the switch in one small class so every handler uses the same mechanism. It stores handler names in a static Set<String>. As you saw earlier, static state lasts for one transaction, so the switch cannot leak into the next request.
public class TriggerBypass {
private static Set<String> bypassed = new Set<String>();
public static void bypass(String handlerName) {
bypassed.add(handlerName);
}
public static void clearBypass(String handlerName) {
bypassed.remove(handlerName);
}
public static void clearAll() {
bypassed.clear();
}
public static Boolean isBypassed(String handlerName) {
return bypassed.contains(handlerName);
}
}Using a set of names instead of one Boolean lets you switch off one handler without disabling every trigger in the org.
Checking the switch in the handler
The handler checks the switch first, before it looks at the Id set or any field values. This is the handler from the earlier chapters with one added line.
public class AccountTriggerHandler {
public static final String NAME = 'AccountTriggerHandler';
private static Set<Id> processedIds = new Set<Id>();
public static void afterUpdate(List<Account> newList) {
if (TriggerBypass.isBypassed(NAME)) {
return;
}
List<Account> toUpdate = new List<Account>();
for (Account acc : newList) {
if (processedIds.contains(acc.Id)) {
continue;
}
processedIds.add(acc.Id);
toUpdate.add(new Account(Id = acc.Id, Description = 'Reviewed'));
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}
}The trigger itself does not change. It still only routes to the handler, so the bypass logic stays in one place.
Setting the switch safely with try and finally
The most common bypass bug is forgetting to turn the switch off. If the caller bypasses the handler and an exception is thrown before the clear call, the handler stays disabled for the rest of the transaction. If the exception is caught higher up, later code silently skips the logic.
Always pair the two calls with try and finally:
public class AccountRepairService {
public static void fixDescriptions(List<Account> accounts) {
for (Account acc : accounts) {
acc.Description = 'Repaired';
}
TriggerBypass.bypass(AccountTriggerHandler.NAME);
try {
update accounts;
} finally {
TriggerBypass.clearBypass(AccountTriggerHandler.NAME);
}
}
}The finally block runs whether the update succeeds or throws. The bypass window covers only the one DML statement, which keeps it as small as possible.
Deliberate re-entry: running a record twice on purpose
A bypass skips the logic. Deliberate re-entry is the reverse: the guard blocks a second run, and you want to allow it. With a Set<Id> guard, you do this by removing specific Ids from the set. You never clear the whole set, because that reopens the recursion loop for every record.
public class AccountTriggerHandler {
public static final String NAME = 'AccountTriggerHandler';
private static Set<Id> processedIds = new Set<Id>();
public static void allowReentry(Set<Id> recordIds) {
processedIds.removeAll(recordIds);
}
public static void afterUpdate(List<Account> newList) {
if (TriggerBypass.isBypassed(NAME)) {
return;
}
List<Account> toUpdate = new List<Account>();
for (Account acc : newList) {
if (processedIds.contains(acc.Id)) {
continue;
}
processedIds.add(acc.Id);
toUpdate.add(new Account(Id = acc.Id, Description = 'Reviewed'));
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}
}A caller that has changed a record and needs the trigger to evaluate it again calls AccountTriggerHandler.allowReentry(idSet) just before its DML. Pair this with a changed-field check, so the second run does real work only when something relevant changed. Without that check you can create a loop that ends only at the platform's trigger depth limit.
Persistent switches for admins and data loads
A static switch exists only inside one transaction. It works for code calling code. It does nothing for a person running a Data Loader job, because that person cannot run Apex in the same transaction as the load.
For that case, use a setting that persists and that you can check at runtime. A custom permission is a good fit because you can grant it to a user or permission set without a deployment. FeatureManagement.checkPermission returns whether the running user has it.
public class TriggerBypass {
private static Set<String> bypassed = new Set<String>();
public static void bypass(String handlerName) {
bypassed.add(handlerName);
}
public static void clearBypass(String handlerName) {
bypassed.remove(handlerName);
}
public static Boolean isBypassed(String handlerName) {
if (bypassed.contains(handlerName)) {
return true;
}
return FeatureManagement.checkPermission('Bypass_Account_Trigger');
}
}This assumes you have created a custom permission with the API name Bypass_Account_Trigger. The two sources behave differently:
| Source | Scope | Set by | Typical use |
|---|---|---|---|
| Static `Set<String>` | One transaction | Apex code | Internal repair code, test setup |
| Custom permission | Every transaction run by that user | An administrator | Data loads, migrations, integration users |
Treat the custom permission as a sensitive privilege. Anyone who holds it skips your business rules, including validation you wrote in the trigger. Grant it to named users for a limited time, not to a broad profile.
Bypass switches and asynchronous work
Static variables reset when a Queueable, @future method, or batch job starts, because each runs in its own transaction. A bypass set before you enqueue the job does not carry into it. If the asynchronous code updates records and the trigger should skip them, the job must set the bypass itself, again with try and finally. A custom permission check does carry across, but it evaluates the user the job runs as, which may differ from the user who started it.
Testing the switch
Test both directions: the logic runs by default, and it does not run while the switch is set. Clear the switch in a finally block here too. Static state persists for the whole test method, including across Test.startTest() and Test.stopTest().
@IsTest
private class TriggerBypassTest {
@IsTest
static void bypassedHandlerSkipsLogic() {
Account acc = new Account(Name = 'Test Account');
insert acc;
TriggerBypass.bypass(AccountTriggerHandler.NAME);
try {
acc.Rating = 'Hot';
update acc;
} finally {
TriggerBypass.clearBypass(AccountTriggerHandler.NAME);
}
Account skipped = [SELECT Description FROM Account WHERE Id = :acc.Id];
System.assertNotEquals('Reviewed', skipped.Description);
acc.Rating = 'Warm';
update acc;
Account ran = [SELECT Description FROM Account WHERE Id = :acc.Id];
System.assertEquals('Reviewed', ran.Description);
}
}The first update runs with the handler bypassed, so the description stays unchanged. After the switch is cleared, the second update runs the guarded logic as normal.
Common errors
- Forgetting to clear. Use
finally, every time. - Bypassing too widely. Name the specific handler, not a global "disable all triggers" flag. A global flag hides bugs in unrelated features.
- Clearing the whole Id set to allow re-entry. This turns a targeted retry into the original recursion problem.
- Assuming the switch crosses transactions. Static state does not survive into Queueable, future, or batch code.
- Leaving bypass code in production paths with no owner. Each caller that sets a bypass is a place where business rules do not apply. Search for
TriggerBypass.bypassduring code review.
Exercise
An Apex service method sets TriggerBypass.bypass('AccountTriggerHandler'), updates a list of Accounts, then calls TriggerBypass.clearBypass('AccountTriggerHandler'), all without a try/finally. The update throws a DmlException that a caller higher in the stack catches. What is wrong with the next lines of code in the same transaction, and how do you fix it?
Show answer
The exception skips the clearBypass call, so the handler stays bypassed. Any later Account DML in the same transaction silently skips the handler logic, because the caught exception does not roll back static variables. Fix it by wrapping the update in try and putting TriggerBypass.clearBypass('AccountTriggerHandler') in the finally block, so the switch is cleared whether the DML succeeds or fails.
Exercise
Why is a static Set<String> bypass not enough to stop trigger logic during a Data Loader import, and what mechanism can you add?
Show answer
Static variables exist only inside one Apex transaction, and a Data Loader job runs no Apex of yours to set them before the records are saved. Add a persistent check such as a custom permission read with FeatureManagement.checkPermission in TriggerBypass.isBypassed, and grant that permission to the user running the load for as long as needed.