Sub topic 3
Avoiding Re-entry and Job Loops
Assume you know Apex triggers, Queueable Apex, governor limits, and basic HTTP callouts. An asynchronous job runs in a new transaction. If its callout response updates an Account, that update can fire the trigger again and enqueue another job.
Gate work on the fields that actually require synchronization. For example, enqueue on insert or when Name changes, but do not enqueue when only Sync_Status__c changes.
trigger AccountSyncTrigger on Account (after insert, after update) {
Set<Id> ids = new Set<Id>();
for (Account current : Trigger.new) {
if (Trigger.isInsert ||
current.Name != Trigger.oldMap.get(current.Id).Name) {
ids.add(current.Id);
}
}
if (!ids.isEmpty()) {
System.enqueueJob(new AccountSyncJob(ids));
}
}A static Boolean can prevent duplicate work inside one transaction, but it does not protect against a later asynchronous transaction. A field-based gate, an integration-origin field, or a persistent synchronization status is safer.
Handling Failures and Using Finalizers
Check every HTTP status code. A Queueable Finalizer runs after the Queueable completes, including after an unhandled exception. Use it to record failure details or schedule controlled recovery.
public class AccountSyncFinalizer implements Finalizer {
public void execute(FinalizerContext context) {
if (context.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
System.debug(LoggingLevel.ERROR,
'Sync failed: ' + context.getException().getMessage());
}
}
}Testing with `HttpCalloutMock`
Tests cannot call the real service. Test.setMock supplies a fake response, and Test.stopTest() runs queued work before assertions.
Test.setMock(HttpCalloutMock.class, new MockOk());
Test.startTest();
insert new Account(Name = 'Acme');
Test.stopTest();When Batch Apex Fits
Use Batch Apex when the record set is large or must be processed in manageable scopes. The batch class implements Database.AllowsCallouts, and each execute method sends a bulk request for its scope.
Monitoring and Choosing an Approach
Query AsyncApexJob to inspect queued, running, failed, and completed jobs.
flowchart TD
A[Trigger] --> B{Work needs synchronization?}
B -->|No| C[Stop]
B -->|Yes| D[Enqueue async job]
D --> E[Callout]
E --> F[Update status only]
F --> B| Approach | Best fit |
|---|---|
| Future | Small, simple fire-and-forget work |
| Queueable | Payloads, chaining, monitoring, and Finalizers |
| Batch | Large data sets processed in scopes |
Exercise
Why can a static recursion guard fail to prevent a Queueable job loop?
Show answer
The Queueable runs in a new transaction, where the previous transaction's static state no longer exists.