Sub topic 13
When to use Queueable or Batch Apex instead
This chapter assumes you can write and call a future method, and that you know the governor limits for future methods and the restrictions on where you can call them. You should also be comfortable with basic Apex classes, SOQL, DML, and triggers.
Future methods are the simplest way to run work asynchronously. They are also the most limited. This chapter shows where those limits become a problem and what to use in their place.
Where future methods fall short
A future method is a good fit for small, fire-and-forget work. Examples are a single callout after a record save, or setup object DML that has to be separated from other DML. Four limitations push you to other tools.
- Parameters are primitives only. You cannot pass an
sObjector a custom class instance. You pass IDs and re-query. - No job ID. Calling a future method returns
void. You cannot easily find the job you just queued or check its status from code. - No chaining. A future method cannot call another future method, so you cannot build a sequence of steps.
- No control over volume. A future method runs in one transaction with one set of limits. It cannot walk through millions of records.
Queueable Apex fixes the first three. Batch Apex fixes the fourth.
Queueable Apex
A Queueable class implements the Queueable interface and has one method, execute(QueueableContext). You start it with System.enqueueJob(), which returns the job ID.
public class RatingUpdater implements Queueable {
private List<Account> accounts;
public RatingUpdater(List<Account> accounts) {
this.accounts = accounts;
}
public void execute(QueueableContext ctx) {
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
}
}Enqueue it like this:
List<Account> accts = [SELECT Id, Rating FROM Account LIMIT 50];
Id jobId = System.enqueueJob(new RatingUpdater(accts));
System.debug('Queued job: ' + jobId);The constructor accepts List<Account>, which a future method cannot do. Member variables can hold sObjects, collections, and your own classes. Salesforce serializes the object when you enqueue it. That has two consequences:
- The data is a snapshot taken at enqueue time. If another process changes the records before the job runs, your copy is stale. For records that change often, pass IDs and re-query, as you did with future methods.
- Member variables that cannot be serialized, such as an open
Httpobject, must be markedtransientor created insideexecute.
Chaining jobs
A running Queueable job can enqueue one more Queueable job. This lets you split a large task into steps, or work through a list a chunk at a time while each step gets fresh limits.
public class ChunkedUpdater implements Queueable {
private List<Id> remaining;
public ChunkedUpdater(List<Id> remaining) {
this.remaining = remaining;
}
public void execute(QueueableContext ctx) {
List<Id> current = new List<Id>();
while (!remaining.isEmpty() && current.size() < 200) {
current.add(remaining.remove(0));
}
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :current];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
if (!remaining.isEmpty()) {
System.enqueueJob(new ChunkedUpdater(remaining));
}
}
}Each job in the chain runs in its own transaction. A job can enqueue only one child job from execute. In Developer Edition and trial orgs, the chain depth is limited to 5. Other org types have no fixed depth limit. Even so, an endless chain is a risk, so always make sure the chain has a stopping condition.
Callouts, monitoring, and failure handling
- Callouts. Implement
Database.AllowsCalloutsin addition toQueueable. This replaces@future(callout=true). - Monitoring. Queueable jobs appear on the Apex Jobs page in Setup. You can also query
AsyncApexJobusing the ID thatSystem.enqueueJobreturned. - Failure handling. You can attach a finalizer with
System.attachFinalizer(). A finalizer runs after the job ends, whether it succeeded or failed. It can log the error or enqueue a retry. Future methods have no equivalent.
public class BillingJob implements Queueable, Database.AllowsCallouts {
private List<Id> accountIds;
public BillingJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
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) {
System.debug(LoggingLevel.ERROR, 'Callout failed: ' + res.getStatus());
}
}
}Billing_API is the same placeholder Named Credential used earlier in this tutorial. You must define it in your own org.
Calling Queueable from triggers
The trigger pattern is the same as for future methods. Collect IDs, then enqueue once per trigger invocation. A single transaction can enqueue up to 50 Queueable jobs, which matches the future method call limit. Queueable has one extra advantage here. You can call System.enqueueJob from a future method, a batch job, or another Queueable job. Calling a future method from a future or batch context is not allowed.
Batch Apex
Batch Apex is built for large data volumes. The platform splits the records into chunks called scopes and runs each scope as its own transaction with fresh governor limits. A batch class implements Database.Batchable<SObject> and has three methods:
startdefines the records to process.executeruns once per scope.finishruns once at the end.
public class AccountRatingBatch implements Database.Batchable<SObject>, Database.Stateful {
private Integer processed = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id, Rating FROM Account WHERE Rating = null]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = 'Warm';
}
update scope;
processed += scope.size();
}
public void finish(Database.BatchableContext bc) {
System.debug('Accounts updated: ' + processed);
}
}Start it with Database.executeBatch:
Id jobId = Database.executeBatch(new AccountRatingBatch(), 200);The second argument is the scope size. The default is 200. A smaller scope helps when each record needs heavy processing or many callouts. A QueryLocator can return up to 50 million records, which is far beyond what a future method or a single Queueable job can handle.
Instance variables do not keep their values between execute calls unless the class implements Database.Stateful. In the example, processed only works because of that interface. Stateful batches use more memory and run slower, so use the interface only when you need it.
Other things to know about batch jobs:
- Only 5 batch jobs can be queued or active at once. Additional jobs wait in the Apex Flex Queue, which holds up to 100.
- Batch jobs are started, not chained from triggers. Starting one from a trigger is possible but risky, because every save could start a job.
- Callouts need
Database.AllowsCallouts, the same as in Queueable.
Comparing the three
| Feature | Future | Queueable | Batch |
|---|---|---|---|
| Accepts sObjects and custom types | No | Yes | Yes (via query or constructor) |
| Returns a job ID | No | Yes | Yes |
| Chaining | No | One child per job | Start a new batch from `finish` |
| Data volume | Small | Small to moderate | Up to 50 million records |
| Fresh limits per chunk | No | Per job in a chain | Per scope |
| Can be called from a future or batch method | No | Yes | Yes, with limits |
| Finalizers | No | Yes | No |
| Scheduling | No | No, but it can be started from a scheduler | Yes, via a Schedulable class |
Choosing between them
Work through the questions in this order.
In practice:
- Use Batch Apex when the number of records is large or unknown, when the job must run on a schedule, or when each chunk needs its own limits.
- Use Queueable Apex for most other cases. It handles sObject parameters, chained steps, job tracking, and error handling.
- Use a future method only when the work is tiny and has no further needs. It is also the right choice for existing code that already works.
Salesforce's guidance favors Queueable for new work. Future methods are still supported, so you do not need to rewrite working code. Migrate when you hit one of the limitations above.
Common mistakes
- Using Batch Apex for a handful of records. A batch job has startup overhead and uses one of the five concurrent slots. Use Queueable for small jobs.
- Enqueueing a job per record in a loop. This hits the limit of 50
enqueueJobcalls per transaction. Pass a list instead. - Trusting a serialized sObject. The job may run minutes later. Re-query if freshness matters.
- Chaining without an exit. Always test the condition that stops the chain.
- Forgetting
Database.AllowsCallouts. The callout fails at runtime with an error about uncommitted work or callouts not being allowed.
Converting a future method to Queueable
Take the updateAccountRatings future method from the start of this tutorial. Its Queueable version accepts a Set<Id>, which the future method could already do, but it now returns a job ID that you can log or monitor.
public class AccountRatingJob implements Queueable {
private Set<Id> accountIds;
public AccountRatingJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
}
}The trigger changes from calling AccountService.updateAccountRatings(ids) to System.enqueueJob(new AccountRatingJob(ids)). The test is the same as before. Only the call inside Test.startTest() and Test.stopTest() changes.
Exercise
An after-insert trigger must process 3 million Account records in a nightly cleanup. Each record needs a field update. Should you use a future method, Queueable Apex, or Batch Apex, and why?
Show answer
Batch Apex. It uses a QueryLocator that can return up to 50 million records, runs each scope of records in its own transaction with fresh governor limits, and can be run nightly through a Schedulable class. A future method accepts only primitives and runs in one transaction. A Queueable chain handles one chunk per job and is awkward at this volume. (Also, a trigger is the wrong place to start a nightly cleanup. Schedule the batch instead.)
Exercise
You need to send a list of Contact sObjects to an external system after a save, and you want to log the job ID. Which tool fits, and which interface must the class implement to make the callout?
Show answer
Queueable Apex. It accepts sObjects in its constructor and returns a job ID from System.enqueueJob. The class must implement both Queueable and Database.AllowsCallouts. A future method cannot take sObject parameters and returns no ID.