Sub topic 8
Choosing batch scope size and keeping state across batches
This chapter covers two decisions you make every time you write a Batch Apex class. The first is how many records each execute call receives. The second is whether data should survive from one execute call to the next. It assumes you can write a basic Batchable class with start, execute, and finish, and that you know SOQL, DML, and governor limits at a high level.
What a scope is
Batch Apex splits the records returned by start into chunks. Each chunk is called a scope. Salesforce calls execute once per scope, and each call runs as its own transaction with its own fresh set of governor limits.
You choose the scope size with the second argument of Database.executeBatch:
Id batchId = Database.executeBatch(new StaleLeadBatch(), 200);The rules for the size:
- The default is 200 if you leave the argument out.
- The minimum is 1.
- The maximum is 2000.
- A value above 2000 is capped at 2000.
Because every execute call is a separate transaction, a failure in one scope rolls back only that scope. Scopes that already finished stay committed, and scopes that have not started yet keep running unless you abort the job. A batch job is not atomic as a whole.
How scope size affects limits
Each execute call gets the normal asynchronous limits. The scope size decides how much of that budget the call spends. Examples of limits that matter:
| Limit (per `execute` call) | Value | How scope size affects it |
|---|---|---|
| SOQL queries | 200 | Queries inside a loop over the scope add up quickly. |
| DML rows | 10,000 | A scope of 2000 records with 6 DML rows each exceeds it. |
| Heap size | 12 MB | A large scope with wide records can run out of memory. |
| CPU time | 60,000 ms | Complex logic per record multiplies with scope size. |
| Callouts | 100 | A scope larger than 100 fails if each record needs a callout. |
The DML row limit often decides the size. Suppose your execute method updates each Lead and also inserts two related Task records. Each Lead then costs 3 DML rows. A scope of 200 uses 600 rows, which is fine. A scope of 2000 uses 6000, which still fits. If each Lead cost 6 rows, a scope of 2000 would need 12,000 and would fail.
Picking a size
Start with the default of 200 and change it only for a reason. These are the common reasons.
| Situation | Direction | Why |
|---|---|---|
| Simple field updates, no triggers | Raise toward 1000–2000 | Fewer transactions means less overhead and a faster job. |
| Heavy triggers, flows, or many related records | Lower to 50–100 | Automation on the records consumes limits in the same transaction. |
| One callout per record | Set 100 or below | The callout limit is 100 per transaction. |
| Row-lock errors with other processes | Lower | Smaller transactions hold locks for less time. |
| Slow external service | Lower | A short transaction is less likely to hit a timeout. |
Triggers and flows on the records you update run inside the same execute transaction. They share its limits. A batch that looks safe at scope 200 can fail once someone adds a trigger that runs more queries. Test with realistic data volumes and automation turned on.
State does not persist by default
Salesforce creates a new instance of your batch class for each execute call. Member variables reset to their initial values, and static variables do not carry over either. The following counter looks right but always reports 0 in finish:
public class BrokenCounterBatch implements Database.Batchable<SObject> {
private Integer processed = 0; // reset on every execute call
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM Lead');
}
public void execute(Database.BatchableContext bc, List<Lead> scope) {
processed += scope.size();
}
public void finish(Database.BatchableContext bc) {
System.debug('Processed: ' + processed); // prints 0
}
}Keeping state with Database.Stateful
Add Database.Stateful to the implements list and Salesforce serializes the member variables at the end of each execute call and restores them before the next one. Values you set in one call are then visible in the next calls and in finish.
The following class counts successes and keeps the Ids of failed records. It uses Database.update with allOrNone set to false, so one bad record does not roll back the whole scope.
public class LeadCleanupBatch implements Database.Batchable<SObject>, Database.Stateful {
private Integer successCount = 0;
private Set<Id> failedIds = new Set<Id>();
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';
}
List<Database.SaveResult> results = Database.update(scope, false);
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
successCount++;
} else {
failedIds.add(scope[i].Id);
}
}
}
public void finish(Database.BatchableContext bc) {
AsyncApexJob job = [
SELECT Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
FROM AsyncApexJob
WHERE Id = :bc.getJobId()
];
System.debug('Status: ' + job.Status);
System.debug('Updated: ' + successCount + ', failed: ' + failedIds.size());
}
}Run it with a smaller scope if the Lead object has heavy automation:
Id jobId = Database.executeBatch(new LeadCleanupBatch(), 100);The data flows through the job like this:
The cost of Stateful
State is not free. Keep these points in mind:
- Salesforce serializes the whole object after every
executecall. A large state makes each call slower and can slow the entire job. - The heap limit still applies. A
List<Lead>that grows across thousands of calls will eventually exceed 12 MB. Store Ids, counts, or short strings instead of full records. - Every member variable must be serializable. Using a type that cannot be serialized causes a runtime error when the state is saved.
- The state belongs to one job. Two jobs started from the same class do not share it.
- Static variables are not preserved, even with
Database.Stateful. Use instance variables.
If you only need a total at the end, you can avoid state entirely. Query the results in finish, or write a log record from each execute call and summarize later. For the job-level counts shown above, AsyncApexJob already stores JobItemsProcessed and NumberOfErrors for free.
Edge cases
- Scope size and callouts. If you call an external service, the class must also implement
Database.AllowsCallouts. Keep the scope at or below the number of callouts you make per record divided into 100. - Failures with
allOrNonetrue. With a plainupdate scope;, one bad record rolls back the whole scope, and the job moves on to the next one. The failed records stay unprocessed. Use the partial-success form shown above when you want the good records to save. - Scope in tests. A test that calls
Database.executeBatchruns only oneexecutecall, so keep test data within a single scope. - Iterable batches. If
startreturns anIterableinstead of aQueryLocator, the scope size rules are the same. TheQueryLocatorcan supply up to 50 million records, while an iterable is limited by the row and heap limits of thestarttransaction.
Putting it together
- Begin with the default scope of 200.
- Count the DML rows, queries, and callouts one record costs, including automation, and check that a full scope fits in the limits.
- Change the size only when the limits, locks, or run time give you a reason.
- Add
Database.Statefulonly for values that must survive between scopes, and store the smallest values that do the job. - Use
Database.update(scope, false)and aSet<Id>of failures when partial success is acceptable.
Exercise
A batch job updates each Account and inserts 15 related Case records per Account in execute. What is the largest scope size that stays inside the 10,000 DML row limit, and why? Also, why would a counter field declared as private Integer total = 0; report 0 in finish unless you add Database.Stateful?
Show answer
Each Account costs 1 row for the update plus 15 for the inserts, which is 16 DML rows. 10,000 / 16 = 625, so the largest safe scope is 625. In practice choose a lower value such as 500 to leave room for triggers. Without Database.Stateful, each execute call runs on a fresh instance, so member variables reset to their initial value of 0. Only Database.Stateful makes Salesforce save and restore them between calls.
Exercise
Your stateful batch stores every failed Lead record in a List<Lead> and fails with a heap error after many scopes. What should you change?
Show answer
Store only what finish needs, such as a Set<Id> of failed record Ids or a count, instead of full sObjects. This keeps the serialized state small and under the 12 MB heap limit. Query the records again in finish if you need more details.