Sub topic 8
Why a Boolean Flag Can Skip Records Beyond 200
This chapter assumes you can read the static Boolean guard from the previous chapter and know that Apex runs a trigger in a single transaction. You should also be comfortable with List and Trigger.new. Here you will see how that guard silently loses work when a single DML statement touches more than 200 records.
The guard that looks correct
Here is the handler from the previous chapter:
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;
}
}It stops the recursion. The update inside the handler fires the trigger again, and the second call returns at the first if. With 5 or 50 records, it also does everything you want.
The problem appears only with larger data volumes. That is why it often passes in development and fails in production.
How Salesforce chunks a bulk operation
When one DML statement affects many records, Salesforce does not hand all of them to your trigger at once. It splits them into chunks of up to 200 records and runs the trigger once per chunk. For a 450-record update, the trigger fires three times, with 200, 200, and 50 records in Trigger.new.
Two facts about chunking cause the pitfall:
- All chunks of one DML statement run in the same transaction. Governor limits are shared across them.
- Static variables live for the whole transaction. They are not reset between chunks.
Together, these mean a static flag set during chunk 1 is still true when chunk 2 starts.
You can see the chunks yourself by logging Trigger.size:
trigger AccountTrigger on Account (after update) {
System.debug('Trigger fired with ' + Trigger.size + ' records');
if (Trigger.isAfter && Trigger.isUpdate) {
AccountTriggerHandler.afterUpdate(Trigger.new);
}
}Run an update of 450 accounts from anonymous Apex and the debug log shows one line per chunk.
Where chunking applies
Chunking happens whenever a single DML operation covers more than 200 records. That includes:
- An Apex
updateorinserton a list of more than 200 records. - A DML statement inside a batch Apex
executemethod if the scope size is more than 200. - A trigger or process that updates more than 200 related records in one statement.
It does not apply in one common case. A Data Loader run or Bulk API job sends records in batches of up to 200, and each batch is its own transaction. Static variables reset between those batches. The flag bug therefore shows up most often with Apex code that handles large lists in one transaction, and it is hard to reproduce by loading a file.
Tracing the lost records
Take an Apex statement that updates 450 accounts. Here is the execution with the Boolean guard:
The guard did its job in the nested call, because it prevented recursion. It also blocked chunks 2 and 3, which are legitimate first-time calls. Records 201 to 450 never get Description = 'Reviewed'. No exception is thrown, no error appears in the log, and the DML succeeds. The only symptom is data that was never changed.
The table summarizes what happens per call:
| Call | Records in `Trigger.new` | `hasRun` on entry | Result |
|---|---|---|---|
| Chunk 1 | 200 | false | Processed |
| Nested call from chunk 1's `update` | 200 | true | Skipped (intended) |
| Chunk 2 | 200 | true | Skipped (bug) |
| Chunk 3 | 50 | true | Skipped (bug) |
Only the nested call should be skipped. A Boolean flag can't tell the nested call from the later chunks, because both look the same to it: the flag is true and a list of records arrives.
Reproducing the bug in a test
A test that uses 5 records will pass with this guard. You need more than 200 records, so use 250:
@IsTest
private class AccountBulkChunkTest {
@IsTest
static void bulkUpdateProcessesEveryChunk() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 250; i++) {
accounts.add(new Account(Name = 'Bulk Account ' + i));
}
insert accounts;
Test.startTest();
for (Account acc : accounts) {
acc.Rating = 'Hot';
}
update accounts;
Test.stopTest();
Integer reviewed = [
SELECT COUNT() FROM Account WHERE Description = 'Reviewed'
];
System.assertEquals(250, reviewed, 'Every chunk should be processed');
}
}With the Boolean guard, the assertion fails. The count is 200, because only chunk 1 ran. When you replace the guard with a correct one, the same test passes. That makes it a good regression test for any guard you write.
The test relies on the trigger from the previous chapters, which routes after update to AccountTriggerHandler.afterUpdate. The insert does not fire that trigger, so only the update is counted.
Why the usual fixes don't work
Some quick fixes look reasonable but don't solve the problem:
- Resetting the flag at the end of the handler. If you set
hasRun = falseafter theupdatestatement returns, the nested call is still blocked, because the flag is true while the nested call runs. But chunk 2 then runs with the flag false, and its ownupdatefires another nested call. Each chunk then handles its own recursion, which works in this case. The danger is that the nested call is guarded only because it runs before the reset. If the handler has logic after the DML, or if any other code path triggers an update later, the flag no longer protects you. The flag also does not track which records have been handled, so a record changed in a later step can be reprocessed. - Checking
Trigger.sizeagainst 200. This ties your correctness to a platform chunk size and does not identify which records were handled. - Using
System.isBatch()orSystem.isFuture()to skip the guard. These tell you the execution context. They do not tell you whether you are in a nested call or a later chunk.
The underlying issue is that the flag records "the handler ran" for the whole transaction, but what you need to know is "this particular record was handled."
What the fix has to do
A correct guard has to meet three requirements:
- Stop the nested call from reprocessing records that were just handled.
- Allow later chunks to process records that have not been seen yet.
- Keep working when more than one chunk exists in one transaction.
Requirements 1 and 2 both depend on knowing which records have been handled. A Boolean can only say yes or no for everything. A collection keyed by record Id can answer per record, which is the approach the next chapter takes with a static Set<Id>.
Summary of the failure mode
- Salesforce splits a DML statement into chunks of up to 200 records, and all chunks run in one transaction.
- Static variables keep their values across chunks.
- A static Boolean set in chunk 1 makes every later chunk return early.
- The result is silent data loss for records beyond the first 200.
- Tests must use at least 201 records to expose it.
Exercise
An Apex method updates 600 Account records in a single update statement. The handler uses a static Boolean hasRun guard as shown in this chapter. How many times does the trigger fire, how many records are processed by the handler's logic, and why?
Show answer
The trigger fires for three chunks of 200 records. Chunk 1 also causes a nested trigger call from the handler's own update, so the trigger fires four times in total, assuming the handler's update of 200 records fits in one chunk. Only chunk 1 runs the handler logic, so 200 of the 600 records are processed. The flag is set to true in chunk 1 and static variables persist across chunks in the same transaction, so the nested call and chunks 2 and 3 all return early. The other 400 records are silently skipped.
Exercise
A developer tests a Boolean flag guard with 10 accounts and it passes. Describe a test that would expose the bug, and say what the assertion would show.
Show answer
Insert 250 accounts, update them all in one update statement inside Test.startTest() and Test.stopTest(), then count the accounts whose Description is Reviewed. The assertion expects 250, but with the Boolean flag the count is 200, because the second chunk of 50 records is skipped.