Sub topic 13
When to Use Batch Apex for Callouts
This chapter assumes you can write an Apex trigger, know the basic governor limits, and have read the earlier chapters on future methods and Queueable callouts. Here you will see when a Batch Apex job is a better fit than a Queueable job for callouts that start in a trigger.
What Batch Apex adds
Batch Apex splits a large set of records into chunks. Each chunk runs in its own transaction, so each one gets a fresh set of governor limits, including its own callout limit of 100 per transaction.
A batch class implements Database.Batchable<sObject>. To make callouts, it must also implement Database.AllowsCallouts. Without that interface, the callout fails at runtime.
A batch job has three methods:
startreturns the records to process, usually as aDatabase.QueryLocator.executeruns once per chunk. The callout goes here.finishruns once at the end. Use it for summaries or to chain another job.
A batch class that makes callouts
This example sends accounts that are not yet synced to the billing API. The scope size is small, so each chunk makes one callout and stays well within limits.
public class AccountSyncBatch implements Database.Batchable<SObject>, Database.AllowsCallouts {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id, Name FROM Account WHERE Name != null LIMIT 50000'
);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
List<Map<String, Object>> payload = new List<Map<String, Object>>();
for (Account a : scope) {
payload.add(new Map<String, Object>{ 'id' => a.Id, 'name' => a.Name });
}
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(payload));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR, 'Batch sync failed: ' + res.getStatusCode());
}
}
public void finish(Database.BatchableContext bc) {
System.debug('Account sync batch finished');
}
}You start it with Database.executeBatch. The second argument is the scope size, the number of records per chunk. The default is 200.
Id jobId = Database.executeBatch(new AccountSyncBatch(), 100);Starting a batch from a trigger
A trigger can call Database.executeBatch, but doing so for every insert is usually a mistake. Only 5 batch jobs can be queued or active at once, and the rest wait in the Apex flex queue (up to 100 jobs). A trigger that fires on many small saves can fill that queue quickly.
Batch fits best in these cases:
- The work is a scheduled or on-demand sweep over many records, such as a nightly resync.
- A trigger only flags records, for example by setting
Needs_Sync__c = true, and a scheduled batch picks them up later. - The volume is far above what one transaction handles. A Queueable job is still one transaction, with one set of limits.
Limits to remember
| Limit | Value |
|---|---|
| Callouts per transaction | 100 |
| Batch jobs queued or active | 5 |
| Flex queue size | 100 |
| Default scope size | 200 |
A batch job cannot be started from another batch job's execute method. Chain the next job from finish instead.
Exercise
A trigger on Account must sync each new record to an external API as soon as possible, and typical saves insert one to ten records. Should you use Batch Apex? Give one reason.
Show answer
No. Use a Queueable job. Batch Apex has only 5 active job slots and a slower start, so a job per save would crowd the queue. Batch fits scheduled sweeps over many records, not an immediate sync of a few.