Sub topic 5
What happens inside each execute call
This chapter assumes you can read the start, execute and finish skeleton from the previous chapter and that you know basic governor limits.
One chunk, one transaction
Salesforce calls execute once for every chunk of records the start method produced. Each call runs as its own transaction. The platform starts the transaction, passes in a list of records called the scope, runs your code, and commits or rolls back. Then it moves to the next chunk.
Three consequences follow.
- Governor limits reset for every call. Each
executegets a fresh set of limits, using the asynchronous values. For example, you get 200 SOQL queries, 150 DML statements and 12 MB of heap per call. You do not get these across the whole job. - Failures are isolated. If
executethrows an unhandled exception, Salesforce rolls back that chunk only. Chunks that already committed stay committed. The job records the error and continues with the remaining chunks. - Calls are serial. The
executecalls of one job run one after another, not in parallel. The order is not guaranteed, so do not depend on it.
Bulkify inside the chunk
The limits reset per call, but they still apply within a call. A batch size of 200 with a query inside the loop would run 200 queries and reach the limit. Query once per chunk and look the results up in a map.
public class AccountOpenOppBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id, Description FROM Account]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
Map<Id, Integer> openCounts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acct, COUNT(Id) total
FROM Opportunity
WHERE IsClosed = false AND AccountId IN :new Map<Id, Account>(scope).keySet()
GROUP BY AccountId
]) {
openCounts.put((Id) ar.get('acct'), (Integer) ar.get('total'));
}
for (Account a : scope) {
Integer n = openCounts.containsKey(a.Id) ? openCounts.get(a.Id) : 0;
a.Description = 'Open opportunities: ' + n;
}
update scope;
}
public void finish(Database.BatchableContext bc) {}
}This execute uses one SOQL query and one DML statement per chunk, however many records the job processes in total.
Common errors
| Mistake | What happens |
|---|---|
| Storing a running total in an instance variable | The value is lost between calls, because each `execute` may run on a freshly deserialized instance. Implement `Database.Stateful` to keep it. |
| Relying on static variables across calls | Statics reset for every transaction. |
| Expecting one failure to stop the job | Only the failing chunk rolls back. The job continues, so the data ends up partly processed. |
| Querying or updating inside the `for` loop | The per-call limits are reached even though they reset between calls. |
Exercise
A batch job has 1,000 records and a batch size of 200. The third execute call throws an unhandled exception. What happens to the records in chunks 1, 2, 4 and 5?
Show answer
Chunks 1 and 2 were already committed and stay saved. The third chunk is rolled back. The job does not stop, so chunks 4 and 5 still run in their own transactions and commit if they succeed. Only the 200 records in chunk 3 are unprocessed.