Sub topic 9
Controlling chains with AsyncOptions
This chapter assumes you can write a Queueable class, enqueue it with System.enqueueJob, and chain a child job from execute. It also assumes you know the basic chaining limits. Chained jobs can repeat forever by accident, run too soon, or be enqueued twice. AsyncOptions lets the code that enqueues a job control all three problems.
What AsyncOptions is
AsyncOptions is a class you pass as a second argument to System.enqueueJob. It has three properties, and you set only the ones you need.
| Property | Type | What it does |
|---|---|---|
| `MaximumQueueableStackDepth` | Integer | Caps how many jobs deep a chain can go |
| `MinimumQueueableDelayInMinutes` | Integer | Delays the job's start by at least this many minutes (0 to 10) |
| `DuplicateSignature` | QueueableDuplicateSignature | Rejects the enqueue if a job with the same signature is already waiting |
The following example sets all three.
AsyncOptions options = new AsyncOptions();
options.MaximumQueueableStackDepth = 3;
options.MinimumQueueableDelayInMinutes = 2;
options.DuplicateSignature = QueueableDuplicateSignature.Builder()
.addId(UserInfo.getUserId())
.addString('AccountRatingJob')
.build();
System.enqueueJob(new AccountRatingJob(accountIds), options);The overload returns the job ID, the same as the plain System.enqueueJob(job). If you only need a delay, a shorter overload exists: System.enqueueJob(job, 5) delays the job by five minutes.
flowchart TDThe diagram block below shows the order of checks at enqueue time.
Stack depth
The stack depth is the position of a job in its chain. The first job has depth 1. A job it enqueues has depth 2, and so on. Without a cap, a chain keeps going as long as each job enqueues another. In a production org that is a risk when a bug makes a job always enqueue a child. Every run succeeds, so nothing fails, and the chain consumes async capacity indefinitely.
MaximumQueueableStackDepth sets a ceiling. With a value of 3, depths 1, 2, and 3 run. A job at depth 3 that tries to enqueue a child fails. Set the value on the first enqueue. The chain carries the limit forward, so you do not repeat it in each child.
The failure is a System.LimitException. Apex cannot catch a LimitException, so a try/catch will not save you. Check the depth before you enqueue, using the AsyncInfo class:
public class DepthAwareJob implements Queueable {
private static final Integer CHUNK_SIZE = 200;
private List<Id> remaining;
public DepthAwareJob(List<Id> remaining) {
this.remaining = remaining;
}
public void execute(QueueableContext context) {
Integer n = Math.min(CHUNK_SIZE, remaining.size());
List<Id> current = new List<Id>();
List<Id> rest = new List<Id>();
for (Integer i = 0; i < remaining.size(); i++) {
if (i < n) {
current.add(remaining[i]);
} else {
rest.add(remaining[i]);
}
}
List<Account> accounts = [SELECT Id, Description FROM Account WHERE Id IN :current];
for (Account a : accounts) {
a.Description = 'Processed';
}
update accounts;
if (rest.isEmpty() || Test.isRunningTest()) {
return;
}
Boolean atCeiling = AsyncInfo.hasMaxStackDepth()
&& AsyncInfo.getCurrentQueueableStackDepth() >= AsyncInfo.getMaximumQueueableStackDepth();
if (atCeiling) {
System.debug(LoggingLevel.WARN, rest.size() + ' records left unprocessed at depth '
+ AsyncInfo.getCurrentQueueableStackDepth());
} else {
System.enqueueJob(new DepthAwareJob(rest));
}
}
}The AsyncInfo methods used here are:
hasMaxStackDepth()returns true only when the chain was started with a maximum.getCurrentQueueableStackDepth()returns the depth of the running job.getMaximumQueueableStackDepth()returns the configured ceiling.
When the job reaches the ceiling, it should hand the leftover work to something else. It can log it, store it in a custom object, or let a scheduled job pick it up later. Silently dropping the remainder is the worst option.
The org's edition also caps chains. Developer Edition and trial orgs allow a chain of at most five jobs, whatever you set. An option can lower the ceiling but cannot raise it above what the org allows.
Delaying a job
MinimumQueueableDelayInMinutes accepts whole minutes from 0 to 10. A value outside that range throws an exception when you enqueue.
A delay is useful in three situations:
- Rate limits. A chained job that calls an external API can wait a couple of minutes between slices so it does not exceed the API's rate limit.
- Eventual consistency. If another system needs time to finish processing, a short delay avoids reading half-written data.
- Retries. A retry that runs immediately often hits the same transient fault. A delay of a few minutes gives the fault time to clear.
The value is a minimum. The job starts no sooner than the delay, but it can start later depending on queue load. Do not build logic that assumes it starts at exactly that minute.
Combine the delay with a finalizer for retries with backoff. The finalizer builds an AsyncOptions whose delay grows with the attempt number:
public class RetryWithDelayFinalizer implements Finalizer {
private List<Id> recordIds;
private Integer attempt;
public RetryWithDelayFinalizer(List<Id> recordIds, Integer attempt) {
this.recordIds = recordIds;
this.attempt = attempt;
}
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.SUCCESS || attempt >= 3) {
return;
}
AsyncOptions options = new AsyncOptions();
options.MinimumQueueableDelayInMinutes = Math.min(attempt * 2, 10);
System.enqueueJob(new ImportJob(recordIds, attempt + 1), options);
}
}The Math.min keeps the delay inside the allowed range. ImportJob is the class from the finalizer chapters.
Duplicate signatures
Triggers and flows often fire several times in quick succession, and each firing may enqueue the same job. Ten identical jobs waiting in the queue waste capacity. A duplicate signature lets the platform reject the extras.
You build a signature with QueueableDuplicateSignature.Builder(). Add values with addId, addInteger, and addString, then call build(). Two enqueues are duplicates when their signatures match. If a job with that signature is still waiting in the queue, the second System.enqueueJob call throws a DuplicateMessageException. Unlike a limit exception, you can catch this one:
public class RatingScheduler {
public static Id enqueueOnce(List<Id> accountIds) {
AsyncOptions options = new AsyncOptions();
options.DuplicateSignature = QueueableDuplicateSignature.Builder()
.addId(UserInfo.getUserId())
.addString('AccountRatingJob')
.build();
try {
return System.enqueueJob(new AccountRatingJob(accountIds), options);
} catch (DuplicateMessageException e) {
System.debug('Skipped duplicate enqueue: ' + e.getMessage());
return null;
}
}
}Choose the signature values with care, because they define what counts as the same work.
- Too few values make unrelated jobs collide. A signature of only the class name blocks every user's job while one is waiting.
- Too many values let duplicates through. Adding a timestamp makes every signature unique and defeats the check.
A good signature identifies the work: the class name plus the user, the record ID, or the batch key. The example above uses the user ID and the class name, so each user can have one pending rating job.
Signature matching applies to jobs waiting in the queue. A job that has already started is no longer a pending duplicate. If the same work can be triggered again while the first run executes, your job still has to handle overlapping runs.
Gotchas
- The options object configures the job being enqueued. Setting a depth cap on a child enqueue does not change the parent.
- A returned job ID is not proof that the job ran. A delayed job is in the queue for at least the delay, so query
AsyncApexJobfor its status. - In tests, delays do not make the job wait.
Test.stopTest()still runs the enqueued job. Chaining inside a test is not allowed, so keep theTest.isRunningTest()guard when you test chains. - When a job is rejected as a duplicate, no job ID exists. Code that expects an ID must handle
null.
Choosing options
| Problem | Option |
|---|---|
| A bug could create an endless chain | `MaximumQueueableStackDepth` |
| An external API needs breathing room | `MinimumQueueableDelayInMinutes` |
| A trigger enqueues the same job repeatedly | `DuplicateSignature` |
| A retry hits the same transient fault | `MinimumQueueableDelayInMinutes` in the finalizer |
Exercise
A trigger enqueues AccountRatingJob every time an account changes. During a bulk load, hundreds of identical jobs pile up. You add a duplicate signature built only from addString('AccountRatingJob'). A second user then reports that their job never runs while the first user's job is waiting. What is wrong, and how do you fix it? Also say what the enqueue call does for the rejected job.
Show answer
The signature is too broad. It has no user-specific value, so every user's job has the same signature, and one user's waiting job blocks everyone else's. Add a value that identifies the work, such as addId(UserInfo.getUserId()), so each user can have one pending job. The rejected enqueue throws a DuplicateMessageException, which you can catch. No job ID is returned, so the caller must handle that case.
Exercise
A chain is started with MaximumQueueableStackDepth = 3. The job at depth 3 still has records left. Why is try { System.enqueueJob(next); } catch (Exception e) { ... } the wrong way to handle this, and what should the job do instead?
Show answer
Exceeding the depth throws a System.LimitException, which Apex cannot catch, so the catch block never runs and the job fails. Check AsyncInfo.hasMaxStackDepth() and compare getCurrentQueueableStackDepth() with getMaximumQueueableStackDepth() before enqueuing. At the ceiling, log or store the unprocessed work so another process can pick it up.