How does Queueable job chaining work, and what are the platform limits associated with it?
Answer
Basics: Chaining lets you run steps in sequence, each in a fresh transaction with fresh async limits, for example fetch, then transform, then update.
How it works: In execute(QueueableContext), call System.enqueueJob(new NextStep(state)). The next job starts after the current one completes. State is passed through the constructor and non-transient member variables are serialised. Each job gets async limits (60,000 ms CPU, 12 MB heap, 200 SOQL).
Advanced / deep dive: Original claims that "5 chains in sync contexts" are incorrect: the limits are 50 enqueues per synchronous transaction, one child from an executing queueable, and the 5-depth cap only applies to Developer Edition and trial orgs. Use AsyncOptions with MaximumQueueableStackDepth to cap runaway recursion, and AsyncInfo.getCurrentQueueableStackDepth() to check depth. Use System.attachFinalizer for post-processing, which runs even if the job fails with an unhandled exception, enabling retries and logging. Callouts need Database.AllowsCallouts. Chaining in tests is not allowed: only the first job runs, so guard the enqueue with Test.isRunningTest or design tests per step. To process large data, prefer Batch; chains are best for orchestration of a few steps.
Code / config example:
public class StepOne implements Queueable {
public void execute(QueueableContext ctx) {
// ... do step one work ...
(!Test.isRunningTest()) {
System.enqueueJob( ());
}
}
}