Sub topic 9
Tracking processed records with a static Set of Ids
This chapter assumes you can write an Apex trigger and a handler class, and that you know Set<Id> and Map collections. It also assumes you know why a trigger that updates its own object can re-fire. The earlier chapters showed that a static Boolean flag stops the loop but can skip records when a bulk operation arrives in several chunks. Here you replace the flag with a static Set<Id>, so the guard works per record instead of per transaction.
The idea: remember which records you handled
A static Boolean answers the question "has this code run in this transaction?" A static Set of Ids answers a better one: "has this record been handled in this transaction?"
Static variables live for the whole transaction, across every trigger invocation in it. So a static Set of Ids is shared by the original trigger run, by every 200-record chunk of a bulk operation, and by any re-fired trigger caused by your own DML. Each run checks the Set before processing a record and adds the Id after it decides to process it.
A working handler
This handler adds each Id to the Set before it issues DML. When the update re-fires the trigger, every Id is already in the Set, so the nested run builds an empty list and does nothing.
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;
}
}
}The trigger stays thin and only routes to the handler:
trigger AccountTrigger on Account (after update) {
if (Trigger.isAfter && Trigger.isUpdate) {
AccountTriggerHandler.afterUpdate(Trigger.new);
}
}Three details matter here:
- The Id is added before the DML. The nested trigger runs inside the
updatestatement. If you added the Ids after the statement, the nested run would not see them. - The DML is skipped when the list is empty. An
updateof an empty list does not fire the trigger, but the check keeps the intent clear and avoids a pointless statement. - The
Accountobjects intoUpdateare new instances. They carry only the Id and the changed field, so the update does not overwrite other fields with stale values fromTrigger.new, which is read-only in after triggers.
Following a bulk update through the guard
Suppose a user updates 450 accounts in one transaction, such as a Data Loader run. Salesforce passes the records to the trigger in chunks of up to 200. The static Set persists across all of them.
With a Boolean flag, chunk 1 would set the flag and chunks 2 and 3 would return early, leaving 250 records unprocessed. With the Set, each chunk contains Ids the Set has not seen, so every record is processed once. The re-fired runs contain only Ids already in the Set, so they do nothing.
Why the guard needs a stable Id
A before insert trigger has no Ids yet, because records get their Id when they are saved. acc.Id is null for every record, so a Set of Ids cannot tell them apart. The Set would hold a single null, and every record after the first would be skipped.
Use the Set guard in after insert, before update, after update, and the delete and undelete events, where Ids exist. For before insert, do the work in the trigger without DML and rely on field checks instead. Chapter 4 covered that approach.
One Set per purpose
A single Set shared by before update and after update logic causes a subtle bug. The before handler adds the Id, and the after handler then sees the Id and skips the record, even though it has never run. Keep one Set per handler method, and name it for what it protects:
public class AccountTriggerHandler {
private static Set<Id> beforeUpdateIds = new Set<Id>();
private static Set<Id> afterUpdateIds = new Set<Id>();
public static void beforeUpdate(List<Account> newList) {
for (Account acc : newList) {
if (beforeUpdateIds.add(acc.Id)) {
acc.Description = 'Reviewed';
}
}
}
public static void afterUpdate(List<Account> newList) {
List<Account> toUpdate = new List<Account>();
for (Account acc : newList) {
if (afterUpdateIds.add(acc.Id)) {
toUpdate.add(new Account(Id = acc.Id, Rating = 'Warm'));
}
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}
}Set.add returns true when the element was not already present and false when it was. That lets you test and record in one expression, which is shorter than the contains and add pair. The result is the same.
The main trade-off: a record runs once, even if it should run twice
The Set says "never again" for a record, for the rest of the transaction. Sometimes that is wrong. Consider this sequence in one transaction:
- A user saves an Account with
Rating = 'Hot'. Your after trigger processes it and adds its Id. - A workflow field update or a flow then changes the Rating to
'Cold', and the trigger re-fires. - The Set contains the Id, so the trigger skips the record, and your logic never sees the
'Cold'value.
This is a correctness trade-off, not a performance one. If your logic depends on later values in the same transaction, a plain Set hides them. Two fixes are common.
Combine the Set with a changed-value check. Process a record only when it is new to the Set or when the field you care about has changed since the last time you handled it. Storing the last handled value in a Map does this:
public class AccountRatingHandler {
private static Map<Id, String> handledRatings = new Map<Id, String>();
public static void afterUpdate(List<Account> newList) {
List<Account> toUpdate = new List<Account>();
for (Account acc : newList) {
if (handledRatings.containsKey(acc.Id)
&& handledRatings.get(acc.Id) == acc.Rating) {
continue;
}
handledRatings.put(acc.Id, acc.Rating);
toUpdate.add(new Account(Id = acc.Id, Description = 'Rating is ' + acc.Rating));
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}
}containsKey is required because Rating can legitimately be null, and get also returns null for a missing key. Without it, a record with a null Rating would be skipped the first time.
Check old against new values. The Trigger.oldMap comparison from the earlier chapter often replaces the Set entirely, because a re-fired trigger with no relevant change does nothing.
Costs and limits to keep in mind
- Heap size. The Set holds an Id per processed record. Ids are small, but a transaction touching hundreds of thousands of records can accumulate a large Set. Synchronous Apex has a 6 MB heap limit, and asynchronous Apex has 12 MB. A Map of Id to value grows faster than a Set.
- No sharing across transactions. Static state is discarded when the transaction ends. A Queueable, future method, or batch job runs in a new transaction with an empty Set, so a trigger re-fired from asynchronous work is not guarded by the earlier Set. A later chapter covers this.
- The guard hides bugs as well as loops. If a record is skipped unexpectedly, check whether its Id was added by an earlier code path in the same transaction.
- Order of Ids does not matter. A Set is unordered, so do not rely on iteration order of
processedIds. Iterate the trigger's list instead.
Comparison with the Boolean flag
| Aspect | Static Boolean | Static `Set<Id>` |
|---|---|---|
| Granularity | Whole transaction | Per record |
| Bulk operations over 200 records | Skips later chunks | Processes every chunk |
| Memory | One value | One Id per record |
| Works in `before insert` | Yes | No, Ids are `null` |
| Hides a later legitimate change to the same record | Yes | Yes, unless combined with a value check |
Exercises
Exercise
A handler uses a static Set<Id> guard in its after update method. A batch of 450 Accounts is updated in one transaction. How many records does the handler process in total, and why does the Set not skip the second and third chunks of 200 and 50?
Show answer
It processes all 450 records. The static Set lives for the whole transaction, so it is shared by every chunk, but each chunk holds different Ids that are not yet in the Set. Only a repeated Id is skipped, such as one seen again when the handler's own update re-fires the trigger. A Boolean flag would have skipped the last 250 records.
Exercise
Why does a Set<Id> guard fail in a before insert trigger, and what would you use in that trigger instead?
Show answer
Records in a before insert trigger have no Id yet, so every acc.Id is null. The Set would contain a single null, and every record after the first would be treated as already processed. Instead, change the fields on the records in Trigger.new without DML, and check field values so the logic runs only when needed.