Sub topic 11
Moving heavy work to Queueable and Batch Apex
This chapter assumes you can write bulkified triggers with Sets, Maps and Lists, and that you know the per-transaction limits from earlier chapters. You should also be comfortable with @IsTest classes and Test.startTest() and Test.stopTest().
Bulkification keeps one transaction inside its limits. Sometimes the work is too large for any single transaction, even a well-written one. Examples are recalculating a field on a million Accounts, or running logic that needs a lot of CPU time. Asynchronous Apex handles these cases by running the work outside the user's transaction, in one or more new transactions that each get their own limits.
Why asynchronous Apex has more room
Each asynchronous execution is a separate transaction. Some of its limits are higher than the synchronous ones, and the others are the same. Check the current values in the Apex Developer Guide, because Salesforce can change them.
| Limit | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries | 100 | 200 |
| CPU time | 10,000 ms | 60,000 ms |
| Heap size | 6 MB | 12 MB |
| DML statements | 150 | 150 |
| Records retrieved by SOQL | 50,000 | 50,000 |
| DML rows | 10,000 | 10,000 |
Async code is not exempt from the other limits. The 50,000 rows and 10,000 DML rows still apply to each transaction. Async Apex works for large data sets because it can split the work across many transactions. It does not work because any one transaction may do more.
Async Apex also changes the user's experience. The user's save finishes quickly, and the heavy work completes later. The user cannot see the result immediately, and the work can fail without the user seeing the error. Plan for that.
Choosing between Queueable and Batch
Two tools cover most heavy work.
- Queueable Apex runs one job in the background. You pass it state through its constructor. It can be enqueued from a trigger, it accepts non-primitive types such as SObjects and custom classes, and it can chain to a follow-up job.
- Batch Apex reads a large record set and processes it in chunks. Each chunk runs in its own transaction. The platform manages the iteration for you.
The rule of thumb is to use Queueable when you already hold the Ids or records to process, and Batch when you need to walk through a large data set from a query.
Queueable Apex
A Queueable class implements the Queueable interface and has one method, execute. Pass the records or Ids you need through the constructor and store them in fields.
public class AccountIndustryJob implements Queueable {
private final Set<Id> accountIds;
public AccountIndustryJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [
SELECT Id, Industry
FROM Account
WHERE Id IN :accountIds AND Industry = NULL
];
for (Account a : accounts) {
a.Industry = 'Other';
}
if (!accounts.isEmpty()) {
update accounts;
}
}
}The job is bulkified like any other Apex. It makes one query and one DML statement for any number of Ids.
Enqueue it from a trigger with System.enqueueJob. Pass the whole collection of Ids from the trigger batch, never one job per record.
trigger AccountAfter on Account (after insert) {
if (!Trigger.newMap.isEmpty()) {
System.enqueueJob(new AccountIndustryJob(Trigger.newMap.keySet()));
}
}Trigger.newMap is available in after triggers, so its keySet() gives you a Set<Id>.
Queueable limits to remember
- A synchronous transaction can enqueue at most 50 jobs. Enqueueing a job inside a loop will hit this limit quickly.
- An executing Queueable job can enqueue only one child job.
- Jobs are not guaranteed to run at a particular time. They wait in the queue until a worker is available.
- A job cannot make a callout unless it implements
Database.AllowsCallouts.
Chaining jobs
When a data set is too big for one job, you can process a slice and enqueue the next job at the end of execute. This is called chaining.
public class SliceProcessor implements Queueable {
private final List<Id> remainingIds;
private static final Integer SLICE_SIZE = 2000;
public SliceProcessor(List<Id> remainingIds) {
this.remainingIds = remainingIds;
}
public void execute(QueueableContext context) {
Integer sliceEnd = Math.min(SLICE_SIZE, remainingIds.size());
List<Id> current = new List<Id>();
for (Integer i = 0; i < sliceEnd; i++) {
current.add(remainingIds[i]);
}
List<Account> accounts = [
SELECT Id, Industry FROM Account WHERE Id IN :current
];
for (Account a : accounts) {
if (a.Industry == null) {
a.Industry = 'Other';
}
}
update accounts;
List<Id> rest = new List<Id>();
for (Integer i = sliceEnd; i < remainingIds.size(); i++) {
rest.add(remainingIds[i]);
}
if (!rest.isEmpty()) {
System.enqueueJob(new SliceProcessor(rest));
}
}
}Chaining works, but it is hand-built iteration. If you find yourself writing a loop of chained jobs over a query result, Batch Apex is usually the better fit.
Batch Apex
A batch class implements Database.Batchable<SObject> and has three methods.
startreturns the records to process, usually aDatabase.QueryLocator.executereceives one chunk of records, called the scope, and runs once per chunk. Each call is its own transaction with its own limits.finishruns once at the end. Use it for summary work, such as sending a notification.
A query locator can return up to 50 million records, which is far above the normal 50,000-row limit. That limit applies to the query in start only when you return an Iterable instead of a locator.
Here is a batch class that tracks its results across chunks. Instance variables are reset between execute calls unless the class implements Database.Stateful.
public class AccountIndustryBatch implements Database.Batchable<SObject>, Database.Stateful {
private Integer updatedCount = 0;
private Integer failedCount = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id, Industry FROM Account WHERE Industry = NULL'
);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Industry = 'Other';
}
List<Database.SaveResult> results = Database.update(scope, false);
for (Database.SaveResult sr : results) {
if (sr.isSuccess()) {
updatedCount++;
} else {
failedCount++;
}
}
}
public void finish(Database.BatchableContext bc) {
System.debug('Updated: ' + updatedCount + ', failed: ' + failedCount);
}
}Database.update(scope, false) allows partial success. One bad record does not roll back the whole chunk. Without the false, any failure would roll back every record in that chunk's transaction.
Start the job with Database.executeBatch. The second argument is the chunk size.
Id jobId = Database.executeBatch(new AccountIndustryBatch(), 200);
System.debug('Batch job Id: ' + jobId);The default chunk size is 200 and the maximum is 2,000. Choose the size by what each record costs. Lower it to 50 or 100 when execute does heavy CPU work, callouts or many related queries. Raise it only when each record is cheap to process.
Batch limits to remember
- Up to five batch jobs can be queued or active at once. More wait in a holding queue called the flex queue, which holds up to 100 jobs.
Database.Statefulmakes the job serialize its state after each chunk, which adds overhead. Use it only for counters, error lists and similar small values.- Chunks are not guaranteed to run in order, and you cannot rely on a chunk finishing before the next starts in any strict sense. Do not write code that depends on that.
- Callouts from
executeneedDatabase.AllowsCalloutsin the class declaration. - Calling
Database.executeBatchfrom a trigger is possible but risky. A bulk load can try to start many jobs. Prefer a Queueable job that starts the batch, or a check that no job is already running.
Comparing the two
| Question | Queueable | Batch |
|---|---|---|
| Typical size | Known set, up to a few thousand records | Thousands to millions of records |
| Input | Constructor arguments, including SObjects | A query locator or iterable |
| Per-chunk transaction | One transaction per job | One transaction per chunk |
| Can be started from a trigger | Yes | Possible, but needs care |
| Monitoring | `AsyncApexJob`, Apex Jobs page | `AsyncApexJob`, Apex Jobs page |
| Chaining | One child job per execution | `finish` can start another batch |
Testing asynchronous code
Async jobs in a test run only when Test.stopTest() executes. Everything enqueued between startTest and stopTest runs synchronously at the stopTest call, so your assertions come after it.
@IsTest
private class AccountIndustryBatchTest {
@IsTest
static void fillsMissingIndustry() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Batch Test ' + i));
}
insert accounts;
Test.startTest();
Database.executeBatch(new AccountIndustryBatch(), 200);
Test.stopTest();
System.assertEquals(
200,
[SELECT COUNT() FROM Account WHERE Industry = 'Other' AND Name LIKE 'Batch Test %']
);
}
}A test can run only one chunk of a batch job. For that reason, tests should use at most 200 records, the default scope size. A Queueable test follows the same shape. Insert the data, then call System.enqueueJob(...) or fire the trigger between startTest and stopTest, and assert after stopTest.
Edge cases and common errors
- Too many queueable jobs: 51. A loop that calls
System.enqueueJobfor each record fails once it passes 50 jobs. Collect Ids and enqueue one job. - Serialization surprises. Queueable fields are serialized when the job is enqueued. The job sees the data as it was at enqueue time, not as it is when the job runs. Query fresh records inside
executeif another transaction may have changed them. - Recursion through async. A Queueable that updates Accounts can fire the same trigger that enqueued it, which enqueues another job. Use a guard such as a static flag, or check that a field actually needs changing before you update it. The next chapter covers recursion control.
- Silent failures. An unhandled exception in an async job does not show a message to the user. Check
AsyncApexJobfor status andNumberOfErrors, and log failures fromexecuteandfinish. - Mixed DML and setup objects. Updating a setup object such as a User and a non-setup object like an Account in the same transaction raises an error. Putting one of them in a Queueable job is the standard fix.
Exercise
A trigger on Contact calls System.enqueueJob(new ContactSyncJob(c.Id)) inside a for loop over Trigger.new. A user imports 120 contacts in one transaction. What happens, and how do you fix it?
Show answer
The transaction fails with a limit exception after the 50th job, because a synchronous transaction can enqueue at most 50 Queueable jobs. Fix it by collecting the Ids into a Set<Id> inside the loop (or using Trigger.newMap.keySet()), then enqueueing a single job after the loop with System.enqueueJob(new ContactSyncJob(ids)). The job's constructor takes the Set, and its execute method does one bulkified query and one DML statement.
Exercise
You must set a default value on 3 million Account records. Should you use Queueable or Batch Apex, which chunk size is a reasonable starting point, and how do you keep a count of failures across chunks?
Show answer
Use Batch Apex, because the data set is far too large for one transaction and a query locator can return up to 50 million records. Start with the default chunk size of 200 and lower it if execute is CPU heavy. Implement Database.Stateful and increment a counter field for each failed Database.SaveResult returned by Database.update(scope, false). Report the total in finish.