Sub topic 3
Tracking Processed Records with a Static Set of Ids
Assume you know basic Apex collections, triggers, DML, and governor limits. A static Set<Id> guard records which database records the handler has already processed during the current transaction. Unlike a single Boolean, it allows later bulk chunks to run.
Track each record
public class AccountTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
public static void afterUpdate(List<Account> newList) {
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;
}
}
}If the update statement fires the trigger again, the second invocation sees the same Ids and skips them. A different set of records, including a later 200-record chunk, can still be processed.
Keep the guard in a handler
The trigger should route events to the handler:
trigger AccountTrigger on Account (after update) {
AccountTriggerHandler.afterUpdate(Trigger.new);
}This keeps recursion state and business logic in one testable class. In production code, add a carefully controlled bypass switch when an approved operation must re-enter the handler.
public class AccountTriggerHandler {
public static Boolean bypass = false;
public static void afterUpdate(List<Account> records) {
if (bypass) {
return;
}
// Guarded business logic goes here.
}
}A bypass should be narrow and explicit. Do not expose an uncontrolled switch that can silently disable required automation.
Transaction and asynchronous boundaries
Static variables persist only for the current transaction. Queueable jobs, future methods, and each batch execution run in separate transactions, so their static sets start empty. If recursion crosses an asynchronous boundary, design each transaction's guard independently. Do not use static state as permanent storage.
Choose the strategy
| Strategy | Best use | Main limitation |
|---|---|---|
| Before-trigger field update | Set fields on the triggering record | Cannot replace unrelated automation |
| Changed-field check | React only to meaningful changes | Requires old and new values |
| Static Set<Id> | Per-record protection in bulk work | State ends with the transaction |
A Boolean is simple but can skip every later record after the first invocation. Prefer a Set when each record must be handled independently.
Test once-per-record behavior
A test should update records, allow the handler's DML to re-fire the trigger, and verify the final result. Also test a bulk operation larger than 200 records when the implementation depends on chunk behavior.
Exercise
Why is a static Set<Id> safer than a static Boolean for bulk recursion protection?
Show answer
The Set skips only records already processed, while a Boolean can stop processing for all later records in the transaction.