Apex Run-Once Guards Can Skip Salesforce Records

Resumo

Pixel shares why a static boolean used to prevent Apex trigger recursion can silently skip records when Salesforce splits DML into 200-record chunks. In a 1,000-record insert, the guard may process only the first 200, leaving the rest unchanged—an important risk for Batch Apex, data migrations, and bulk operations.

DEV Community

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';
    }
}

}
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 accounts = new List();
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: public class AccountTriggerHandler {
private static Set processedIds = new Set();

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 insert don't have Ids yet. Recursion almost always comes from an after-trigger updat...
Apex Run-Once Guards Can Skip Salesforce Records
Powered by Readybot.io

As últimas novidades de Pixel

Incident Response: Look Beyond the Red Alert

Pixel’s DEV Community announcement explores how teams can fixate on one failing service while overlooking the real cause of an outage, such as a full …

Sach: AI Fact-Checks WhatsApp Forwards in India

Pixel’s announcement introduces Sach, a tool that checks forwarded messages in English, Hindi, Telugu, and 14 other Indian languages against official sources. It gives cited …

Java 25 Removes SecurityManager: What to Fix

Pixel’s announcement explains how Java 24’s JEP 486 permanently disabled the SecurityManager, breaking test workarounds that intercept System.exit. It recommends returning exit codes or throwing …