Sub topic 5
What happens inside each execute call
This chapter assumes you can write Apex classes, run SOQL and DML, and know the basic synchronous governor limits. It also assumes you have seen the start, execute and finish outline of a batch class. Here we look at what the platform does each time it calls execute, and what that means for your code.
One chunk, one transaction
A batch job does not run as one long transaction. The platform takes the records that start produced and cuts them into chunks. It then calls execute once per chunk. Each call is its own transaction with its own set of governor limits.
For a job of 2,000,000 records and a batch size of 200, the platform makes 10,000 execute calls. The limits reset before each call. You can issue up to 150 DML statements, 100 SOQL queries and 10,000 DML rows in every one of them.
The diagram shows chunks side by side, but in practice the platform processes them one after another for a single job. Do not assume any particular order or timing between chunks beyond that.
What the platform gives you
The execute signature has two parameters:
Database.BatchableContext bcidentifies the job. Callbc.getJobId()to get theAsyncApexJobId.List<SObject> scopeholds the chunk. Whenstartreturns aQueryLocator, the list type can be a concrete type such asList<Account>. The records contain only the fields you selected in the locator query.
The scope list is at most as long as the batch size. The last chunk is usually smaller. A job can also receive fewer records than expected if a record was deleted between start and execute.
The limits that still apply
Resetting limits per chunk does not remove them. Your code in one execute call must still fit inside a single asynchronous transaction. The main limits are:
| Limit | Value per execute call |
|---|---|
| SOQL queries | 200 |
| DML statements | 150 |
| DML rows | 10,000 |
| CPU time | 60,000 ms |
| Heap size | 12 MB |
| Callouts | 100 |
Batch Apex runs asynchronously, so it gets the asynchronous limits. The SOQL query limit is 200 rather than the synchronous 100, CPU time is 60 seconds rather than 10, and heap is 12 MB rather than 6 MB. The scope records themselves count toward heap, so a wide record with long text fields uses much more memory than a narrow one.
The batch size is the main tool for staying under these limits. If each record triggers 3 DML rows in related objects, a chunk of 200 uses 600 rows. If each record triggers 60, the same chunk needs 12,000 rows and fails. Chapter content on tuning the batch size covers this in more depth.
Bulkify inside execute
Each call receives up to 200 records by default, so the same rules apply as in a trigger. Do not run a query or a DML statement inside the loop over scope. Collect the Ids, query once, and update once.
The example below finds the open opportunity count for each account in the chunk using one query, not one query per account.
public class OpenOppCountBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id FROM Account]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
Map<Id, Integer> counts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acc, COUNT(Id) total
FROM Opportunity
WHERE AccountId IN :scope AND IsClosed = false
GROUP BY AccountId
]) {
counts.put((Id) ar.get('acc'), (Integer) ar.get('total'));
}
List<Account> toUpdate = new List<Account>();
for (Account a : scope) {
Integer n = counts.containsKey(a.Id) ? counts.get(a.Id) : 0;
toUpdate.add(new Account(Id = a.Id, NumberOfEmployees = n));
}
update toUpdate;
}
public void finish(Database.BatchableContext bc) {}
}The class uses NumberOfEmployees only so the example runs in any org. In real code you would write the count to a custom field. The loop makes no queries and no DML. The aggregate query uses IN :scope, which Apex accepts for a list of records, and it returns at most one row per account.
Commit and rollback behavior
Every execute call commits on its own. If chunk 5 succeeds and chunk 6 throws an unhandled exception, chunk 5 stays saved. The platform rolls back only the failed chunk.
- A successful
executecommits its DML when the method returns. - An unhandled exception rolls back all DML in that call. The job records the error, increments the error count, and moves on to the next chunk.
- The job does not stop on a failed chunk. It continues with the remaining chunks.
- There is no automatic retry. If you need the failed records processed again, your job must find and requeue them.
Why a full-job failure is rare but a chunk failure is common
Most failures come from the data in one chunk, such as a validation rule that rejects a single record, a lock on a parent record, or a record with unusually large text. With the default behavior, one bad record rolls back all 200 records in its chunk. The other 199 are not saved, even though they were fine.
You have two ways to limit that damage:
- Use
Database.update(scope, false)so valid records save and failed records are reported, as covered in the chapter on partial failures. - Use a smaller batch size so a failure affects fewer records.
Static variables and instance variables
Each execute call is a separate transaction, and by default the platform creates a fresh state for it. Instance variables on your batch class do not keep their changes from one call to the next unless the class implements Database.Stateful. Without it, the class is serialized after each call and restored with the values it had when the job started.
Static variables are reset per transaction in all cases. Database.Stateful does not preserve them. If you need to carry a value across chunks, use an instance field on a Database.Stateful class.
public class CounterBatch implements Database.Batchable<SObject> {
public Integer seen = 0; // not Stateful: resets for every chunk
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id FROM Account]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
seen += scope.size();
System.debug('seen = ' + seen); // prints the chunk size every time
}
public void finish(Database.BatchableContext bc) {
System.debug('seen in finish = ' + seen); // prints 0
}
}Adding Database.Stateful to the implements list changes the output so that seen grows with each chunk and finish prints the total.
Things you cannot do in execute
- Calling
Database.executeBatchmore than once is not allowed fromexecute. A batch job can start another job fromfinish, and in some contexts it can enqueue one Queueable. Starting a batch fromexecuteis restricted, so use chaining fromfinishinstead. - Calling
@futuremethods from a batchexecuteis not allowed. - Making a callout requires
Database.AllowsCalloutson the class, and you cannot make a callout after DML in the same transaction.
Debugging a single chunk
When a chunk fails, find out which one. The AsyncApexJob record shows NumberOfErrors, but not which records failed. To see the exception, check the Apex Jobs page, the debug log for the job's user, or an email from Salesforce to the user who started the job. To find the failing records, log the Ids inside a try and catch block:
public void execute(Database.BatchableContext bc, List<Account> scope) {
try {
update scope;
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, 'Chunk failed: ' + e.getMessage()
+ ' first Id: ' + scope[0].Id);
throw e;
}
}Rethrowing keeps the error count accurate on the job record. If you swallow the exception, the job reports success even though the chunk was rolled back.
Exercise
A batch job runs with a batch size of 200 over 1,000 accounts. The 3rd chunk throws an unhandled exception in execute. What is the state of the data afterward, and does the job process chunks 4 and 5?
Show answer
Chunks 1, 2, 4 and 5 are committed, because each execute call is its own transaction. Chunk 3 is rolled back, so its 200 records are unchanged. The job records one error and continues with chunks 4 and 5, so they are processed. The platform does not retry chunk 3 on its own.
Exercise
Why does a counter field on a batch class that does not implement Database.Stateful print the chunk size on each execute call, and what is the smallest change that makes it count across the whole job?
Show answer
Without Database.Stateful, the platform restores the class to the state it had at the start of the job before each execute call, so changes to instance fields are lost. Adding Database.Stateful to the implements list makes the platform save the instance fields between calls, so the counter accumulates.