Sub topic 7
Batch Apex: processing large data volumes
This chapter assumes you can write Apex classes, run SOQL and DML, and know the basics of governor limits and the synchronous transaction model. It also assumes you have written a simple unit test. It covers the structure of a Batch Apex class, how a batch job runs, and the mistakes that most often break one.
Why Batch Apex exists
Future methods and Queueable jobs run as a single transaction. That transaction has one set of governor limits. If you must process 2 million Lead records, one transaction cannot hold them all. A query in a transaction returns at most 50,000 rows, and heap and CPU limits would stop you well before that.
Batch Apex solves this by splitting the work. It queries a large set of records, cuts the result into slices called batches, and processes each slice in its own transaction. Each transaction gets a fresh set of governor limits. The total work can be far larger than any single transaction could handle.
Use Batch Apex when:
- The record count is large, or could grow large.
- You can describe the work as "for every record matching a query, do X".
- You want each slice of records to succeed or fail independently.
The Database.Batchable interface
A batch class implements Database.Batchable<SObject>. The interface has three methods.
| Method | Runs | Purpose |
|---|---|---|
| `start` | Once, at the beginning | Defines the full set of records to process |
| `execute` | Once per slice of records | Does the work on one slice, in its own transaction |
| `finish` | Once, at the end | Runs after all slices are done, for summaries and follow-up work |
The type in angle brackets, SObject, is the type of record that start returns. You can use a specific type such as Lead in the execute signature.
start
start returns either a Database.QueryLocator or an Iterable.
- A
QueryLocatoris built withDatabase.getQueryLocator. It supports up to 50 million records. The 50,000-row query limit does not apply to it. - An
Iterableis for data that does not come from one SOQL query, such as a list you built in code. With anIterable, the normal SOQL row limit applies to the queries that produce it.
Prefer a QueryLocator whenever the records come from a query.
execute
execute receives the BatchableContext and a list of records, called the scope. The default scope size is 200 records. Each execute call is a separate transaction. If one call throws an unhandled exception, only that slice rolls back. Slices that already finished stay committed, and the job moves on to the next slice.
finish
finish runs once after the last execute. Typical uses are sending a summary email, logging totals, or starting another job. It is a separate transaction too.
A complete batch class
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);Points to notice:
Database.executeBatchtakes an instance of the class and an optional scope size. It returns the Id of theAsyncApexJobrecord that tracks the job.- The
startquery runs once. The platform then holds the matching records and hands them out in slices. Database.Statefulis what letsprocessedkeep its value betweenexecutecalls. The next section explains why that matters.
How a batch job runs
After you call executeBatch, the job is placed in the flex queue or the batch queue and starts when system resources allow. It does not start immediately. Do not write code that assumes the work has begun by the next line.
Each execute call also runs in its own instance context. Salesforce serializes the batch object between calls. This is the reason instance variables reset between slices unless you use Database.Stateful.
Scope size and state
Choosing a scope size
The scope size is the second argument to executeBatch. Valid values are 1 to 2,000. The default is 200.
The trade-off:
- A larger scope means fewer transactions and a faster job overall. It also means each transaction uses more CPU time, heap, and DML rows, so it is more likely to hit a limit.
- A smaller scope is safer for heavy logic. It means more transactions, which adds queue overhead and slows the total run.
Choose by looking at what execute does per record.
| Work done in execute | Suggested scope size |
|---|---|
| Simple field updates, no callouts | 200 (default) up to 2,000 |
| Triggers, flows, or workflow fire on the update | 50 to 200 |
| Callouts, one per record | 1 to 100, limited by the callout cap per transaction |
| Complex calculation, high CPU or heap use | 10 to 100 |
If a slice fails with a limit exception, lower the scope. A LimitException cannot be caught, so lowering the scope is the usual fix.
Remember that DML in execute can fire triggers on the same records. Those triggers run in the same transaction as execute and share its limits. A scope of 200 can turn into much more work than the batch code itself suggests.
Keeping state with Database.Stateful
By default, a batch class does not remember its member variables between execute calls. Each call starts with the values the object had after construction. Add Database.Stateful to the class declaration to keep them.
public class OrderTotalBatch implements Database.Batchable<SObject>, Database.Stateful {
private Decimal runningTotal = 0;
private List<String> failedIds = new List<String>();
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id, Amount FROM Opportunity WHERE IsClosed = false]);
}
public void execute(Database.BatchableContext bc, List<Opportunity> scope) {
for (Opportunity o : scope) {
runningTotal += o.Amount == null ? 0 : o.Amount;
}
List<Database.SaveResult> results = Database.update(scope, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
failedIds.add(scope[i].Id);
}
}
}
public void finish(Database.BatchableContext bc) {
System.debug('Open pipeline: ' + runningTotal);
System.debug('Failed records: ' + failedIds.size());
}
}This example uses Database.update(scope, false). The second argument, allOrNone, set to false, lets good records save even when others in the slice fail. Without it, one bad record rolls back the entire slice.
Stateful has costs:
- The platform serializes the object after every
execute. A large collection, such as a list of thousands of Ids, slows every transaction and can exceed the heap limit. - Variables that cannot be serialized, such as some framework objects, can cause errors.
- Static variables never persist between slices, even with
Database.Stateful. Only instance members persist.
Keep stateful data small. If you must track many records, write them to a custom object instead of holding them in memory.
Constructors and parameters
A batch class often needs input, such as a record type or a date. Pass it through the constructor and store it in an instance variable. Instance variables set in the constructor are available in start, execute, and finish even without Database.Stateful, because the object is rebuilt with those values.
public class RegionLeadBatch implements Database.Batchable<SObject> {
private final String region;
public RegionLeadBatch(String region) {
this.region = region;
}
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Description FROM Lead WHERE Country = :region
]);
}
public void execute(Database.BatchableContext bc, List<Lead> scope) {
for (Lead l : scope) {
l.Description = 'Reviewed for ' + region;
}
update scope;
}
public void finish(Database.BatchableContext bc) {}
}Start it with Database.executeBatch(new RegionLeadBatch('Germany'), 200);. The bind variable :region works in Database.getQueryLocator because the query is static SOQL. For dynamic SOQL, pass a string to Database.getQueryLocator and escape user-supplied values with String.escapeSingleQuotes.
Limits that apply to batch jobs
- Up to 5 batch jobs can be queued or active at one time per org. Others wait in the flex queue.
- The flex queue holds up to 100 jobs in the
Holdingstatus. You can reorder them from the Apex Flex Queue page. - A
QueryLocatorcan return up to 50 million records. - Scope size is 1 to 2,000.
- Each
executecall has its own governor limits, but the limits are the usual asynchronous ones. For example, heap is 12 MB and CPU time is 60,000 ms, not the synchronous values. - A batch job can call
System.enqueueJobandDatabase.executeBatchfromfinish. Fromexecute, you can enqueue at most one Queueable job per call and cannot start another batch in anexecutethat is already running unless you account for the single-start rule. Starting a new batch fromfinishis the reliable way to chain. - Callouts from
executeneed the class to implementDatabase.AllowsCallouts.
public class PartnerPushBatch implements Database.Batchable<SObject>, Database.AllowsCallouts {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id, Name FROM Account WHERE Partner_Synced__c = false]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Partner_API/accounts');
req.setMethod('POST');
req.setBody(JSON.serialize(scope));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
for (Account a : scope) {
a.Partner_Synced__c = true;
}
update scope;
}
}
public void finish(Database.BatchableContext bc) {}
}Make the callout before the DML in each execute. A callout after uncommitted DML in the same transaction throws an error. This batch sends one callout per slice, so a scope of 200 stays inside the callout limit.
Common errors
- Instance variable resets to its initial value. The class lacks
Database.Stateful. Add it, or avoid relying on state. - Too many query rows: 50001.
startused anIterablebuilt from a normal query. Return aQueryLocatorinstead. - Uncatchable limit exception in
execute. The scope is too large for the work per record, or triggers on the updated object are heavy. Lower the scope. - Callout not allowed. The class does not implement
Database.AllowsCallouts. - Job never seems to start. It is waiting in the flex queue because five jobs are already active. Check the Apex Jobs page.
- Non-selective query in
start. AQueryLocatorcan be slow on large tables without a selective filter. Filter on indexed fields where possible.
Exercises
Exercise
A batch class counts matching records in a member variable called total and prints it in finish. The output is always 0, though the job updated thousands of records. What change fixes it?
Show answer
Add Database.Stateful to the class declaration (implements Database.Batchable<SObject>, Database.Stateful). Without it, the object is rebuilt for every execute call and member variables return to their initial values, so finish sees 0.
Exercise
Your batch's execute method updates Accounts, and a trigger on Account makes several callouts and heavy queries. Slices fail intermittently with limit exceptions at the default scope. What do you change, and why?
Show answer
Pass a smaller scope size to Database.executeBatch, for example 25 or 50. The trigger runs inside the same transaction as execute and shares its limits, so fewer records per slice means less work per transaction. Limit exceptions cannot be caught, so reducing the scope is the practical fix.
Exercise
A teammate writes start to return Database.getQueryLocator('SELECT Id FROM Contact') and says the job can handle 10 million contacts. Another teammate says it will hit the 50,000 row limit. Who is right?
Show answer
The first teammate. A QueryLocator bypasses the 50,000-row SOQL limit and can return up to 50 million records. The 50,000 limit would apply if start returned an Iterable built from a regular query.