Sub topic 8
Choosing batch scope size and keeping state across batches
This chapter assumes you can write a basic Batch Apex class with start, execute, and finish, and that you know governor limits at a high level. It covers two decisions you make when you run a batch job: how many records go into each execute call, and how to carry data from one execute call to the next.
Scope size: what it controls
The scope size is the number of records passed to each execute call. You set it in the second argument of Database.executeBatch. If you leave it out, the default is 200. The maximum is 2,000.
Each execute call runs in its own transaction with its own set of governor limits. That means scope size decides how much work shares one set of limits. A larger scope means fewer transactions and less overhead. A smaller scope means each transaction has more headroom.
// 200 records per execute call (the default)
Database.executeBatch(new StaleLeadBatch());
// 50 records per execute call
Database.executeBatch(new StaleLeadBatch(), 50);How to pick a number
Start with the default and lower it only when you have a reason. Common reasons:
- Callouts. Each
executecall can make up to 100 callouts. If every record needs one callout, a scope above 100 fails. - CPU time. Complex logic, triggers, and flows that fire on your DML all count against the CPU limit of the transaction. If you see "Apex CPU time limit exceeded," reduce the scope.
- Row-locking conflicts. Smaller scopes lock fewer records at once, which can reduce
UNABLE_TO_LOCK_ROWerrors. - Failure cost. If one record throws an unhandled exception, the whole scope rolls back. A smaller scope limits how many records are affected.
Raise the scope only when the logic is light and you want fewer transactions.
| Situation | Suggested scope |
|---|---|
| Simple field updates, no callouts | 200 (default) or higher |
| Heavy triggers or flows on the object | 50 to 100 |
| One callout per record | 100 or lower |
| Frequent lock errors | Lower until errors stop |
Keeping state with Database.Stateful
By default, a batch class is stateless. Each execute call gets a fresh copy of the class, so member variables reset. If you add a counter and increment it in execute, finish sees the starting value.
To keep member variables across calls, implement Database.Stateful alongside Database.Batchable. This is what the processed counter in StaleLeadBatch does.
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);Costs and limits of Stateful
Stateful is not free. Salesforce serializes the class after each execute call and restores it before the next one. Keep these points in mind:
- Large state slows the job. Do not accumulate thousands of full sObjects. Store counts or sets of Ids instead.
- Everything in the state must be serializable. Avoid fields that hold non-serializable objects.
- Without Stateful, DML changes still persist. Only the member variables reset.
Common errors
- Reading a counter in
finishand getting zero because the class is not Stateful. - Setting a scope of 200 when each record makes a callout, which exceeds the 100-callout limit.
- Treating a failed scope as a failed job. Other scopes still run, and only the failed scope's changes roll back.
Exercise
A batch class makes one HTTP callout per record and counts the failures in a member variable that finish logs. The job runs with the default scope and finish always logs 0 failures, even though some callouts fail. What two changes fix it?
Show answer
Add Database.Stateful to the class declaration so the failure counter keeps its value across execute calls and into finish. Also lower the scope size to 100 or less when calling Database.executeBatch, because each execute call is limited to 100 callouts and the default scope of 200 would exceed that.