Sub topic 15
Queueable, Future Method, or Batch Apex?
This chapter assumes you can write and enqueue a Queueable class, chain jobs, attach a finalizer, and read AsyncApexJob. It also assumes you know the governor limits that apply to a transaction. Here you compare the three main asynchronous tools and learn how to pick one for a given workload.
What the three tools have in common
Future methods, Queueable Apex, and Batch Apex all run outside the transaction that started them. Each job runs in its own transaction with its own governor limits. Asynchronous limits are higher for some resources, such as heap size (12 MB instead of 6 MB) and CPU time (60,000 ms instead of 10,000 ms).
They also share some constraints:
- Each job runs some time after you request it. Salesforce gives no guarantee about when.
- The org has a daily cap on asynchronous Apex executions, and all three tools count against it. The cap is 250,000 or 200 times the number of user licenses, whichever is greater.
- A failure in the background job does not roll back the transaction that started it.
The differences are in how you pass data, how much data you can cover, how you chain work, and how well you can observe a job.
Future methods
A future method is a static void method marked with @future. Its parameters must be primitives or collections of primitives, so you pass record IDs and query the records again inside the method.
public class AccountSync {
@future(callout=true)
public static void pushAccounts(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
// Make the callout here.
}
}Future methods have these properties:
- They return nothing, so you get no job ID to monitor or abort.
- They cannot accept sObjects or custom Apex types as parameters.
- One transaction can call at most 50 of them.
- A future method cannot call another future method, and a batch job's
executecannot call one either. - They have no chaining and no finalizer support.
Future methods are still fine for small, fire-and-forget work that already exists in a codebase. For new code, Queueable is almost always at least as good.
Queueable Apex
Queueable keeps the simplicity of a future method and removes most of its limits:
- Rich state. Member variables can hold sObjects, collections, and custom Apex types, as long as they are serializable.
- A job ID.
System.enqueueJobreturns an ID you can query inAsyncApexJobor pass toSystem.abortJob. - Chaining.
executecan enqueue one child job. - Finalizers. A transaction finalizer can log a failure or retry the job, even after an unhandled exception or a limit error.
- AsyncOptions. You can cap stack depth, delay the start, and reject duplicates.
A Queueable has no built-in way to iterate over a query. You write the slicing logic yourself, as in the chunked example from the chaining chapters. Your code also has to supply state handling, error handling, and a stopping condition. The limits are:
| Context | Queueable jobs you can enqueue |
|---|---|
| Synchronous transaction | 50 |
| Inside a Queueable, batch `execute`, or future method | 1 |
A chain has no fixed length in most orgs. Developer Edition and trial orgs cap the depth at 5. Because a chain runs one job at a time, it processes slices serially.
Batch Apex
Batch Apex is built for data volume. A class implements Database.Batchable<SObject> with three methods: start, execute, and finish.
public class AccountCleanupBatch implements Database.Batchable<SObject>, Database.Stateful {
private Integer processed = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id, Description FROM Account WHERE Description = null'
);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Description = 'Reviewed';
}
update scope;
processed += scope.size();
}
public void finish(Database.BatchableContext bc) {
System.debug('Accounts processed: ' + processed);
}
}
// Run it with a scope size of 200 records per execute call:
// Id jobId = Database.executeBatch(new AccountCleanupBatch(), 200);Batch Apex has these properties:
- A
QueryLocatorcan cover up to 50 million records. Salesforce divides them into scopes and callsexecuteonce per scope. The default scope size is 200 and the maximum is 2,000. - Every
executecall is its own transaction. A failed scope does not undo the scopes that already committed. - Member variables are reset between
executecalls unless the class implementsDatabase.Stateful. Stateful batches are slower because Salesforce serializes the state after each scope. finishruns once at the end. You can use it to send a summary or start the next batch.- An org can have up to 5 batch jobs running at once. Others wait in the flex queue, which holds up to 100 jobs in
Holdingstatus. - Queueable and batch jobs both appear in
AsyncApexJob, which reportsTotalJobItemsandJobItemsProcessedfor batches.
Batch Apex costs more to set up and usually takes longer to start than a Queueable. It is the right tool when the number of records is the main concern.
Comparing them side by side
| Feature | Future method | Queueable | Batch Apex |
|---|---|---|---|
| Parameter types | Primitives and collections of primitives | Any serializable type | Constructor state, plus a query or iterable |
| Job ID returned | No | Yes | Yes |
| Chaining | No | One child per job | `finish` can start another batch |
| Finalizer | No | Yes | No. Use `finish` and `Database.RaisesPlatformEvents` instead |
| Best data size | Small | Small to medium | Large, up to 50 million records |
| Splits work automatically | No | No | Yes |
| Callouts | `@future(callout=true)` | `Database.AllowsCallouts` | `Database.AllowsCallouts` |
A decision path
Start with the size of the work, then look at the other requirements.
Use these criteria in order:
- Volume. If you must process more records than a few Queueable slices can reasonably handle, use Batch Apex. It has built-in query iteration, automatic scoping, and flex queue management.
- Failure handling. If you need to know why a job failed, and possibly retry it, use Queueable with a finalizer. Batch jobs report failures per scope through
AsyncApexJoband optional platform events, but a finalizer reacts inside the platform right after the job ends. - State shape. If the input is an sObject or a custom class, use Queueable. A future method forces you to pass IDs and query again.
- Dependent steps. If step 2 needs the result of step 1, chain Queueable jobs. Chaining from a batch is possible only through
finish. - Throughput. Queueable chains run serially. If you need many slices in parallel, a batch job processes scopes with its own concurrency rules, and you can also enqueue several independent Queueables from a synchronous transaction, up to 50.
Combining tools
The tools work well together, within the enqueue limits:
- A trigger or controller enqueues one Queueable, which prepares data and calls
Database.executeBatch. A Queueable can start a batch job, and starting one is not counted as a Queueable enqueue. - A batch
executecan enqueue one Queueable per scope. This suits a callout that must happen after each scope commits, but check the daily cap, because each scope would create a job. - A batch
finishmethod can enqueue a Queueable that sends a report or runs follow-up work.
public class StartCleanupJob implements Queueable {
public void execute(QueueableContext context) {
// Prepare data first, then hand large-volume work to Batch Apex.
Database.executeBatch(new AccountCleanupBatch(), 200);
}
}Common mistakes
- Using Queueable chains to walk millions of rows. Each link costs an extra queue wait. A batch job with a query locator is simpler and faster.
- Using a batch job for ten records. The overhead of
start,execute, andfinishoutweighs the benefit, and the job competes for the five concurrent batch slots. - Calling a future method from a future method or a batch
execute. This throws a runtime exception. A Queueable is the safe replacement. - Forgetting that async enqueue limits drop to 1. Code that enqueues several Queueables works from a trigger but fails when the same code runs inside a Queueable or a batch.
- Assuming a Queueable can see uncommitted work. A job starts only after the enqueuing transaction commits. If the transaction rolls back, the job never runs.
Worked decision: three requests
- "After an Opportunity closes, push its ID to an external system." This is one small callout with a few IDs. A Queueable with
Database.AllowsCalloutsand a finalizer to log failures is the best fit. A future method also works. - "Recalculate a field on all 3 million Contacts nightly." This is a batch job, probably started by a schedulable class. A chain of Queueable slices would create about 15,000 jobs at 200 records each.
- "Process a CSV upload, then call a service for each row group, retrying twice on failure." Use a chained Queueable with a finalizer. State is carried in member variables, the retry count lives in the job, and the finalizer enforces the limit.
Exercise
A trigger on Case must send a list of Case sObjects, with their current field values, to an external API after commit, and the team wants to retry once if the job fails with an unhandled exception. A future method was proposed. Which tool should you use, and give two reasons?
Show answer
Use Queueable Apex implementing Database.AllowsCallouts. First, a future method accepts only primitives and collections of primitives, so it cannot take the Case sObjects as a parameter, but a Queueable can hold them in a member variable. Second, only a Queueable can attach a transaction finalizer, which reads the parent job's result and exception and re-enqueues the job once. A future method has no finalizer and returns no job ID.
Exercise
A nightly process must update 8 million Account records. Why is a chained Queueable the wrong choice, and what should you use instead?
Show answer
A chain runs one slice at a time, and each link waits in the queue, so 8 million records at 200 per slice would need about 40,000 jobs, which also uses a large share of the daily async execution limit. Use Batch Apex with a QueryLocator in start, which handles up to 50 million records and calls execute once per scope in its own transaction, with a scope size such as 200.