Sub topic 13
Making callouts from a batch job
This chapter assumes you can write a basic Database.Batchable class, know what Database.Stateful does, and understand that each execute call runs in its own transaction. Here you add HTTP callouts to a batch job.
Why callouts need an opt-in
A batch class cannot make callouts by default. To allow them, implement the marker interface Database.AllowsCallouts next to Database.Batchable. Without it, the first callout throws a System.CalloutException at runtime, and the failure only shows up when the job runs.
The callout limits apply per execute call, because each call is a separate transaction. In a single transaction you can make up to 100 callouts, and the total callout time is capped at 120 seconds. Each callout also has its own timeout, which defaults to 10 seconds and can be raised to 120 seconds with setTimeout.
A batch class that calls an external service
This example sends each account to an external system. It calls the service first and updates records afterward, which matters (see the next section).
public class AccountSyncBatch implements
Database.Batchable<SObject>, Database.AllowsCallouts, Database.Stateful {
public Integer synced = 0;
public Integer failed = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Name, Description FROM Account WHERE Description = null
]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
List<Account> toUpdate = new List<Account>();
for (Account a : scope) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Account_Service/accounts/' + a.Id);
req.setMethod('GET');
req.setTimeout(20000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
a.Description = res.getBody().left(200);
toUpdate.add(a);
synced++;
} else {
failed++;
}
}
Database.update(toUpdate, false);
}
public void finish(Database.BatchableContext bc) {
System.debug('Synced: ' + synced + ', failed: ' + failed);
}
}The endpoint uses a Named Credential (callout:Account_Service), so the URL and secrets stay out of the code. You must create that Named Credential in Setup before the job can run.
Choosing a batch size for callouts
This class makes one callout per record. With the default batch size of 200, the 101st callout in a single execute call would exceed the limit of 100. Pick a batch size at or below the callout limit, and lower it further if the service is slow.
Database.executeBatch(new AccountSyncBatch(), 50);With a size of 50 and 20-second timeouts, the worst case is 1,000 seconds of waiting, which is far past the 120-second total. Size the batch for the typical response time, not just the callout count. Measure a real run, then adjust.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `Callout from batch not allowed` | Class lacks `Database.AllowsCallouts` | Add the interface |
| `You have uncommitted work pending` | DML ran before a callout in the same transaction | Make callouts first, then run DML |
| `Too many callouts: 101` | Batch size exceeds the callout limit | Lower the batch size |
| `Read timed out` | Service slower than the timeout | Raise `setTimeout` or shrink the batch |
The uncommitted work rule is the one that surprises people. Once an execute call performs DML, it cannot make a callout until the transaction ends. So collect all the responses in the loop, and update the records once at the end, as the example does.
Testing callouts
Test methods cannot make real callouts. Implement HttpCalloutMock and register it with Test.setMock before Test.startTest.
@IsTest
private class AccountSyncBatchTest {
private class OkMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('synced');
return res;
}
}
@IsTest
static void syncsAccounts() {
insert new Account(Name = 'Test');
Test.setMock(HttpCalloutMock.class, new OkMock());
Test.startTest();
Database.executeBatch(new AccountSyncBatch(), 50);
Test.stopTest();
System.assertEquals(1, [SELECT COUNT() FROM Account WHERE Description = 'synced']);
}
}Exercise
A batch class makes one callout per record and runs with the default batch size of 200. It fails partway through each chunk with a callout error. What two changes would you make?
Show answer
Add nothing to the interface list if Database.AllowsCallouts is already there. The failure comes from the limit of 100 callouts per transaction, so lower the batch size to 100 or less when you call Database.executeBatch. Also make sure all callouts happen before any DML in execute. If the service is slow, use an even smaller size so the total time stays under 120 seconds.