DEV Community

ApexCraft Studio
ApexCraft Studio

Posted on Edited on AI-assisted

Why Your 'Run Once' Trigger Guard Silently Skips Records

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';
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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');
    }
}
Enter fullscreen mode Exit fullscreen mode

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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 insert don't have Ids yet. Recursion almost always comes from an after-trigger updating the same records, so guard afterUpdate (and beforeUpdate if needed), not inserts.
  • Keep one set per event if a handler runs work in both beforeUpdate and afterUpdate, so one doesn't block the other. A Map<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
}
Enter fullscreen mode Exit fullscreen mode

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

  1. Search your org for static Boolean in trigger handlers. Each one is a candidate for this bug.
  2. Remove guards from handlers that don't run DML on the same object.
  3. React to field changes with Trigger.oldMap instead of every update.
  4. Where you still need a guard, track a Set<Id>, not a boolean.
  5. Test every trigger with 201+ records in a single DML statement.

Free: catch this bug in your own org

I packaged the fix and the test into a free Bulk-Test Kit: the Id-based RecursionGuard, a ChunkSimulator that reproduces 200-record trigger chunks in a unit test (no DML, no triggers), and a one-page checklist of trigger and test bugs. 12 tests, safe to deploy, free for commercial use.

Download the free Bulk-Test Kit →

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 (2)

Collapse
 
beusebiu profile image
Eusebiu Balan •

Had the mirror image of this in my points. Each habit check is its own row and was paid on its own, so deleting a check and adding it back paid twice.

The fix asks your question, keyed by the thing that matters: has this habit already paid today? If an earlier paid check exists for the same habit on the same day, the new one pays 0.

Collapse
 
apexcraftstudio profile image
ApexCraft Studio •

Great example, and a nice way to put it: the bug is the same whenever the guard is keyed to the wrong thing. Here it was “this row” instead of “this habit, this day”, just like “has the trigger run” instead of “has this record been handled”.

One edge case worth checking: if two checks for the same habit arrive at almost the same moment, both can look for an earlier paid check, find none, and both pay. Putting the rule in the data closes that gap. For example, a unique key on habit + date for paid checks, so the second insert fails instead of paying twice.

In payment APIs, this is the idea behind an idempotency key: a value representing the business event, so repeated requests are recognised as the same operation, regardless of how many times they arrive. I'm writing a follow-up post on applying this principle to Apex callouts.