Sub topic 12
Queueable, future, and batch: static state resets
This chapter assumes you can write Apex triggers and handler classes. It also assumes you know what a static variable is and what the earlier chapters covered: the static Boolean flag guard, the static Set<Id> guard, and the changed-field check. You should also know that governor limits apply per transaction.
Why static guards stop working here
A static variable lives for one transaction. Asynchronous Apex (Queueable, @future, Batch) starts a new transaction later, on a separate thread of execution. That transaction begins with fresh static state, so every static guard is back to its initial value.
If the asynchronous work updates records that fire the same trigger, the trigger runs again. The static flag, which was set in the first transaction, is false again, and the trigger enqueues the same work a second time.
| Async mechanism | Runs in a new transaction | Static variables carried over | Notes for recursion |
|---|---|---|---|
| `@future` method | Yes | No | A future method cannot call another future method. A trigger that fires from inside a future method cannot call one either. |
| Queueable job | Yes | No | A job can enqueue one child job, so chains are possible. |
| Batch `execute()` | Yes, once per scope chunk | No | `Database.Stateful` keeps instance variables only, not statics. |
| Schedulable | Yes | No | Same as above. |
The next section shows the failure with a Queueable job.
A loop that a static flag cannot stop
The handler below uses the Boolean flag from earlier in this tutorial. Instead of updating records directly, it hands the work to a Queueable job.
public class AccountTriggerHandler {
private static Boolean hasRun = false;
public static void afterUpdate(List<Account> newList) {
if (hasRun) {
return;
}
hasRun = true;
System.enqueueJob(new ReviewAccountsJob(new Map<Id, Account>(newList).keySet()));
}
}The job writes to the same object:
public class ReviewAccountsJob implements Queueable {
private Set<Id> accountIds;
public ReviewAccountsJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> toUpdate = new List<Account>();
for (Id accountId : accountIds) {
toUpdate.add(new Account(Id = accountId, Description = 'Reviewed'));
}
update toUpdate;
}
}The trigger stays the same thin router as before:
trigger AccountTrigger on Account (after update) {
if (Trigger.isAfter && Trigger.isUpdate) {
AccountTriggerHandler.afterUpdate(Trigger.new);
}
}The sequence is:
No error says "maximum trigger depth exceeded", because each trigger execution is only one level deep. The loop is spread across many transactions. It stops only when something external stops it:
- In Developer Edition and trial orgs, the Queueable chain depth is capped, so you get a stack depth error.
- In other orgs, the chain can continue until you hit the daily asynchronous Apex execution limit, or until someone aborts the job.
Fix 1: gate the enqueue on a real change
The most reliable fix does not depend on static state at all. Make the trigger enqueue the job only when a field you care about changed. The job's own update changes a different field (Description), so the second trigger run finds nothing to do.
public class AccountTriggerHandler {
public static void afterUpdate(List<Account> newList, Map<Id, Account> oldMap) {
Set<Id> changedIds = new Set<Id>();
for (Account acc : newList) {
Account oldAcc = oldMap.get(acc.Id);
if (acc.Rating != oldAcc.Rating) {
changedIds.add(acc.Id);
}
}
if (!changedIds.isEmpty()) {
System.enqueueJob(new ReviewAccountsJob(changedIds));
}
}
}The trigger passes both collections:
trigger AccountTrigger on Account (after update) {
if (Trigger.isAfter && Trigger.isUpdate) {
AccountTriggerHandler.afterUpdate(Trigger.new, Trigger.oldMap);
}
}This works because the guard is stored in the data. Trigger.oldMap is rebuilt from the database on every execution, so it is correct in every transaction. The guard survives the async boundary because it never lived in a static variable.
The check only holds while the job never writes the field that the trigger watches. If the job changed Rating as well, the trigger would enqueue again and the loop would return.
Fix 2: persist the guard in a field
Sometimes there is no natural "changed field" to test. In that case, store the guard state on the record, for example in a checkbox such as Review_Queued__c. The trigger checks it and the job clears or sets it. Compare the options:
| Approach | Survives async boundary | Cost | Main risk |
|---|---|---|---|
| Static Boolean or `Set<Id>` | No | None | Infinite chain across transactions |
| Changed-field check | Yes | None | The job must never change the watched field |
| Persisted marker field | Yes | An extra field and an extra DML write | Stale markers if a job fails before clearing them |
If you use a persisted marker, set it in a before trigger (no extra DML) and clear it as part of the job's own update. Handle job failure explicitly. A marker left set after a failed job will block later work for that record.
Batch Apex: one transaction per chunk
A batch job calls execute() once per scope chunk, and each call is its own transaction. Static variables are reset between chunks. This has two effects:
- A static guard cannot remember records handled in an earlier
execute()call. This is usually harmless, because chunks contain different records. - If a trigger fires inside
execute(), its static state starts clean for every chunk, exactly like a fresh transaction.
Use Database.Stateful when the batch class itself must remember values across chunks. It preserves instance variables only:
public class RatingReviewBatch implements Database.Batchable<SObject>, Database.Stateful {
private Integer processed = 0; // kept between execute() calls
private static Integer staticCount = 0; // reset on every execute() call
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id, Rating FROM Account WHERE Rating = \'Hot\'');
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
processed += scope.size();
staticCount += scope.size();
for (Account acc : scope) {
acc.Description = 'Reviewed';
}
update scope;
System.debug('Instance total: ' + processed + ', static total: ' + staticCount);
}
public void finish(Database.BatchableContext bc) {
System.debug('Processed ' + processed + ' accounts');
}
}In the debug output, the instance total grows across chunks while the static total always equals the size of the current chunk. Do not use a static field to carry state between chunks, and do not expect a trigger guard to coordinate with it.
Future methods and context checks
A @future method also starts with empty statics. Two restrictions matter for triggers:
- A future method cannot be called from another future method or from a batch
execute(). If your trigger enqueues a future call and the same trigger fires from within a future or batch context, the call throws an exception. - A Queueable job does not have this restriction, which is why it is usually the better choice for trigger-initiated async work.
When you must keep a trigger from starting more async work while it runs inside one, check the context:
public static void afterUpdate(List<Account> newList, Map<Id, Account> oldMap) {
if (System.isFuture() || System.isBatch()) {
return; // already async; do the work inline or skip deliberately
}
// enqueue work here
}Use this sparingly. Skipping logic because the caller is async changes behavior for those callers, so make that decision explicitly and document it. Treat it as a form of bypass switch, not as a general recursion guard.
Checklist for async work started by a trigger
- Ask what the async job writes. If it writes the same object, assume the trigger will fire again.
- Prefer guards that live in the data: a changed-field check, or a persisted marker.
- Keep the job from touching the field that triggers the enqueue.
- Pass record Ids into the job, not the records. The records in
Trigger.newcan be stale by the time the job runs. - Test that exactly one job is enqueued, as in the test below.
Testing that the job is enqueued once
Async jobs execute when Test.stopTest() is called. After that point you can count the jobs that were enqueued.
@IsTest
private class AccountTriggerHandlerAsyncTest {
@IsTest
static void ratingChangeEnqueuesOneJobAndDoesNotLoop() {
Account acc = new Account(Name = 'Test Account');
insert acc;
Test.startTest();
acc.Rating = 'Hot';
update acc;
Test.stopTest();
Integer jobCount = [
SELECT COUNT()
FROM AsyncApexJob
WHERE JobType = 'Queueable' AND ApexClass.Name = 'ReviewAccountsJob'
];
System.assertEquals(1, jobCount, 'The job should be enqueued once');
Account result = [SELECT Description FROM Account WHERE Id = :acc.Id];
System.assertEquals('Reviewed', result.Description);
}
}The count assertion is what catches the static-flag bug. With the flag-only version from earlier in this chapter, the job's update would enqueue a second job, and the count would be greater than one or the test would fail with a depth error.
Exercise
A trigger uses a static Boolean hasRun guard and enqueues a Queueable job. The job updates the same Accounts, which fires the trigger again. Why does the guard not stop the second enqueue, and what is a guard that does?
Show answer
The job runs in a new transaction, and static variables reset at the start of every transaction, so hasRun is false again. A guard that survives the boundary must live in the data. For example, compare Trigger.new with Trigger.oldMap and enqueue only when a watched field such as Rating changed, as long as the job does not modify that field.
Exercise
A batch class declares private static Integer total and adds scope.size() to it in every execute() call. What value does total hold at the start of the third execute() call, and what change would make the total accumulate across chunks?
Show answer
It is 0, because each execute() call runs in its own transaction and static variables reset. Make the field an instance variable (private Integer total) and implement Database.Stateful on the batch class so the instance state is kept between chunks.