Sub topic 17
Batch Apex versus Queueable, Bulk API and other options
This chapter assumes you can write and deploy Apex, that you know the start, execute and finish methods of Database.Batchable, and that you know the governor limits that apply to a single transaction. Batch Apex is one tool among several. The goal here is to decide when it is the right one and when something simpler or something outside Apex fits better.
What you are choosing between
Each option below runs work outside the user's request, but they differ in who starts the work, how much data they handle, and how much custom logic they allow.
- Batch Apex reads a large record set and runs your code on it in chunks. Each chunk gets its own transaction and fresh limits.
- Queueable Apex runs one asynchronous job. It accepts complex objects as constructor arguments and can enqueue a follow-up job.
- Future methods (
@future) run one static method asynchronously. They accept only primitive arguments. - Scheduled Apex starts any of the above at a set time.
- Bulk API 2.0 is a REST interface that an external client uses to load or query large CSV data sets.
- Declarative tools such as scheduled flows, Data Loader and Data Import Wizard need no Apex.
Batch Apex and Queueable compared
Both run asynchronously and both get the asynchronous governor limits for each transaction. The difference is how the work is divided.
A batch job divides the work for you. Salesforce holds the query result, hands your execute method one chunk at a time, and tracks progress in AsyncApexJob. A Queueable job is a single transaction. If you want it to process a lot of data, you have to divide the work yourself and chain jobs.
| Question | Batch Apex | Queueable Apex |
|---|---|---|
| Data volume | A QueryLocator can cover up to 50 million records | One transaction's limits, unless you chain jobs |
| Who divides the work | The platform, using the batch size | You, in code |
| Constructor arguments | Any serializable members of the class | Any serializable members, including sObjects and collections |
| Starting follow-up work | Another batch from `finish` | A new job from `execute` (one child per job) |
| Progress and status | `AsyncApexJob` shows processed and total chunks | `AsyncApexJob` shows one job |
| Concurrency | 5 active or queued, the rest in the Flex Queue | Up to 50 enqueued from one synchronous transaction |
| Typical use | Nightly cleanup, recalculation, data migration | Follow-up work after a trigger or a button, small to medium volume |
A Queueable job is the better fit when the data set is known to be small or is already in memory. For example, a trigger collects 300 record Ids and needs a callout for each. The Queueable class starts with System.enqueueJob, which returns the job Id right away:
public class AccountRatingQueueable implements Queueable {
private List<Id> accountIds;
public AccountRatingQueueable(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext qc) {
List<Account> accts = [
SELECT Id, Rating FROM Account WHERE Id IN :accountIds
];
for (Account a : accts) {
a.Rating = 'Cold';
}
update accts;
}
}List<Id> ids = new List<Id>(new Map<Id, Account>(
[SELECT Id FROM Account WHERE Rating = null LIMIT 500]
).keySet());
Id jobId = System.enqueueJob(new AccountRatingQueueable(ids));
System.debug('Queued ' + jobId);This code works, but it is limited. The job does all 500 updates in one transaction. If you passed 50,000 Ids, it would hit the 10,000 DML row limit. A batch job does not have this problem, because it splits the records for you.
Common errors when picking Queueable for large data
- Assuming a chain is the same as a batch. A chained Queueable job can process large volumes, but you write the paging logic. If you page with
OFFSET, remember it is capped at 2,000 rows. A better pattern is to filter on an Id greater than the last one processed, ordered by Id. - Chaining without a guard. A job that always enqueues a successor can run forever. Add an exit condition, and note that Developer Edition and trial orgs limit chain depth to 5.
- Forgetting that a Queueable job can enqueue only one child. In production a single
executecan start one chained job. Batch Apex has no such limit on records, but the same one-job-at-a-time rule applies to what you start from a batchexecute. - Skipping failure handling. A failed Queueable job does not retry. Attach a
FinalizerwithSystem.attachFinalizerto run cleanup or re-enqueue work whether the job succeeded or failed.
Where future methods and Scheduled Apex fit
A future method is the oldest option. It takes primitive arguments only, returns no job Id, and cannot be chained. For new code, Queueable is usually better, because it gives you an Id to monitor and accepts richer arguments. Keep @future for the narrow case of mixing setup and non-setup DML in one transaction, or for existing code you do not want to rewrite.
Scheduled Apex is a trigger, not a processing engine. Its execute method should start a batch or Queueable job and return, as in the nightly example from the scheduling chapter. A scheduled class that processes records itself is bound by the limits of one transaction.
Bulk API 2.0 and other tools outside Apex
Bulk API 2.0 solves a different problem. It is for an external system that needs to push or pull millions of rows, usually as CSV. Salesforce splits the upload into internal batches and processes them asynchronously. Triggers, flows and validation rules still run on those records, but your own custom loop does not.
Use Bulk API 2.0 or Data Loader when:
- the data originates outside Salesforce, such as a file or another database,
- the operation is a plain insert, update, upsert, delete or query,
- you do not need to compute anything that would take Apex code.
Use Batch Apex when the data is already in Salesforce and each record needs logic that SOQL and DML alone cannot express, such as calling an external service or recalculating a value from related records.
Other options worth checking first:
- Scheduled-triggered flows handle simple record updates with no code, within their own daily limits.
- Platform Events and Change Data Capture suit work that should react to a change as it happens, rather than sweeping through all records later.
- Apex cursors let a Queueable job page through a very large query result with
Database.getCursorandfetch. They are newer than the rest, so check the release notes for the status in your org before relying on them.
A decision path
The diagram shows a practical order of questions. Move down it until one answer settles the choice.
Read the last two decisions with care. "Fits in one async transaction" means within 200 SOQL queries, 10,000 DML rows, 50,000 query rows, 60 seconds of CPU time and 12 MB of heap, all counted together. If you are near any of those numbers, choose Batch Apex.
Combining the options
The options are not exclusive. Real systems often use several:
- A Bulk API 2.0 job loads 5 million rows into a staging object.
- A scheduled class starts a batch job that reads the staging rows, applies business rules and updates the target records.
- In
finish, the batch enqueues a Queueable job that sends one summary callout or notification.
Each piece does the job it is best at. Bulk API handles transport, Batch Apex handles volume and custom logic, and Queueable handles a single follow-up task.
Exercise
A trigger on Case collects up to 200 Case Ids and must call an external service once for each, then update a field on each Case. The volume never grows beyond that. Which option fits best, and why would Batch Apex be more than you need?
Show answer
Queueable Apex fits best. The trigger can pass the 200 Ids to System.enqueueJob, and the job runs asynchronously, makes the callouts (the class also implements Database.AllowsCallouts) and updates the Cases within one set of asynchronous limits. Batch Apex would work, but it needs a start query, a batch size, a job queue slot and finish logic for a volume that fits in one transaction. It also starts from a trigger less simply.
Exercise
Your company receives a 4 million row CSV every night from a partner system. Each row must be inserted as a custom object record with no extra logic. Should you write a batch class?
Show answer
No. This is a plain insert of external data, so Bulk API 2.0 or Data Loader is the better fit. Write a batch class only if the rows need computation that SOQL and DML cannot do, and in that case load them into a staging object first and process them from there.