Sub topic 5
Chaining Queueable jobs for sequential steps
This chapter assumes you can write a basic Queueable class, as covered in the previous chapter. You should also know how governor limits apply to a single transaction. Chaining builds on both.
What chaining is
A Queueable job can enqueue another Queueable job from inside its own execute method. The second job is the child. The job that enqueued it is the parent. The child starts only after the parent's transaction finishes.
Chaining is how you run steps in a guaranteed order. Two separate System.enqueueJob calls from a trigger give you no ordering promise. A chain does, because the child does not exist until the parent has run.
Chaining gives you two more things:
- Each job in the chain gets its own fresh set of governor limits. Asynchronous limits apply, such as 200 SOQL queries and 60,000 ms of CPU time per job.
- Each job can pass data to the next one through its constructor.
The one-child rule
The key restriction is the number of children. A job running asynchronously, as a Queueable does, can enqueue only one child job. A second System.enqueueJob call in the same execute throws a LimitException.
This differs from the synchronous case. A trigger, controller, or anonymous Apex block can enqueue up to 50 jobs in one transaction. Only the async context is limited to one.
| Where `System.enqueueJob` runs | Jobs you can enqueue |
|---|---|
| Synchronous transaction (trigger, controller, anonymous Apex) | Up to 50 |
| Inside a running Queueable's `execute` | 1 |
| Inside a finalizer | 1 |
Because of the one-child rule, a chain is a line. It is never a tree. If you need fan-out, enqueue many jobs from a synchronous transaction, or use Batch Apex.
A worked example: processing a list in chunks
Suppose a trigger hands you 1,000 accounts and each one needs a slow update. You can split the list into chunks of 100. Each job processes one chunk, then enqueues a job for the rest.
public class ChunkedUpdateJob implements Queueable {
private List<Account> remaining;
public ChunkedUpdateJob(List<Account> remaining) {
this.remaining = remaining;
}
public void execute(QueueableContext ctx) {
Integer chunkSize = Math.min(100, remaining.size());
List<Account> chunk = new List<Account>();
for (Integer i = 0; i < chunkSize; i++) {
chunk.add(remaining.remove(0));
}
update chunk;
if (!remaining.isEmpty()) {
System.enqueueJob(new ChunkedUpdateJob(remaining));
}
}
}Read the flow carefully:
- The constructor stores the whole list in a member variable. Apex serializes that state when the job is enqueued.
executeremoves up to 100 records from the front of the list and updates them.- If records remain,
executeenqueues a new instance that holds only the leftovers. - When the list is empty, the chain ends.
The System.enqueueJob call is the last statement. That placement is deliberate. If the update throws an exception, the code never reaches the enqueue, and the chain stops instead of continuing past a failed step.
Passing state down the chain
The constructor is the only channel between jobs. Whatever you put in member variables is serialized into the next job. This works for sObjects, collections, and custom classes. Three rules keep it reliable:
- Pass only what the next step needs. Large lists add to heap use and to the serialization cost of every link.
- Prefer record Ids over full sObjects when the next job can re-query. Re-querying gives the next job current data. A carried sObject can be stale by the time the job runs.
- Do not rely on static variables. Each job runs in a new transaction, so statics reset.
A common pattern is a small state object that carries a step number and the Ids to work on:
public class PipelineJob implements Queueable {
private Integer step;
private Set<Id> accountIds;
public PipelineJob(Integer step, Set<Id> accountIds) {
this.step = step;
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
List<Account> accts = [SELECT Id, Description FROM Account WHERE Id IN :accountIds];
for (Account a : accts) {
a.Description = 'Step ' + step + ' done';
}
update accts;
if (step < 3) {
System.enqueueJob(new PipelineJob(step + 1, accountIds));
}
}
}Each step re-queries the accounts, so it sees the changes made by the previous step.
How deep can a chain go
Chain depth is the number of links, called the stack depth. The initial job has depth 1.
- In Developer Edition and trial orgs, the maximum depth is 5: the initial job plus four chained children. Exceeding it throws an exception when you try to enqueue.
- In other orgs, Salesforce sets no fixed limit on depth.
An unbounded chain is a risk. A bug in your stop condition creates a loop that keeps consuming async capacity. You can set your own cap with AsyncOptions:
AsyncOptions options = new AsyncOptions();
options.MaximumQueueableStackDepth = 6;
options.MinimumQueueableDelayInMinutes = 2;
System.enqueueJob(new ChunkedUpdateJob(remaining), options);MaximumQueueableStackDepth makes the platform refuse links beyond that depth. MinimumQueueableDelayInMinutes delays the start of the child by up to 10 minutes, which is useful when you poll an external system and want to space out calls. Inside a job, AsyncInfo.hasMaxStackDepth() tells you whether you have reached the cap you set, so you can stop cleanly instead of catching an exception.
if (!remaining.isEmpty() && !AsyncInfo.hasMaxStackDepth()) {
System.enqueueJob(new ChunkedUpdateJob(remaining));
}When a link fails
If a job throws an unhandled exception, its transaction rolls back and the chain stops there. The remaining work is never enqueued. Nothing retries it for you.
You have two ways to deal with this:
- Catch exceptions inside
execute, record the problem, and decide whether to enqueue the next link anyway. - Attach a finalizer to each job. A finalizer runs after the job ends, even on failure, and can enqueue one new job. That job can be a retry or a continuation. Finalizers are covered in the next chapter.
Be careful with catch-and-continue. If you swallow an exception from a DML statement inside a try block, the data may be partly saved. Use Database.update(records, false) and inspect the SaveResult list when you want to keep going after row-level failures.
Chaining versus Batch Apex
Chunked Queueable chains look like a hand-built Batch job. They are not a replacement. The differences matter when the data is large:
| Concern | Queueable chain | Batch Apex |
|---|---|---|
| Data source | A list you pass in | A query locator that can return up to 50 million records |
| State between steps | You serialize it yourself | `Database.Stateful` keeps instance variables |
| Parallel work | None, strictly one link at a time | The platform may process batches in parallel |
| Built-in progress | Job Id per link, no overall view | One job Id with total and processed batch counts |
| Best for | A few dependent steps, small to medium lists | Large volumes of records |
Use a chain when step B needs the result of step A. Use Batch when you have many records and the same operation applies to all of them.
Testing a chain
In an Apex test, Test.stopTest() runs queued jobs, but a chained child cannot be enqueued from a job that is itself running in a test. The platform throws an error. The usual workaround is to skip the enqueue when running a test:
@IsTest
private class ChunkedUpdateJobTest {
@IsTest
static void processesFirstChunk() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 150; i++) {
accts.add(new Account(Name = 'Acct ' + i));
}
insert accts;
Test.startTest();
System.enqueueJob(new ChunkedUpdateJob(accts));
Test.stopTest();
Integer updated = [SELECT COUNT() FROM Account WHERE Description = 'Processed'];
Assert.areEqual(100, updated);
}
}This test needs a version of the job that sets Description = 'Processed' on each record in the chunk and checks Test.isRunningTest() before chaining:
public class ChunkedUpdateJob implements Queueable {
private List<Account> remaining;
public ChunkedUpdateJob(List<Account> remaining) {
this.remaining = remaining;
}
public void execute(QueueableContext ctx) {
Integer chunkSize = Math.min(100, remaining.size());
List<Account> chunk = new List<Account>();
for (Integer i = 0; i < chunkSize; i++) {
Account a = remaining.remove(0);
a.Description = 'Processed';
chunk.add(a);
}
update chunk;
if (!remaining.isEmpty() && !Test.isRunningTest()) {
System.enqueueJob(new ChunkedUpdateJob(remaining));
}
}
}The test proves that one link does its work. To prove the whole chain, test the execute logic directly on small inputs, or test each step class on its own.
Common mistakes
- Enqueueing two children from one
execute. The second call throws. If you need two parallel tasks, start both from a synchronous transaction. - No stop condition. A chain that always enqueues another link runs until it hits a limit or you abort it. Always check that work remains.
- Carrying large state. A list of 10,000 sObjects serialized into every link slows each enqueue. Pass Ids and re-query.
- Enqueueing before the risky work. Put
System.enqueueJobafter DML and callouts, so a failure does not leave a child running against incomplete data. - Expecting the child to start at once. The child waits in the async queue, so other jobs can run in between. Do not assume it starts within a fixed time.
Exercise
A Queueable job's execute method calls System.enqueueJob for job B and then, a few lines later, for job C. What happens, and how would you restructure the work so that B and C both run after the current job?
Show answer
The second System.enqueueJob call throws a LimitException, because a job running asynchronously can enqueue only one child. To run both, chain them in a line: the current job enqueues B, and B's execute enqueues C when it finishes. If B and C are independent and do not need to run in order, enqueue both from a synchronous transaction instead, where up to 50 jobs are allowed.
Exercise
You chain 200 Queueable jobs in a Developer Edition org and the enqueue fails partway through. Why, and what two measures make a chain safe to run in a production org?
Show answer
Developer Edition and trial orgs cap the stack depth at 5, so the sixth link cannot be enqueued. In production, where depth is not capped by the platform, make the chain safe with a clear stop condition (stop when no work remains) and a cap you set yourself, such as AsyncOptions.MaximumQueueableStackDepth combined with AsyncInfo.hasMaxStackDepth(). Re-querying records by Id instead of carrying sObjects also keeps each link small.