What factors determine the optimal batch size parameter when calling Database.executeBatch()?
Answer
Basics: Database.executeBatch(job, size) sets how many records are handed to each execute(). Each chunk is its own transaction, so size trades fewer transactions (faster, fewer async executions) against the risk of hitting a limit and failing the whole chunk.
How it works:
- Records are sliced into scopes of the given size.
- Each scope runs in its own transaction with fresh limits (async: 12 MB heap, 60,000 ms CPU, 200 SOQL).
- If any uncaught error or limit hit occurs, only that chunk rolls back.
Advanced / deep dive: Reduce the size when: there is one callout per record (max 100 callouts per transaction, so size at most 100 or fewer), triggers, flows or heavy logic run on the DML, records carry large text or blob fields, or parent-record row locks (UNABLE_TO_LOCK_ROW) appear when many children update the same parent. Increase it for light-touch updates to cut the count of executions, which count toward the daily async limit (greater of 250,000 or licenses x 200). Measure with Limits.getCpuTime() and Limits.getHeapSize() logged in execute(), and look at Apex Jobs for time per batch. Making the size configurable (Custom Metadata) lets admins tune without a deployment. Also remember Database.Stateful growth and that chunk order is not guaranteed.
Code / config example:
// Conservative size for a job that does one callout per record
Id jobId = Database.executeBatch(new SyncBatch(), );
Batch_Config__mdt.getInstance();
(cfg != && cfg.Scope_Size__c != ) ? Integer.valueOf(cfg.Scope_Size__c) : ;
Database.executeBatch( (), size);