Why is implementing Database.allowsCallouts mandatory when making external web service calls in Batch Apex?
Answer
Basics: By default, Batch Apex is not permitted to make callouts to external web services. Salesforce makes you opt in by adding the marker interface Database.AllowsCallouts to the class declaration. It has no methods; its presence tells the platform to allow callouts in that job's transactions.
How it works: Declare implements Database.Batchable<SObject>, Database.AllowsCallouts. Each execute is its own transaction with its own limits, so you get a fresh allowance of 100 callouts per execute and a 120 second cumulative callout time cap. Typical flow: query records in start, call the external API per chunk, then save the results with DML at the end of execute.
Advanced / deep dive: The classic trap is ordering: in a transaction you cannot make a callout after uncommitted DML ("You have uncommitted work pending"), so do all callouts first, collect results, then perform DML. Choose a small scope (for example 10 to 50) so that records times callouts per record stays under 100, and so one slow chunk does not time out. Remember the callout timeout (default 10 s per request, max 120 s) and the 120 s cumulative limit. For bulk-friendly APIs, send one request per chunk, not per record. Add retries and idempotency keys, since a failed chunk can be re-run manually. Use Named Credentials for authentication, never hard-coded secrets. Rate-limited APIs need smaller scopes or Queueable chains with delay. Also note that Stateful and AllowsCallouts combine fine. Platform events or Change Data Capture are alternatives when the external system should pull rather than be pushed to.
Code / config example:
public class PushAccountsBatch .Batchable<SObject>, Database.AllowsCallouts {
Database.QueryLocator {
Database.getQueryLocator();
}
{
();
req.setEndpoint();
req.setMethod();
req.setHeader(, );
req.setBody(JSON.serialize(scope));
req.setTimeout();
().send(req);
(Account a : scope) a.Sync_Pending__c = (res.getStatusCode() != );
update scope;
}
{}
}