# How do you prevent recursive asynchronous job enqueuing triggered by recursive database DML updates?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Triggers

Read it on the site: https://www.forcechallenges.com/interview-questions/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:
1. Only enqueue when a relevant field actually changed (compare `Trigger.oldMap` to `Trigger.new`).
2. Have the job set a marker field (for example `Sync_Pending__c = false`) and make the trigger enqueue only when it is true.
3. Skip enqueueing when already in async context.
4. 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:**
```apex
// Trigger handler (after update)
public static void afterUpdate(Map<Id,Account> oldMap, Map<Id,Account> newMap) {
    if (System.isBatch() || System.isFuture()) return;
    Set<Id> toSync = new Set<Id>();
    for (Account a : newMap.values()) {
        Account o = oldMap.get(a.Id);
        // only when a business field changed AND we are not already synced
        if (a.Billing_Key__c != o.Billing_Key__c && a.Sync_Pending__c) {
            toSync.add(a.Id);
        }
    }
    if (!toSync.isEmpty()) System.enqueueJob(new SyncAccountsJob(new List<Id>(toSync)));
}
```

**Hidden gotchas & must-remember points:**
- Static variables are per transaction, so they never span jobs.
- Developer Edition's 5-deep queueable limit hides loops that explode in production.
- The job's own DML must not flip the field the trigger watches.
- 24-hour async limit exhaustion is the usual symptom.
- `@future` from a future method throws an exception.

**Best practice:** Make the trigger condition depend on persisted record state, not on in-memory flags.

---
Source: ForceChallenges · last updated 2026-11-02
