Sub topic 8
Working through a large list one slice at a time
A single transaction can't always handle every record you need to change. A queueable job gets fresh limits for each run, but one run still has a ceiling. Chunking means each run processes one slice of the data and then enqueues a new job for the rest. This chapter shows how to build that pattern, what limits shape it, and where it breaks.
This chapter assumes you can write a Queueable class and enqueue it with System.enqueueJob. It also assumes you know how chaining works (one job enqueuing another) and the basic governor limits for SOQL and DML.
Why slice the work
Suppose you must update 50,000 accounts. If you pass all the IDs to one queueable, the job tries to do everything in one transaction. It can hit the 10,000-row DML limit, the heap limit, or the CPU limit, and the job fails with an uncatchable limit exception.
Slicing avoids this. Each job does a bounded amount of work, so each run stays well inside its limits. Because every run is a separate transaction, a failure affects only the current slice, and the slices that already committed stay committed.
| Approach | Work per transaction | Failure effect |
|---|---|---|
| One job for all records | Everything | All changes roll back |
| Chained job, one slice per run | One slice | Only the current slice rolls back |
The pattern
A chunking job holds the IDs still to process. On each run it does four things:
- Splits the list into a current slice and a remainder.
- Processes the current slice.
- Commits the DML.
- Enqueues one new job with the remainder, if any is left.
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));
}
}
}You start the chain once, from any Apex code:
List<Id> ids = new List<Id>(new Map<Id, Account>([SELECT Id FROM Account]).keySet());
Id firstJobId = System.enqueueJob(new AccountChunkJob(ids));The loop is the heart of the class. The first n IDs go to current, and everything else goes to rest. The terminating condition is rest.isEmpty(): when no IDs remain, the job does not enqueue a child, and the chain ends.
Choosing the slice size
CHUNK_SIZE = 200 is a starting point, not a rule. The right number depends on what each record costs to process. Check these limits for one asynchronous run:
| Limit | Asynchronous value |
|---|---|
| SOQL queries | 200 |
| Records retrieved by SOQL | 50,000 |
| DML rows | 10,000 |
| CPU time | 60,000 ms |
| Heap size | 12 MB |
Work out which limit your per-record logic consumes fastest. If each record triggers a callout, the callout limit (100 per transaction) caps your slice at fewer than 100 records. If each record runs heavy calculations, CPU time is the constraint. If the slice is too small, you pay for many more jobs than you need. If it is too large, you risk a limit failure.
Limits on chaining
Chunking depends on a job being able to enqueue its successor. The rules differ by where the enqueue happens.
- From a synchronous context such as a trigger or controller, you can enqueue up to 50 jobs in one transaction.
- From inside a running queueable (or a batch
execute), you can enqueue only one child job. - There is no fixed limit on chain depth in most orgs. Developer Edition and trial orgs cap the depth at 5.
The one-child rule is why the code above enqueues a single job carrying the whole remainder. It does not enqueue one job per slice. If you tried to enqueue several children from execute, the second System.enqueueJob call would throw a LimitException.
A cursor-based variation
The version above carries the entire remaining ID list in a member variable. That list is serialized with the job every time it is enqueued. For 50,000 IDs, each hand-off copies and stores a large list, and the cost shrinks only slowly as the list shortens.
An alternative is to carry a cursor: the last ID processed. Each run queries the next slice directly.
public class AccountCursorJob implements Queueable {
private static final Integer CHUNK_SIZE = 200;
private Id lastId;
public AccountCursorJob(Id lastId) {
this.lastId = lastId;
}
public void execute(QueueableContext context) {
List<Account> accounts;
if (lastId == null) {
accounts = [SELECT Id, Description FROM Account ORDER BY Id LIMIT :CHUNK_SIZE];
} else {
accounts = [SELECT Id, Description FROM Account WHERE Id > :lastId ORDER BY Id LIMIT :CHUNK_SIZE];
}
if (accounts.isEmpty()) {
return;
}
for (Account a : accounts) {
a.Description = 'Processed';
}
update accounts;
if (accounts.size() == CHUNK_SIZE && !Test.isRunningTest()) {
System.enqueueJob(new AccountCursorJob(accounts[accounts.size() - 1].Id));
}
}
}You start it with System.enqueueJob(new AccountCursorJob(null));.
The trade-offs are these:
- The job state is one ID, so it stays tiny no matter how large the data set is.
- The query runs on every slice, which costs one SOQL query per run.
- Records created or deleted while the chain runs change what later slices see. The ID list version works on a fixed snapshot, so it never picks up new records.
- A full slice means more records may exist. If the final slice happens to be exactly 200 records, the chain runs one more job that finds nothing and stops.
Use the ID list when you need a fixed snapshot or have a filtered list that is hard to re-query. Use the cursor when the set is large and a simple ORDER BY Id expresses it.
Common errors
- Enqueuing inside the loop. Calling
System.enqueueJobonce per slice fromexecutebreaks the one-child rule. Enqueue exactly once, after the work, with the remainder. - Missing termination condition. If the job enqueues a child unconditionally, the chain never stops. Always test that work remains before enqueuing.
- Enqueuing before the DML. Enqueue the child after
updatesucceeds. If the DML throws, the exception rolls back the transaction, including the enqueue, so a failed slice does not start the next one. Enqueuing earlier makes that behavior harder to reason about. - Assuming the chain is atomic. Slices commit independently. If slice 40 fails, slices 1 to 39 stay committed. The chain stops there, and nothing automatically resumes it. Chapter material on finalizers covers how to detect and retry such failures.
- A slice that is silently too big. A trigger on the object runs for every DML, and its cost counts against the same transaction. A slice that is fine in a bare org can fail in one with heavy automation.
Following the chain
Each job in the chain is a separate row in AsyncApexJob with its own ID. The first enqueueJob returns the ID of the first job only. To watch progress, query by class name:
List<AsyncApexJob> jobs = [
SELECT Id, Status, NumberOfErrors, CreatedDate
FROM AsyncApexJob
WHERE ApexClass.Name = 'AccountChunkJob'
ORDER BY CreatedDate DESC
LIMIT 20
];
for (AsyncApexJob j : jobs) {
System.debug(j.Id + ' ' + j.Status + ' errors=' + j.NumberOfErrors);
}A healthy chain shows a run of Completed rows with the newest one Queued, Preparing, or Processing. A Failed row marks where the chain broke.
Exercise
A queueable's execute method contains a loop that calls System.enqueueJob once for each slice of a 10,000-record list. It throws a LimitException when run from a queueable. Why, and how do you fix it?
Show answer
A running queueable can enqueue only one child job, so the second System.enqueueJob call in the loop exceeds the limit. Fix it by processing one slice per run and enqueuing a single child job with the remaining records (or a cursor) after the slice's DML completes.
Exercise
You use the cursor-based job on an object where records are inserted while the chain runs, and you need every record processed exactly as of the start time. Which design fits better, the ID list or the cursor, and why?
Show answer
The ID list. It is captured once when the first job is enqueued, so the set of records is fixed. The cursor job re-queries on every slice and would pick up records inserted after the start, so it does not process an exact snapshot.
Exercise
Each record in your slice requires one HTTP callout. What is the largest safe slice size, and which limit sets it?
Show answer
The limit of 100 callouts per transaction sets it, so a slice must stay below 100 records, for example 90 to leave a margin. The class must also implement Database.AllowsCallouts for the callouts to be allowed.