How do you prevent recursive asynchronous job enqueuing triggered by recursive database DML updates?
Answer
Basics: A common loop: trigger enqueues a job, the job updates records, the update fires the trigger, which enqueues another job. Static variables reset between transactions, so a static flag set in the trigger never reaches the job's transaction.
How it works: Break the cycle in at least one place:
- Only enqueue when a relevant field actually changed (compare
Trigger.oldMaptoTrigger.new). - Have the job set a marker field (for example
Sync_Pending__c = false) and make the trigger enqueue only when it is true. - Skip enqueueing when already in async context.
- Optionally dedupe with a Custom Setting or hierarchy bypass flag.
Advanced / deep dive: System.isFuture() and System.isBatch() let triggers avoid calling @future from those contexts, which would throw anyway. For queueable duplication, use AsyncOptions with a DuplicateSignature (QueueableDuplicateSignature.Builder) so identical jobs are rejected (verify API version support). Chain depth in production is unlimited, so a loop can run until it exhausts daily async limits; in Developer Edition it stops at depth 5, which hides the bug in dev. Also consider replacing the trigger-plus-job design with platform events or Change Data Capture, which decouple the producer from the consumer. Add an explicit exit condition (a "done" flag or retry counter on the record).
Code / config example:
// Trigger handler (after update)
public static void {
(System.isBatch() || System.isFuture()) ;
Set<Id> toSync = <Id>();
(Account a : newMap.values()) {
oldMap.get(a.Id);
(a.Billing_Key__c != o.Billing_Key__c && a.Sync_Pending__c) {
toSync.add(a.Id);
}
}
(!toSync.isEmpty()) System.enqueueJob( ( <Id>(toSync)));
}