If your trigger handler uses a static boolean to "run once", it is probably skipping records in production, and nothing tells you. No error, no failed test, just records that never got processed.
The pattern everyone copies
Search for "Apex trigger recursion" and you'll find this in almost every tutorial:
public class AccountTriggerHandler {
private static Boolean hasRun = false;
public static void beforeInsert(List<Account> accounts) {
if (hasRun) {
return;
}
hasRun = true;
for (Account acc : accounts) {
acc.Description = 'Processed';
}
}
}
The idea is sound: if the trigger updates records and that update fires the trigger again, stop the loop. The static variable lives for the whole transaction, so the second run sees hasRun = true and exits.
The problem is that "the second run" isn't always recursion.
What actually happens: 200-record chunks
Salesforce never hands a trigger more than 200 records at once. When a single DML statement touches more than 200 records, the platform splits them into chunks of 200 and runs your trigger once per chunk, all inside the same transaction.
So when Apex inserts 1,000 Accounts in one statement:
| Chunk | Records |
hasRun before |
What happens |
|---|---|---|---|
| 1 | 1–200 | false | Processed, then hasRun = true
|
| 2 | 201–400 | true | Skipped |
| 3 | 401–600 | true | Skipped |
| 4 | 601–800 | true | Skipped |
| 5 | 801–1,000 | true | Skipped |
Static variables survive across chunks because it's one transaction. The guard can't tell "the same trigger firing again because of recursion" from "the next 200 records". 800 of the 1,000 Accounts never get their Description set, and the insert still succeeds.
This bites hardest in exactly the places nobody watches:
-
Batch Apex with a scope above 200, e.g.
Database.executeBatch(job, 2000) - Data migration scripts run from Anonymous Apex
- Service classes that build a list and insert or update it in one call
- Flows that create or update many records in one element
Everyday testing in the UI saves one record at a time, so it never shows up there.
Reproduce it in one test
You only need 201 records to see the bug: one full chunk plus one.
@IsTest
private class AccountTriggerHandler_Test {
@IsTest
static void processesEveryRecordInBulk() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 201; i++) {
accounts.add(new Account(Name = 'Bulk ' + i));
}
Test.startTest();
insert accounts; // one DML statement, two chunks
Test.stopTest();
Integer processed = [
SELECT COUNT() FROM Account WHERE Description = 'Processed'
];
Assert.areEqual(201, processed, 'Every record should be processed');
}
}
With the hasRun guard, this fails with expected 201, actual 200. Record 201 is skipped.
If your handler tests only insert one or five records, they pass, and the bug ships. Always test triggers with more than 200 records.
The fix: track record Ids, not a boolean
The real question isn't "has this trigger run?" It's "has this record already been handled?" Answer that with a Set<Id>:
public class AccountTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
public static void afterUpdate(List<Account> accounts) {
List<Account> toProcess = new List<Account>();
for (Account acc : accounts) {
// Set.add returns false if the Id was already there
if (processedIds.add(acc.Id)) {
toProcess.add(acc);
}
}
if (toProcess.isEmpty()) {
return;
}
// ... work on toProcess only
}
}
Now chunk 2 brings 200 new Ids, so they all get processed. A true recursive update brings back Ids that are already in the set, so they're skipped. The guard finally does what it was meant to do.
A few details matter:
-
Use it in update contexts. Records in
before insertdon't have Ids yet. Recursion almost always comes from an after-trigger updating the same records, so guardafterUpdate(andbeforeUpdateif needed), not inserts. -
Keep one set per event if a handler runs work in both
beforeUpdateandafterUpdate, so one doesn't block the other. AMap<String, Set<Id>>keyed by the trigger operation handles this. - Know the trade-off. A record updated twice in one transaction on purpose, e.g. by two different processes, is only handled once. That's usually what you want, but be aware of it. The same goes for partial-success saves (Database.update(records, false), Data Loader, the API): when some records fail, Salesforce retries the rest without resetting static variables, so the set skips them. For logic that's safe to repeat, the next section's approach avoids this entirely.
Even better: only act on records that changed
Often you don't need a recursion guard at all. Most recursion happens because a handler reacts to every update, including the one it just made itself. Compare against Trigger.oldMap and react only to the change you care about:
public static void afterUpdate(List<Account> accounts, Map<Id, Account> oldMap) {
List<Account> ratingChanged = new List<Account>();
for (Account acc : accounts) {
if (acc.Rating != oldMap.get(acc.Id).Rating) {
ratingChanged.add(acc);
}
}
// ... work on ratingChanged only
}
If your own follow-up update doesn't change Rating again, the second run finds nothing to do and stops by itself.
The same goes for the beforeInsert example at the top. A before-insert handler that only sets fields on Trigger.new can't cause recursion, because it doesn't run any DML. It needs no guard at all. Delete the hasRun check and all 201 records pass the test.
Checklist for your triggers
- Search your org for
static Booleanin trigger handlers. Each one is a candidate for this bug. - Remove guards from handlers that don't run DML on the same object.
- React to field changes with
Trigger.oldMapinstead of every update. - Where you still need a guard, track a
Set<Id>, not a boolean. - Test every trigger with 201+ records in a single DML statement.
Want this already built?
The ApexCraft Apex + LWC Starter Kit includes a trigger framework with this Id-based guard built in, plus a bypass API, an admin on/off switch, service and selector layers, a rollback-safe logger and six Lightning Web Components. It deploys in one command, with 68 Apex tests and 45 Jest tests included.
Get the Starter Kit → ($19 launch price until December 16)
Either way, go check your handlers for that static Boolean.
Follow-up: 7 bugs that passed 100+ tests in my Salesforce starter kit covers the retry trap and six more.
Top comments (0)