Sub topic 7
Batch Apex: processing large data volumes
This chapter assumes you know basic Apex syntax, SOQL and DML, governor limits at a high level, and how to write a simple unit test. It covers the Batch Apex interface and how a batch job runs. Scope size and state get deeper treatment in the next chapter.
Why Batch Apex exists
A future method or Queueable job still runs inside one transaction. That transaction has a fixed budget for SOQL rows, DML rows, and CPU time. If you need to touch hundreds of thousands of records, one transaction cannot do it.
Batch Apex splits the work into slices. Each slice runs in its own transaction with its own fresh set of governor limits. A job can therefore process millions of records, because no single transaction ever sees all of them.
The three methods
A batch class implements Database.Batchable<SObject>. The interface has three methods.
startruns once. It returns the full set of records to process.executeruns once per slice of records, called a scope. Each call is a separate transaction.finishruns once, after the lastexecute. Use it for summaries, notifications, or starting a follow-up job.
A worked example
This class finds leads that have not been modified in a year and marks them as stale.
public class StaleLeadBatch implements Database.Batchable<SObject>, Database.Stateful {
private Integer processed = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Description FROM Lead
WHERE IsConverted = false AND LastModifiedDate < LAST_N_DAYS:365
]);
}
public void execute(Database.BatchableContext bc, List<Lead> scope) {
for (Lead l : scope) {
l.Description = 'Stale';
}
update scope;
processed += scope.size();
}
public void finish(Database.BatchableContext bc) {
System.debug('Leads processed: ' + processed);
}
}
// Run it with a scope of 200 records per execute call:
Id batchId = Database.executeBatch(new StaleLeadBatch(), 200);Walk through what happens:
Database.executeBatchqueues the job and returns a job Id right away. The work does not run inside your current transaction.startreturns aQueryLocator. This object can stream up to 50 million records, which is far above the normal 50,000-row SOQL limit.- The platform hands the records to
executein groups of up to 200. Each call updates its own group. finishprints the total once every scope is done.
The second argument to executeBatch is the scope size. If you leave it out, the default is 200.
QueryLocator or Iterable
start can return one of two types.
| Return type | Use it when | Row limit |
|---|---|---|
| `Database.QueryLocator` | One SOQL query describes the records | Up to 50 million rows |
| `Iterable<SObject>` | The records come from custom logic, not a single query | Normal SOQL row limit applies to the query you run in `start` |
Prefer QueryLocator whenever one query is enough.
Behavior to remember
- Each
executecall is its own transaction. If one scope throws an unhandled exception, only that scope rolls back. Earlier scopes stay committed, and later scopes still run. - Member variables reset between
executecalls unless the class implementsDatabase.Stateful. The example uses it soprocessedsurvives. - Batch jobs wait in a queue. They may start a little after you call
executeBatch, and the order is not guaranteed across jobs. - An org can have only 5 batch jobs queued or active at one time. Extra jobs go to the Apex Flex Queue, which holds up to 100 jobs in the Holding status.
Common errors
- Putting a SOQL query inside
executefor each record. Query once per scope, using a set of Ids from the scope. - Expecting a variable to keep its value across scopes without
Database.Stateful. - Returning a huge
Listfromstartinstead of aQueryLocator. This uses heap memory and can hit limits.
Exercise
A batch job runs with a scope size of 200 and the query returns 1,000 records. How many times does each of start, execute, and finish run, and what happens to the other scopes if the third execute call throws an unhandled exception?
Show answer
start runs once, execute runs 5 times (1,000 / 200), and finish runs once. If the third execute call fails, only that scope's changes roll back. The first two scopes stay committed, and the fourth and fifth scopes still run.