Sub topic 13
Making callouts from a batch job
A callout is an outbound request from Apex to an external service, usually over HTTP. Batch Apex can make callouts, but only if you ask for them explicitly and respect a few limits that differ from normal code. This chapter assumes you can write a basic batch class with start, execute and finish, and that you know what an HttpRequest is. It also assumes you have set up a Named Credential.
Why a batch job needs permission to make callouts
A batch class cannot make callouts by default. To allow them, add Database.AllowsCallouts to the implements list. The interface has no methods. It is a marker that tells the platform to allow HTTP callouts in start, execute and finish.
public class MyBatch implements Database.Batchable<SObject>, Database.AllowsCallouts {
// start, execute, finish
}If you leave it out, the first callout throws System.CalloutException: Callout from scheduled Apex not supported or a similar error, depending on the context. The error appears at run time, not at save time.
Limits that apply to callouts in each execute call
Each execute call is its own transaction, so callout limits reset for every chunk. Inside one chunk, the usual per-transaction limits apply.
| Limit | Value | Practical effect |
|---|---|---|
| Callouts per transaction | 100 | A batch size above 100 with one callout per record will fail. |
| Timeout per callout | Up to 120 seconds (default 10) | Set `setTimeout` deliberately. |
| Cumulative callout time per transaction | 120 seconds | Slow endpoints reduce how many callouts fit in one chunk. |
| Request and response size | 12 MB each in asynchronous Apex | Large payloads also consume heap. |
| Long-running callouts across the org | 10 callouts of 5 seconds or more at once | Many parallel jobs can hit this limit. |
Check the current Apex Developer Guide for exact values, because Salesforce can change them between releases.
Choose a batch size from the callout pattern
The right batch size depends on how many callouts each record needs.
- One callout per record. The batch size must be 100 or less. With a slow endpoint, it must be lower. Divide 120 seconds by the typical response time to estimate a safe size.
- One callout per chunk. Send all records in
scopein a single request. This is usually the better design because it uses one callout against the limit and gives the fastest run time. It only works if the external API accepts bulk requests. - Several callouts per chunk. Group records into sub-batches that match the API's bulk size, and keep the total below 100.
Prefer bulk requests when the API supports them. A job that makes one callout for each of two million records needs two million callouts, and the org-wide limits on long-running requests will slow it down.
Do all callouts before any DML
Within a single transaction, you cannot make a callout after you have performed DML that is not yet committed. Salesforce throws System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out.
This applies inside each execute call. The safe order is:
- Build the request from
scope. - Make all callouts.
- Apply the results with DML.
public void execute(Database.BatchableContext bc, List<Account> scope) {
update scope; // DML first
HttpResponse res = new Http().send(req); // fails: uncommitted work pending
}The example above is the wrong order. If you need a callout after each of several DML steps, split the work across separate transactions, for example by chaining a Queueable job. The simplest fix is to reorder so that every callout comes first.
A complete example: rate accounts through an external service
This batch sends each chunk of accounts to an external rating service in one request. It then applies the returned ratings with a partial-success update. It assumes a Named Credential called Rating_Service exists. The service accepts a JSON array of {id, name} objects and returns a JSON array of {accountId, rating} objects.
public class AccountRatingCalloutBatch implements
Database.Batchable<SObject>, Database.AllowsCallouts, Database.Stateful {
public class RatingResult {
public Id accountId;
public String rating;
}
public Integer calloutFailures = 0;
public Integer updated = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Name, Rating FROM Account WHERE Rating = null
]);
}
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:Rating_Service/ratings');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(60000);
req.setBody(JSON.serialize(payload));
HttpResponse res;
try {
res = new Http().send(req);
} catch (CalloutException e) {
calloutFailures++;
System.debug(LoggingLevel.ERROR, 'Callout failed: ' + e.getMessage());
return;
}
if (res.getStatusCode() != 200) {
calloutFailures++;
System.debug(LoggingLevel.ERROR, 'Unexpected status ' + res.getStatusCode());
return;
}
List<RatingResult> results =
(List<RatingResult>) JSON.deserialize(res.getBody(), List<RatingResult>.class);
Map<Id, String> ratingById = new Map<Id, String>();
for (RatingResult r : results) {
ratingById.put(r.accountId, r.rating);
}
List<Account> toUpdate = new List<Account>();
for (Account a : scope) {
if (ratingById.containsKey(a.Id)) {
a.Rating = ratingById.get(a.Id);
toUpdate.add(a);
}
}
for (Database.SaveResult sr : Database.update(toUpdate, false)) {
if (sr.isSuccess()) {
updated++;
}
}
}
public void finish(Database.BatchableContext bc) {
System.debug('Updated ' + updated + ' accounts, ' + calloutFailures + ' chunks failed.');
}
}Several choices in this class matter:
- The Named Credential (
callout:Rating_Service) keeps the URL and secrets out of code. Authentication is handled by the platform. - The
try/catchhandles timeouts, which surface as aCalloutException. The chunk is counted as failed, and the job moves on to the next chunk. - A non-200 status is handled in code. An HTTP error response does not throw an exception by itself.
Database.Statefulkeeps the two counters across chunks, sofinishcan report totals.- The only DML happens after the callout.
What one execute call looks like
The diagram shows the order of events in a single chunk.
What happens when a callout fails
An uncaught exception in execute rolls back that chunk only. Salesforce records it in NumberOfErrors on the AsyncApexJob, and the job continues with the next chunk. Records in the failed chunk are not retried automatically.
You have three options for handling failures:
- Catch and count. This is what the example does. It keeps the job running and lets
finishreport the totals. - Record the failed IDs. Store them in a
Database.Statefullist or in a custom object so that a later run can pick them up. Keep the list small, because stateful data is serialized between chunks and counts against heap. - Make the query self-selecting. In the example,
WHERE Rating = nullmeans a rerun processes only unrated accounts. Idempotent design like this is the cleanest retry strategy.
Do not retry inside a loop in the same execute call. Each retry uses a callout and more of the 120-second budget.
Testing a callout batch
Apex tests cannot make real callouts. If a test runs a batch that sends one, it fails unless you register a mock with Test.setMock. A mock implements HttpCalloutMock and returns a canned response.
@IsTest
private class AccountRatingCalloutBatchTest {
private class RatingMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
List<Object> items = (List<Object>) JSON.deserializeUntyped(req.getBody());
List<Map<String, Object>> results = new List<Map<String, Object>>();
for (Object o : items) {
Map<String, Object> item = (Map<String, Object>) o;
results.add(new Map<String, Object>{
'accountId' => item.get('id'),
'rating' => 'Hot'
});
}
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setHeader('Content-Type', 'application/json');
res.setBody(JSON.serialize(results));
return res;
}
}
@IsTest
static void ratesAccountsThroughService() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 50; i++) {
accts.add(new Account(Name = 'Test ' + i));
}
insert accts;
Test.setMock(HttpCalloutMock.class, new RatingMock());
Test.startTest();
Database.executeBatch(new AccountRatingCalloutBatch(), 50);
Test.stopTest();
System.assertEquals(50, [SELECT COUNT() FROM Account WHERE Rating = 'Hot']);
}
}A test runs only one execute call, so keep the record count within the batch size. To cover the failure path, write a second mock that returns status 500 and assert that no accounts were rated.
Common mistakes
- Forgetting
Database.AllowsCallouts. - Using a batch size over 100 with one callout per record.
- Placing DML before a callout in the same
executecall. - Treating a 4xx or 5xx response as success because no exception was thrown.
- Leaving the default 10-second timeout on a slow service, which turns slow responses into failed chunks.
Exercise
A batch class implements Database.Batchable<SObject> and makes one callout for each record in scope. It runs with a batch size of 200 and every chunk fails. Name two separate problems that could cause this and how to fix each.
Show answer
First, the class may not implement Database.AllowsCallouts, so the platform rejects the callout. Add the interface. Second, 200 callouts per chunk exceed the limit of 100 callouts per transaction. Lower the batch size to 100 or less (less if the endpoint is slow, to stay under the 120-second cumulative limit), or change the design to send the whole chunk in one bulk request. A third possible cause is DML placed before the callout, which throws an uncommitted work error. Move all callouts ahead of any DML.