Sub topic 7
Limits that apply to enqueuing and chaining
This chapter assumes you know Apex governor limits and transactions, can write a basic Queueable class, and have seen a job enqueue a child job. Here you will learn the limits that decide how many jobs you can enqueue, how deep a chain can go, and what happens when you hit a limit.
Two contexts, two rules
The limit on enqueuing depends on where System.enqueueJob is called. Salesforce treats these two cases differently:
- Synchronous context. This covers triggers, controllers, anonymous Apex, REST handlers, and anything else a user or API call starts directly. The transaction can enqueue up to 50 jobs.
- Asynchronous context. This covers
executein a queueable, a batch method, or a future method. The running job can enqueue only one child job.
The second rule is what makes chaining a one-at-a-time pattern. A chain is a line of jobs, not a tree. If one execute call needs to start several jobs, it can't.
The limits at a glance
| Limit | Value | What happens when exceeded |
|---|---|---|
| Jobs enqueued in a synchronous transaction | 50 | `System.LimitException: Too many queueable jobs added to the queue: 51` |
| Child jobs enqueued from one queueable `execute` | 1 | `System.LimitException: Too many queueable jobs added to the queue: 2` |
| Chain depth in Developer Edition and Trial orgs | 5 (the first job plus 4 children) | `System.AsyncException: Maximum stack depth has been reached.` |
| Chain depth in other orgs | No fixed limit | Not applicable |
| Async Apex executions per 24 hours | 250,000, or 200 times the number of user licenses, whichever is greater | New async work fails until the window rolls over |
The daily number is shared by all async Apex: queueable, batch, future, and scheduled. A chain of 1,000 jobs uses 1,000 of those executions, so a runaway chain can use up capacity other features need.
Check current numbers in the Apex Developer Guide before you rely on them. Salesforce changes limits between releases.
Enqueue limit in synchronous code
The 50-job cap bites when you enqueue inside a loop. A trigger that fires for 200 records and enqueues one job per record fails on the 51st. The rule is the same as for SOQL and DML in loops: collect the work, then enqueue once.
Often one job that takes a list is the right answer. Use that when the work fits in one job's limits. When it doesn't, slice the list and enqueue slices up to the cap. The next example stops before the limit and returns the slices it couldn't start.
public class SliceDispatcher {
public static List<List<Id>> enqueueSlices(List<List<Id>> slices) {
List<List<Id>> notStarted = new List<List<Id>>();
for (List<Id> slice : slices) {
if (Limits.getQueueableJobs() >= Limits.getLimitQueueableJobs()) {
notStarted.add(slice);
} else {
System.enqueueJob(new AccountRatingJob(slice));
}
}
return notStarted;
}
}Limits.getQueueableJobs() returns how many jobs this transaction has already enqueued. Limits.getLimitQueueableJobs() returns the cap for the current context. In an async context the cap is 1, so the same check also protects chained code.
What to do with notStarted is a design decision. You can log it, store the IDs in a custom object for a later run, or hand them to a single chained job.
One child per execution
Because a queueable may enqueue only one child, a chain that needs to continue must make that call exactly once, and only when there is more work. Two common mistakes:
- Enqueuing in a loop inside
execute. The secondSystem.enqueueJobcall throws, and the exception rolls back the wholeexecutetransaction, including DML that had already succeeded. - Enqueuing unconditionally. A job that always enqueues a successor never ends. Each link needs an exit condition, such as an empty remainder.
A LimitException can't be caught. Catching it in a try/catch block does not stop the transaction from failing. So the guard has to come before the call, using the Limits methods or your own state.
Chain depth
In Developer Edition and Trial orgs, the chain stops at depth 5. The initial job is depth 1, and its child is depth 2. Attempting a sixth enqueue throws an AsyncException. Production and sandbox orgs on other editions have no fixed depth limit.
An unlimited chain is not always a good chain. Depth problems show up in three ways:
- Runaway loops. A bug in the exit condition keeps the chain alive and burns the daily execution allowance.
- Slow throughput. Jobs in a chain run one after another. A chain of 500 jobs is 500 sequential waits in the queue, with no parallelism.
- Hard to monitor. Each link is its own
AsyncApexJobrow, with no built-in parent record that groups the chain.
The following job carries its own depth counter. It stops itself instead of relying on org limits.
public class BoundedChainJob implements Queueable {
private static final Integer MAX_DEPTH = 50;
private List<Id> remaining;
private Integer depth;
public BoundedChainJob(List<Id> remaining, Integer depth) {
this.remaining = remaining;
this.depth = depth;
}
public void execute(QueueableContext context) {
Integer n = Math.min(200, 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 at depth ' + depth;
}
update accounts;
if (rest.isEmpty()) {
return;
}
if (depth >= MAX_DEPTH) {
System.debug(LoggingLevel.ERROR,
'Chain stopped at depth ' + depth + '. Unprocessed: ' + rest.size());
return;
}
if (!Test.isRunningTest()) {
System.enqueueJob(new BoundedChainJob(rest, depth + 1));
}
}
}Start it with System.enqueueJob(new BoundedChainJob(ids, 1));. The cap of 50 is an example. Choose a number that fits your data volume and your tolerance for a long chain.
The AsyncOptions class, covered in a later chapter, can enforce a depth cap for you with MaximumQueueableStackDepth. It is the better tool when the cap should apply no matter who writes the code that enqueues the job.
Limits inside each job
Every queueable execute is its own transaction with its own governor limits. Asynchronous limits are higher than synchronous ones:
- SOQL queries: 200 per transaction, instead of 100.
- Heap size: 12 MB, instead of 6 MB.
- CPU time: 60,000 ms, instead of 10,000 ms.
- DML statements, DML rows, and callouts: the same as in synchronous code (150, 10,000, and 100).
Fresh limits for each link are the reason to chain at all. They are also the reason a slice size should be chosen by the heaviest thing a slice does. A job that makes one callout per record can't process 200 records, because that would be 200 callouts and the cap is 100.
Limits in tests
Tests add a rule of their own. A test can't run a chain to completion: when a queueable enqueues a child while a test is running, the platform throws a stack-depth error. This is why the chain examples guard the child enqueue with Test.isRunningTest(). The testing chapter shows how to verify chain behavior without that guard getting in the way.
A checklist before shipping a chain
- Does the context that calls
enqueueJobenqueue at most 50 jobs, even for 200-record trigger batches? - Does each
executecallenqueueJobat most once, on every code path? - Is there an exit condition that is reached for every input, including empty ones?
- Is there a depth cap, in your code or in
AsyncOptions? - Does one slice fit within the per-job limits for the heaviest operation it does?
- Is the total number of jobs well below your daily async allowance?
Exercise
A trigger on Contact fires for a batch of 200 records. The developer's handler loops over the records and calls System.enqueueJob(new SyncJob(c.Id)) once per record. What happens, and how should the handler be changed?
Show answer
The 51st call throws an uncatchable System.LimitException ("Too many queueable jobs added to the queue: 51"), and the whole trigger transaction rolls back. Collect the IDs in a list and enqueue one SyncJob that takes the list. If the work is too heavy for one job, split the list into slices, enqueue at most 50 jobs, and give the rest to a chained job.
Exercise
A queueable's execute method processes a slice and then enqueues two jobs: one to send email and one to process the next slice. What goes wrong, and what are two ways to fix it?
Show answer
The second System.enqueueJob call throws a LimitException because an async context may enqueue only one child. The exception rolls back the whole execute transaction. Fix it by combining the work into one child job, or by running the email step in the same execute (or in a finalizer). Another option is to enqueue the email job from a synchronous starting point instead.