# Why is implementing Database.allowsCallouts mandatory when making external web service calls in Batch Apex?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Batch Apex

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
```apex
public class PushAccountsBatch implements Database.Batchable<SObject>, Database.AllowsCallouts {
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT Id, Name FROM Account WHERE Sync_Pending__c = true');
    }
    public void execute(Database.BatchableContext bc, List<Account> scope) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:ERP_Credential/accounts/bulk');   // Named Credential
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        req.setBody(JSON.serialize(scope));
        req.setTimeout(60000);
        HttpResponse res = new Http().send(req);                    // callout BEFORE any DML
        for (Account a : scope) a.Sync_Pending__c = (res.getStatusCode() != 200);
        update scope;
    }
    public void finish(Database.BatchableContext bc) {}
}
// Run with a small scope: Database.executeBatch(new PushAccountsBatch(), 20);
```

**Hidden gotchas & must-remember points:**
- The correct name is `Database.AllowsCallouts` (capital A).
- It applies to the whole class: start, execute and finish.
- No callout after DML in the same transaction.
- Max 100 callouts per execute; size scope accordingly.
- Callout cumulative timeout 120 s per transaction.
- Test classes need `Test.setMock(HttpCalloutMock.class, ...)` before running the batch.

**Best practice:** Use Named Credentials, small scope sizes, and perform callouts before DML within each chunk.

---
Source: ForceChallenges · last updated 2026-11-02
