Sub topic 13
When to use Batch Apex for callouts
This chapter assumes you can write Apex triggers and Queueable classes. It also assumes you know the transaction limits from earlier chapters. You will see when Batch Apex is a better fit than a future method or a Queueable job for callouts. You will also see how to build a batch job that makes callouts safely.
What Batch Apex adds
Batch Apex splits a large set of records into chunks called scopes. Each scope runs in its own transaction through the execute method. Because every execute call is a fresh transaction, it gets a fresh set of governor limits, including a fresh budget of 100 callouts.
A batch class implements three methods:
startselects the records, usually withDatabase.getQueryLocator. A query locator can return up to 50 million records.executereceives one scope, 200 records by default and at most 2,000, and processes it.finishruns once after all scopes complete. Use it for summaries, notifications, or chaining another job.
A batch class can make callouts only if it also implements Database.AllowsCallouts. Without that interface, the callout throws an exception at runtime. This is the same rule that applies to Queueable classes.
Why not just call a batch from the trigger?
You can call Database.executeBatch from a trigger. It is usually a poor fit for per-record work, for these reasons:
- Only 5 batch jobs can be queued or active at once. Extra jobs wait in the Flex Queue, which holds up to 100 jobs.
- A trigger transaction can start many jobs if several saves happen close together, such as a data load in many chunks.
- Batch startup is slower than a Queueable. It is not meant for "do this one thing right now".
So a trigger that starts one batch job per insert does not scale. Batch Apex fits when the work is a large backlog, not an event.
The pending-flag pattern
The usual design for triggers and batch callouts has three steps:
- The trigger does no callout and starts no job. It only marks records as needing work, for example by setting a custom field
Billing_Sync_Status__ctoPending. - A scheduled job starts a batch every few minutes or hours.
- The batch queries
Pendingrecords, calls the external service, and writes backSyncedorFailed.
The status field is the queue, so work survives failures and can be retried. This chapter assumes a text field Billing_Sync_Status__c exists on Account. You could also set the field with a record-triggered flow or a default value.
A batch class with callouts
This batch sends one bulk request per scope. It uses the Named Credential Billing_API from earlier chapters.
public class AccountSyncBatch implements
Database.Batchable<SObject>, Database.AllowsCallouts, Database.Stateful {
private Integer syncedCount = 0;
private Integer failedCount = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Name FROM Account WHERE Billing_Sync_Status__c = 'Pending'
]);
}
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.setTimeout(20000);
req.setBody(JSON.serialize(payload));
Boolean ok = false;
try {
HttpResponse res = new Http().send(req);
ok = res.getStatusCode() >= 200 && res.getStatusCode() < 300;
} catch (CalloutException e) {
System.debug(LoggingLevel.ERROR, 'Callout failed: ' + e.getMessage());
}
for (Account a : scope) {
a.Billing_Sync_Status__c = ok ? 'Synced' : 'Failed';
}
update scope;
if (ok) { syncedCount += scope.size(); } else { failedCount += scope.size(); }
}
public void finish(Database.BatchableContext bc) {
System.debug('Synced: ' + syncedCount + ', failed: ' + failedCount);
}
}Some details in this class matter:
- The callout happens before the
update. In one transaction, a callout after uncommitted DML throws the "uncommitted work pending" error. Eachexecuteis a transaction, so this ordering rule still applies inside it. Database.Statefulkeeps the instance variables between scopes. Without it, the instance variables reset to their initial values after everyexecute. The cost is that the state is serialized between scopes, so keep it small.- The
tryblock catchesCalloutException, which covers timeouts. A failed scope is markedFailedand the job continues. An unhandled exception would roll back that scope's transaction and leave its recordsPending. Other scopes still run.
Choosing the scope size
The scope size is the second argument of Database.executeBatch. Two limits drive the choice:
- A transaction allows 100 callouts. If you make one callout per record, the scope size must be 100 or less. The example above makes one callout per scope, so it is not bound by this.
- The callouts in one transaction can take at most 120 seconds in total. If the service is slow, use smaller scopes so that one scope finishes in time.
Smaller scopes also limit how many records a single failure affects.
public class AccountSyncScheduler implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new AccountSyncBatch(), 50);
}
}Schedule it once, for example every day at 02:00:
System.schedule('Account sync nightly', '0 0 2 * * ?', new AccountSyncScheduler());A Schedulable class cannot make callouts itself. It starts the batch, which can.
Avoiding loops
The batch writes to Account, so triggers on Account fire again. The trigger in this tutorial runs only after insert, so the batch's update does not re-enter it. If your trigger also runs on update, it must skip records whose only change is the status field. Compare the old and new values, or check a static flag, as described in the chapter on re-entry.
Testing the batch
A test can run at most one execute call, so keep test data within one scope. Call Database.executeBatch between Test.startTest() and Test.stopTest(). Supply a mock with Test.setMock.
@IsTest
private class AccountSyncBatchTest {
private class MockOk implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}
@IsTest
static void marksPendingAccountsAsSynced() {
insert new Account(Name = 'Acme', Billing_Sync_Status__c = 'Pending');
Test.setMock(HttpCalloutMock.class, new MockOk());
Test.startTest();
Database.executeBatch(new AccountSyncBatch(), 50);
Test.stopTest();
Account a = [SELECT Billing_Sync_Status__c FROM Account WHERE Name = 'Acme'];
System.assertEquals('Synced', a.Billing_Sync_Status__c);
}
}Insert the test data before Test.setMock and Test.startTest(). The mock must be registered before the job runs.
Batch compared with Queueable
| Question | Queueable | Batch |
|---|---|---|
| Data size | Small, known at enqueue time | Thousands to millions of records |
| Callout budget | One transaction, 100 callouts | 100 callouts per scope |
| Start-up | Fast | Slower, can wait in the Flex Queue |
| Starting from a trigger | One job per trigger run, up to 50 per transaction | Poor fit for per-record work |
| Retry model | Finalizer re-enqueues | Status field, re-run on schedule |
| State between steps | Fields in the class | `Database.Stateful` |
Use Batch Apex for callouts when:
- the volume exceeds what one transaction can send, for example a backfill of 200,000 accounts;
- the work can be delayed and runs on a schedule;
- you need a durable "to do" list that you can inspect and retry.
Stay with a Queueable job when each trigger run produces a small payload that should be sent within seconds.
Exercise
A batch class makes one HTTP callout per record and uses the default scope size. The job fails with a "Too many callouts: 101" error. What causes this, and how do you fix it?
Show answer
The default scope is 200 records, and each execute call is one transaction limited to 100 callouts. At 101 records the limit is exceeded. Fix it by passing a scope size of 100 or less to Database.executeBatch. Better, send one bulk request per scope, as the service allows.
Exercise
Why does the batch in this chapter make the callout before the update, and what happens if the order is reversed?
Show answer
A callout after DML in the same transaction throws the "uncommitted work pending" error, because the open transaction would be held while the external service responds. Each execute is its own transaction, so the callout must come first, then the update.