Sub topic 10
Avoiding re-entry and job loops
This chapter assumes you can write a bulk-safe trigger and a Queueable class that implements Database.AllowsCallouts. It also assumes you know the basic governor limits. Earlier chapters moved the callout out of the trigger. Here you will stop that asynchronous work from triggering itself again.
How the loop forms
A callout often ends with a database write. The external system returns an ID or a status, and you save it on the record. That update can fire the same trigger that started the job.
- A user inserts an Account. The
after inserttrigger enqueuesAccountSyncJob. - The job calls the billing API and writes the result back to the Account.
- The write fires the trigger again, now as an
after update. - The trigger enqueues another
AccountSyncJob, and the cycle repeats.
Each pass runs in its own transaction. Salesforce does not see a recursive call, so no "maximum trigger depth exceeded" error stops it. The loop burns asynchronous Apex executions, callouts to the external system, and daily limits until something fails.
Why a static variable is not enough
The usual fix for trigger recursion is a static Boolean. That works inside one transaction. It does not work across the asynchronous boundary. Static variables live only as long as the transaction. A Queueable job starts a new transaction with fresh statics. A flag that the trigger sets before it enqueues the job is back to false when the job's DML fires the trigger.
A static Boolean also has a second flaw even in a single transaction. A bulk load of 10,000 records reaches the trigger in chunks of 200. If the first chunk sets the flag, the next 49 chunks are skipped, and those records never sync. If you use a static guard, track the record Ids you have handled instead:
public class AccountSyncGuard {
private static Set<Id> alreadyQueued = new Set<Id>();
// Returns only the Ids not yet queued in this transaction, and remembers them.
public static Set<Id> claim(Set<Id> candidates) {
Set<Id> fresh = candidates.clone();
fresh.removeAll(alreadyQueued);
alreadyQueued.addAll(fresh);
return fresh;
}
}This guards against re-entry within one transaction. For example, a flow that updates the record can re-fire the trigger in the same transaction. For the loop between the job and the trigger you need a guard that survives the boundary.
Guard with data, not with memory
State that is stored on the record, or passed into the job, carries across transactions. Three techniques are common.
| Technique | Survives the async boundary? | Best for |
|---|---|---|
| Static Boolean | No | Nothing in this pattern |
| Static `Set<Id>` | No | Re-entry within one transaction |
| Compare `Trigger.old` and `Trigger.new` | Yes | Syncing only when relevant fields change |
| Status field on the record | Yes | Syncing only records that need it |
| Attempt counter passed to the job | Yes | Bounding retries |
The most reliable technique is to enqueue only when a field you actually send to the API has changed. The job's write-back then touches only fields outside that set, so it never qualifies.
trigger AccountSyncTrigger on Account (after insert, after update) {
Set<Id> toSync = new Set<Id>();
for (Account a : Trigger.new) {
if (Trigger.isInsert || a.Name != Trigger.oldMap.get(a.Id).Name) {
toSync.add(a.Id);
}
}
toSync = AccountSyncGuard.claim(toSync);
if (!toSync.isEmpty()) {
System.enqueueJob(new AccountSyncJob(toSync, 0));
}
}The trigger uses Name because the payload contains id and name. If you add more fields to the payload, add them to the comparison. If the filter and the payload drift apart, you either miss real changes or re-sync on every update.
Write back only fields outside the filter
The job below assumes two custom fields on Account: Billing_Sync_Status__c (text) and Billing_Sync_Attempts__c (number). Neither is in the payload, and neither is in the trigger's comparison.
public class AccountSyncJob implements Queueable, Database.AllowsCallouts {
private static final Integer MAX_ATTEMPTS = 3;
private Set<Id> accountIds;
private Integer attempt;
public AccountSyncJob(Set<Id> accountIds, Integer attempt) {
this.accountIds = accountIds;
this.attempt = attempt;
}
public void execute(QueueableContext ctx) {
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
if (accounts.isEmpty()) {
return;
}
List<Map<String, Object>> payload = new List<Map<String, Object>>();
for (Account a : accounts) {
payload.add(new Map<String, Object>{ 'id' => a.Id, 'name' => a.Name });
}
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(20000);
req.setBody(JSON.serialize(payload));
HttpResponse res = new Http().send(req);
Boolean ok = res.getStatusCode() >= 200 && res.getStatusCode() < 300;
// The DML comes after the callout, which is allowed. The reverse order is not.
List<Account> updates = new List<Account>();
for (Account a : accounts) {
updates.add(new Account(
Id = a.Id,
Billing_Sync_Status__c = ok ? 'Synced' : 'Failed',
Billing_Sync_Attempts__c = attempt + 1
));
}
update updates;
if (!ok && res.getStatusCode() >= 500 && attempt + 1 < MAX_ATTEMPTS) {
System.enqueueJob(new AccountSyncJob(accountIds, attempt + 1));
}
}
}Three details matter here.
- The update uses new
Accountinstances that carry only the Id and the two status fields. The trigger fires, finds thatNameis unchanged for every record, and enqueues nothing. - The job writes back to the Account in a single DML statement for the whole list, so the write-back is bulk-safe.
- The retry is bounded by the
attemptcounter, which travels in the constructor. The retry covers only 5xx responses, because a 400 will fail the same way every time.
Limits that also stop chains
Salesforce limits enqueuing, and these limits can end a chain even when your logic is wrong.
- A synchronous transaction, such as a trigger, can enqueue up to 50 Queueable jobs.
- A Queueable can enqueue only one child job from its
executemethod. A secondSystem.enqueueJobcall throws aSystem.LimitException. - In Developer Edition and trial orgs, a chain can be only five jobs deep. Production orgs have no fixed depth limit.
- A future method cannot be called from another future method or from a Batch Apex method. This is a hard error, so a future-based version of this pattern cannot loop, but it also cannot chain.
Do not rely on these limits to stop a loop. They fail late and noisily, and part of the work may already have run. A retry that you want delayed can use the overload System.enqueueJob(job, delayInMinutes), which accepts 0 to 10 minutes. This avoids hammering an API that is already failing.
Checking for a loop in practice
If you suspect a loop, look at the evidence before changing code.
- In Setup, open Apex Jobs and sort by start time. A burst of identical
AccountSyncJobrows for the same records means a loop. - Query
AsyncApexJobfor the class and count rows over a short window. - Open a debug log for a single job run and check which trigger fired after the job's DML.
List<AggregateResult> rows = [
SELECT COUNT(Id) total, Status
FROM AsyncApexJob
WHERE ApexClass.Name = 'AccountSyncJob'
AND CreatedDate = LAST_N_DAYS:1
GROUP BY Status
];
System.debug(rows);A count in the thousands for a handful of Account edits is the sign you are looking for. The Billing_Sync_Attempts__c field also gives you a quick report of records that retried repeatedly.
Test that the loop is closed
A test should prove that the job's write-back does not enqueue a second job. This needs Test.setMock and a Test.startTest / Test.stopTest pair. The trigger enqueues the first job on insert. The job runs when stopTest is called.
@IsTest
private class AccountSyncLoopTest {
private class MockOk implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}
@IsTest
static void writeBackDoesNotEnqueueAnotherJob() {
Test.setMock(HttpCalloutMock.class, new MockOk());
Test.startTest();
insert new Account(Name = 'Acme');
Test.stopTest();
Integer jobs = [
SELECT COUNT() FROM AsyncApexJob
WHERE JobType = 'Queueable' AND ApexClass.Name = 'AccountSyncJob'
];
System.assertEquals(1, jobs, 'Exactly one job should run, with no loop');
Account a = [SELECT Billing_Sync_Status__c FROM Account WHERE Name = 'Acme'];
System.assertEquals('Synced', a.Billing_Sync_Status__c);
}
}If the filter were wrong, the write-back would enqueue a second job. In a test, queued jobs started inside stopTest run and any chained job is not run. The count assertion still catches a second job that was enqueued, so keep it.
Summary of rules
- Treat every job write-back as a possible trigger event.
- Filter on changed fields, not on the whole record being touched.
- Keep write-back fields separate from synced fields.
- Use a static
Set<Id>only for re-entry inside one transaction. - Pass attempt counters as arguments and set a maximum.
- Retry only errors that can succeed on a second try.
Exercise
A trigger on Account enqueues a Queueable when Trigger.new contains records. The job calls an API and then updates Account.Description with the response text. A developer adds a static Boolean hasRun to the trigger handler, sets it to true before enqueuing, and skips the trigger when it is true. Jobs still pile up. Why does the guard fail, and what change fixes it?
Show answer
The Queueable runs in a new transaction, so static variables are reset and hasRun is false again when the job's update fires the trigger. The trigger then enqueues another job. The fix is to guard with data. Enqueue only when a field that is sent to the API has changed, by comparing Trigger.old and Trigger.new, and write the response to a field that is outside that comparison. A status field or attempt counter on the record also works.
Exercise
A Queueable job retries by calling System.enqueueJob(new MyJob(ids)) on every failure, with no counter. Name two ways this can go wrong, and give one fix.
Show answer
A permanent failure, such as a 400 caused by bad data, makes the job retry forever, using asynchronous executions and callouts each time. The chain may also end with a limit error, which makes the failure harder to diagnose. The fix is to pass an attempt number in the constructor, stop at a maximum such as 3, and retry only transient errors such as 5xx responses. Optionally add a delay with System.enqueueJob(job, delayInMinutes).