Sub topic 15
Choosing Between Future, Queueable and Batch
This chapter assumes you can write a bulkified trigger and know the basic governor limits. It also assumes you have read the earlier chapters on why a trigger cannot call out directly and how to build the callout in a future method and a Queueable job. Here you compare the three options and learn how to pick one for a given requirement.
What the three options share
All three move the callout out of the trigger transaction. The trigger commits its DML first. The callout then runs later, in its own transaction, with fresh governor limits. That removes the "uncommitted work pending" error, because the async transaction starts with nothing uncommitted.
All three also share these rules:
- The callout runs after the trigger commits, so the trigger cannot read the response in the same transaction.
- Each async execution gets its own limits. A callout is bounded by 100 callouts per transaction and a cumulative 120 second timeout.
- You pass Ids, not sObjects, and re-query inside the async code, so you work with current data.
- None of them can roll back the original trigger transaction if the callout fails. Failure handling has to be compensating logic, such as a retry or a status field.
The differences are in how much you can pass in, how you can react to failure, how many jobs you can start, and what scale each handles.
Side-by-side comparison
| Feature | Future method | Queueable | Batch |
|---|---|---|---|
| Callout permission | `@future(callout=true)` | `Database.AllowsCallouts` | `Database.AllowsCallouts` |
| Parameters | Primitives and collections of primitives only | Any serializable member variables, including sObjects and custom types | Constructor state plus a query or iterable |
| Return value | None (void) | Job Id from `System.enqueueJob` | Job Id from `Database.executeBatch` |
| Per transaction start limit | 50 future calls | 50 `enqueueJob` calls (1 from async context) | Counts toward 5 active jobs, then waits in the Flex Queue |
| Chaining | Not allowed from future or batch | One child job from `execute` | Start another job from `finish` |
| Failure hook | None | Finalizer | `finish` method, but not for unhandled errors in a scope you did not catch |
| Typical volume | A handful of records | Up to the trigger batch, such as 200 | Thousands to millions of records |
| Start from a trigger | Yes | Yes | Possible, but rarely a good idea |
Where each one fits
Future methods
A future method is the smallest option. Use it for a fire-and-forget callout where the data is simple, such as a set of Ids, and you need nothing back.
Its limits are what push you away from it:
- It must be
staticand returnvoid. - You cannot get a job Id, so you cannot easily monitor or abort a specific call.
- Execution order is not guaranteed. Two future calls made in sequence can run in either order.
- You cannot call a future method from another future method or from a batch job.
- There is no Finalizer, so unhandled exceptions are only visible in logs and the Apex Jobs page.
A common trap is calling a future method from a trigger in a loop. That hits the 50 call limit quickly. Collect all Ids first and make one call per transaction.
Queueable Apex
Queueable is the default choice for trigger callouts. It accepts rich member variables, returns a job Id, supports Finalizers for failure handling, and can chain a follow-up job. Its constructor can hold sObjects, though the earlier guidance still applies: pass Ids and re-query when the data must be current.
Chaining is the feature that helps with callout limits. If a trigger batch contains more records than one execution can send, split the work and have each job enqueue the next one:
public class AccountSyncChunkJob implements Queueable, Database.AllowsCallouts {
private List<Id> remainingIds;
private static final Integer CHUNK_SIZE = 100;
public AccountSyncChunkJob(List<Id> remainingIds) {
this.remainingIds = remainingIds;
}
public void execute(QueueableContext ctx) {
Integer take = Math.min(CHUNK_SIZE, remainingIds.size());
List<Id> current = new List<Id>();
for (Integer i = 0; i < take; i++) {
current.add(remainingIds[i]);
}
List<Id> rest = new List<Id>();
for (Integer i = take; i < remainingIds.size(); i++) {
rest.add(remainingIds[i]);
}
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :current];
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(accounts));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() >= 200 && res.getStatusCode() < 300 && !rest.isEmpty()) {
System.enqueueJob(new AccountSyncChunkJob(rest));
}
}
}Only one child job can be enqueued from a running Queueable, so the chain is strictly sequential. That is a feature when the downstream service has rate limits, and a cost when you want throughput.
Batch Apex
Batch Apex is built for volume. It reads records through a QueryLocator (up to 50 million rows), slices them into scopes (default 200, maximum 2000), and runs each scope as its own transaction. With Database.AllowsCallouts, every execute call can make up to 100 callouts.
You rarely start a batch job directly from a trigger. A trigger transaction holds only the records that changed, so a Queueable fits better. A batch job fits when the work is not tied to one transaction, for example a nightly sweep that retries records that are not yet synced. This version assumes a custom checkbox field Billing_Synced__c on Account:
public class AccountSyncBatch implements Database.Batchable<SObject>, Database.AllowsCallouts {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
[SELECT Id, Name FROM Account WHERE Billing_Synced__c = false]
);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(scope));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
for (Account a : scope) {
a.Billing_Synced__c = true;
}
update scope;
}
}
public void finish(Database.BatchableContext bc) {
System.debug('Account sync batch finished: ' + bc.getJobId());
}
}Run it with Database.executeBatch(new AccountSyncBatch(), 100);. The second argument is the scope size. Pick it so that one scope's payload fits comfortably in the callout request size and time limits.
The batch update scope fires your Account triggers again. If the trigger enqueues a Queueable on update, you create a loop. Guard against that with a field check or a static flag, as covered in the chapter on re-entry.
A decision path
Work through the questions in this order. Stop at the first answer that fits.
In practice the middle question almost always answers "yes", because you want failure handling. That is why Queueable is the standard answer, and future methods remain mostly in older code.
Limits that settle edge cases
- Starting from async code. From inside a future, Queueable or batch execution you can start only one more Queueable. A trigger that fires during a batch
updatetherefore cannot enqueue 50 jobs. Design the trigger to enqueue once per transaction, with all Ids in one job. - Mixed contexts. A trigger on a record updated by a future method runs in a future context. It cannot call another future method. A Queueable handles this case, within the one-job limit.
- Daily async capacity. Org-wide async executions are capped per 24 hours (250,000, or the number of user licenses times 200 if that is higher). A trigger that enqueues one job per record can burn this allowance. One job per trigger batch is far cheaper.
- Batch queue depth. Only 5 batch jobs are queued or active at once. Extra
executeBatchcalls enter the Apex Flex Queue, which holds up to 100 jobs in Holding status. That is why you should not start a batch job from a trigger that fires on every save. - Callout time. Each callout defaults to a 10 second timeout, and you can raise it to 120 seconds with
setTimeout. The cumulative callout time for one transaction is also 120 seconds. In a Queueable that sends many chunks, the loop must stop before the total is exhausted.
Common mistakes
- Choosing a future method because it is shorter, then needing a Finalizer or a job Id a month later. Moving to Queueable later means rewriting the callers.
- Enqueuing one Queueable per record inside a loop. This hits the 50 job limit on large loads. Enqueue once, pass the Id set.
- Starting a batch job from a trigger to "handle volume". The trigger already runs on at most 200 records per chunk, so a Queueable is enough.
- Forgetting that a callout response that updates records can re-fire the trigger and enqueue another job.
Exercise
A trigger on Opportunity must send a changed record to an ERP system. A data load may insert 10,000 Opportunities, loaded in chunks of 200. The ERP accepts up to 500 records per request and you need to log any failure. Which option do you choose, and how do you structure it?
Show answer
Use Queueable. Each trigger chunk (200 records) enqueues one job with the set of Ids, which stays far below the 50 job limit per transaction. The job re-queries the records, sends them in one request (200 is under the ERP's 500 record limit), and attaches a Finalizer to log unhandled failures. A future method would work for the callout itself but gives no job Id and no Finalizer. Batch Apex is not needed because each trigger transaction is small, though a scheduled batch that retries records flagged as unsynced is a good addition if delivery must be guaranteed.