Sub topic 8
Working through a large list one slice at a time
This chapter assumes you can write a Queueable class, pass state through its constructor, and enqueue a job from another job. You should also know that each queueable runs in its own transaction with fresh governor limits.
Why slice the list
A single queueable gets one transaction's limits. For example, a synchronous-style budget of 100 SOQL queries and 10,000 DML rows is shared by everything the job does. If you pass 50,000 record IDs to one job, it will probably hit a limit and fail.
The fix is to give each job a bounded amount of work. The job processes one slice and then enqueues a single child job for the rest. Each child starts a new transaction, so the limits reset every time.
The pattern
The job below keeps the remaining IDs in a member variable. Each run takes up to 200 IDs, updates those accounts, and passes the leftover IDs to a new instance of itself.
public class AccountChunkJob implements Queueable {
private static final Integer CHUNK_SIZE = 200;
private List<Id> remaining;
public AccountChunkJob(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()) {
System.enqueueJob(new AccountChunkJob(rest));
}
}
}Start the work once, from any Apex code:
Id firstJobId = System.enqueueJob(new AccountChunkJob(allAccountIds));How it runs
Three details make this work:
- One child per job. A queueable can enqueue only one child from an asynchronous context, so the chain is a line, not a tree.
- State travels in the constructor. The
restlist becomes the child'sremaining. Nothing is shared between jobs except what you pass. - The stop condition is the empty list. When
restis empty, no child is enqueued and the chain ends.
Choosing a slice size
The slice size trades speed against safety. A larger slice means fewer jobs but a greater chance of hitting a limit. Pick a size from the heaviest work done per record. If each record triggers a callout, the 100-callout limit forces a much smaller slice than 200. If a trigger on the object does extra queries, leave room for those as well.
Also keep the stored list small. Every job serializes its member variables when it is enqueued, so a list of IDs is cheap but a list of full records with many fields is not.
Common errors
- No stop condition. If you enqueue a child every time, even with an empty list, the chain never ends.
- Chaining inside a test. Tests allow only one queueable to run, so a job that enqueues a child throws a stack-depth error. The
Test.isRunningTest()guard avoids this. It also means the test covers only the first slice, so keep test data under one slice or test the slicing logic separately. - Ignoring failure. If one job throws an unhandled exception, the chain stops and the remaining IDs are lost. A finalizer, covered in later chapters, can re-enqueue the work.
Exercise
In AccountChunkJob, a caller passes 450 account IDs. How many jobs run in total, and how many records does each job update (assuming all IDs exist)?
Show answer
Three jobs run. The first updates 200 records, the second updates 200, and the third updates the last 50. After the third job, the rest list is empty, so no child is enqueued.
Exercise
Why does the code check !Test.isRunningTest() before enqueuing the child job?
Show answer
A test can run only one level of queueable. Enqueuing a child from a running queueable in a test throws a stack-depth error, so the guard skips the chaining while tests run.