Sub topic 11
Moving heavy work to Queueable and Batch Apex
This chapter assumes you can write a bulkified trigger and know the basic per-transaction limits. Bulkification keeps one transaction under its limits. Some work is too big for any single synchronous transaction, so you need to move it to asynchronous Apex.
Why asynchronous Apex helps
Asynchronous Apex runs later, in its own transaction, with its own limits. Several limits are also higher than in synchronous code. The table shows typical values. Limits change between releases, so check the Apex Developer Guide for current numbers.
| Limit | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries | 100 | 200 |
| CPU time | 10,000 ms | 60,000 ms |
| Heap size | 6 MB | 12 MB |
The trade-off is timing. The user does not wait for the result, and you cannot assume the work has finished when the original transaction commits.
Choosing a tool
- Queueable Apex suits a single job that is too heavy or slow to run inline. Examples are a callout after a save or a moderate amount of follow-up processing. You pass in data through the constructor, including sObjects and other non-primitive types.
- Batch Apex suits large data sets. It splits the records into chunks and runs each chunk as its own transaction with fresh limits.
A Queueable job
A trigger can hand off work after the records are saved. Pass Ids, not stale records, and query inside the job.
public class AccountFollowUpJob implements Queueable {
private List<Id> accountIds;
public AccountFollowUpJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Task> tasks = new List<Task>();
for (Account a : [SELECT Id FROM Account WHERE Id IN :accountIds]) {
tasks.add(new Task(WhatId = a.Id, Subject = 'Follow up'));
}
if (!tasks.isEmpty()) {
insert tasks;
}
}
}trigger AccountAfter on Account (after insert) {
System.enqueueJob(new AccountFollowUpJob(new List<Id>(Trigger.newMap.keySet())));
}The trigger enqueues one job for the whole batch, not one job per record. A transaction can enqueue only a limited number of jobs, so enqueueing inside a loop is another limit risk.
A Batch job
Batch Apex has three methods. start defines the records, execute processes each chunk, and finish runs once at the end.
public class AccountIndustryBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id, Industry FROM Account');
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
if (a.Industry == null) {
a.Industry = 'Other';
}
}
update scope;
}
public void finish(Database.BatchableContext bc) {}
}
// Start it with a chunk size of 200 records:
// Database.executeBatch(new AccountIndustryBatch(), 200);Returning a Database.QueryLocator lets the job cover far more rows than a normal query could return. Each execute call gets its own limits, so a million records become many small, safe transactions. The code inside execute must still be bulkified. A query or DML statement inside the loop over scope fails in the same way as in a trigger.
The second argument to executeBatch is the chunk size. Lower it if each record needs heavy processing and a chunk hits the CPU limit.
Common errors
- Starting async work from async work without care. A Batch job's
executemethod can enqueue only one Queueable job. Chained Queueable jobs are allowed, but each job should add at most one child. - Assuming order or immediacy. Jobs wait in a queue. Do not write code that expects the result right after
enqueueJob. - Using async to hide a bug. Moving a query-in-a-loop into a Queueable job only raises the ceiling from 100 to 200 queries. Bulkify first, then move work.
- Passing large state. Everything in the job's member variables counts against heap when it is serialized and loaded. Pass Ids and re-query.
Exercise
A trigger needs to update 50,000 Accounts after a nightly data load, and doing it inline hits the CPU time limit. Which tool fits best, and why?
Show answer
Batch Apex. The data set is large, and Batch splits it into chunks. Each execute call runs as its own transaction with fresh governor limits. A Queueable job would still process everything in one transaction, so it could hit the same row and CPU limits.