Sub topic 2
What Batch Apex is and when to use it
This chapter assumes you can write Apex classes, run SOQL queries and DML statements, and know that Salesforce enforces governor limits per transaction. It covers what Batch Apex is, how it avoids those limits, and when to choose it over other tools. The next chapters cover the interface in detail.
The idea in one paragraph
Batch Apex takes a large set of records and splits it into chunks, called batches or scopes. Each chunk runs in its own transaction, so governor limits reset for every chunk. The job runs asynchronously, which means it runs in the background after you start it, and your code does not wait for it. A job can process up to 50 million records returned by a QueryLocator, a limit no single synchronous transaction can approach.
Why a single transaction cannot do the work
A synchronous Apex transaction has hard ceilings. These are the commonly cited values for synchronous execution. Check the current Apex Developer Guide before relying on them, because Salesforce can change them.
| Limit | Synchronous value |
|---|---|
| Records returned by SOQL queries | 50,000 |
| Records processed by DML statements | 10,000 |
| SOQL queries issued | 100 |
| DML statements issued | 150 |
| Heap size | 6 MB |
| CPU time | 10,000 ms |
If you need to update 5 million accounts, a single transaction fails on the first query. It would exceed the 50,000 row query limit. Looping and re-querying inside one transaction does not help, because the limits count everything in that transaction.
Batch Apex does not raise these limits. It runs the work as many separate transactions, and each one gets a fresh set of limits. Per-transaction limits for execute are mostly the asynchronous values. Heap is 12 MB and CPU time is 60,000 ms. Other limits, such as 100 queries and 150 DML statements, stay the same.
How a batch job is structured
A batch class implements Database.Batchable<SObject>. The interface defines three methods that the platform calls in a fixed order.
startruns once. It defines which records to process.executeruns once per chunk. It does the real work. Each call is its own transaction.finishruns once after every chunk has been attempted. It is the place for summaries, notifications and follow-up jobs.
Here is a minimal class. It sets a default rating on accounts that have none.
public class AccountRatingBatch implements Database.Batchable<SObject> {
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 = 'Cold';
}
update scope;
}
public void finish(Database.BatchableContext bc) {
System.debug('Job ' + bc.getJobId() + ' finished.');
}
}You start the job with Database.executeBatch. The second argument is the number of records passed to each execute call.
Id jobId = Database.executeBatch(new AccountRatingBatch(), 200);
System.debug('Started batch job ' + jobId);The returned Id identifies an AsyncApexJob record. You can query that record to follow progress.
What the platform does for you
Consider the account example with 2 million matching rows and a batch size of 200.
- The platform runs the
startquery once and keeps the matching record Ids. - It cuts the Ids into 10,000 chunks of 200.
- For each chunk, it loads the records, calls
execute, and commits or rolls back that chunk on its own. - After all chunks have run, it calls
finish.
Because every chunk is a separate transaction, a failure in chunk 37 rolls back only chunk 37. Chunks 1 to 36 stay committed. This is useful, but it also means that a batch job as a whole is not atomic. If you need all-or-nothing behavior across the full data set, Batch Apex does not provide it.
Another consequence is that member variables do not survive between execute calls by default. Each call may run on a freshly deserialized instance of your class. If you need a running total, you must opt in with Database.Stateful, which a later chapter covers.
When to use Batch Apex
Batch Apex is a good fit when these conditions hold.
- The data set is too large for one transaction, typically more than a few thousand records and up to many millions.
- The work does not need to finish before the user's request returns.
- Each record, or each small group of records, can be processed independently.
- The work is recurring or one-off maintenance: data cleanup, recalculating fields, archiving, or syncing with an external system.
Typical examples:
- Nightly recalculation of a rollup that Salesforce cannot compute declaratively.
- One-time backfill of a new field across 10 million contacts.
- Purging old records that match a retention rule.
- Sending records to an external system in controlled groups.
When not to use it
Batch Apex has costs. A job waits in a queue, it can start seconds or minutes after you submit it, and the platform limits how many jobs run at once. These situations call for something else.
| Situation | Better choice |
|---|---|
| Fewer than a few thousand records, finished within one request | Synchronous Apex, if it fits within the limits |
| One follow-up task triggered from a trigger or a class | Queueable Apex |
| A single long computation on a small data set | Queueable Apex |
| Loading or exporting very large files from outside Salesforce | Bulk API |
| The user needs the result immediately | Synchronous code, or a screen flow |
| Simple field updates a admin can maintain | Flow, including scheduled flows |
A common mistake is to launch a batch job from a trigger for every small change. Each call consumes a slot in the queue, and the number of batch jobs you can enqueue is limited. A trigger that fires on a bulk load can exceed it. For a small amount of work from a trigger, use Queueable Apex. A later chapter compares these options in full.
Common errors at this stage
- Expecting an immediate result.
Database.executeBatchreturns as soon as the job is queued. Code that follows it cannot assume any records have changed. - Assuming one transaction. If the job fails halfway, the earlier chunks are already saved. Design the job so it can be run again safely, for example by selecting only records that still need work, as the
Rating = nullfilter does above. - Querying too much in
start. A QueryLocator is lazy about loading rows, but a very broad query still makes a slow job. Filter as tightly as you can. - Treating batch size as a limit on total records. The batch size controls the chunk size only. The total number of records is whatever
startreturns.
Key points
- Batch Apex splits work into chunks and runs each chunk in its own transaction, so limits reset per chunk.
- A batch class implements
start,executeandfinish. - The job runs asynchronously and is not atomic as a whole.
- Choose it for large, independent, non-urgent work. Choose Queueable, Flow, Bulk API or plain synchronous code for other cases.
Exercise
A developer needs to set a field on 3 million Contact records. A single synchronous method that queries all contacts and updates them fails. Explain why, and describe how Batch Apex avoids the problem. Then say what happens to earlier chunks if the job fails in the middle.
Show answer
A synchronous transaction can retrieve at most 50,000 rows with SOQL and process at most 10,000 rows with DML, so 3 million records exceed these limits. Batch Apex splits the records into chunks and runs each chunk's execute call in its own transaction, so the limits reset for every chunk. If the job fails in the middle, only the failing chunk is rolled back. Chunks that already finished stay committed, so the job should be written so it can be safely run again.
Exercise
For each task, choose Batch Apex or another tool and give one reason: (a) a trigger needs to call an external service once after saving a single record, (b) a nightly job must clean 4 million old Task records, (c) an admin wants to set a status field on 200 Cases every Monday.
Show answer
(a) Queueable Apex, because it is a single small follow-up task and a batch job adds queue overhead. (b) Batch Apex, because 4 million records cannot fit in one transaction and the work is not urgent. (c) A scheduled Flow, because 200 records is small and an admin can maintain it without code.