Sub topic 7
Choosing and tuning the batch size
This chapter assumes you can write a basic Database.Batchable class with start, execute and finish. You should also know SOQL, DML and the main per-transaction governor limits. If you need to review them, see the earlier chapters on governor limits and on the anatomy of a batch class.
What the batch size controls
The batch size is the number of records passed to each call of execute. You set it with the second argument of Database.executeBatch:
Id jobId = Database.executeBatch(new AccountRatingBatch(), 200);Every execute call runs in its own transaction with its own set of governor limits. The batch size therefore decides two things:
- How many records share one set of limits.
- How many transactions the whole job needs.
If you omit the argument, the default is 200. The allowed range is 1 to 2,000. Salesforce rejects values outside that range at runtime.
A job over 1,000,000 records shows how much the size matters:
| Batch size | Number of execute calls | Records sharing one set of limits |
|---|---|---|
| 2,000 | 500 | 2,000 |
| 200 | 5,000 | 200 |
| 50 | 20,000 | 50 |
| 1 | 1,000,000 | 1 |
Larger batches finish sooner because they avoid per-transaction overhead. Smaller batches leave more room under the limits, so each transaction is less likely to fail.
How the size interacts with the data source
The start method decides how the batch size is applied. With a QueryLocator, the platform can hand out up to 2,000 records per execute call, and the query itself can return up to 50 million records. With an Iterable, the total number of records retrieved by SOQL is still limited to the normal 50,000-row query limit. This affects what batch size you can sensibly use, because the iterable path loads records through ordinary Apex.
The batch size does not change which records are processed. It only changes how they are grouped.
Limits that depend on the batch size
Several limits are counted per execute call, so they scale with the number of records you process in it. These are the ones that most often force a smaller batch size:
- CPU time. The synchronous limit of 10,000 ms applies to each
executecall. Heavy logic per record, such as string handling, sorting or complex calculations, uses this quickly. - DML statements and rows. A call can run 150 DML statements and process 10,000 DML rows. A batch size of 2,000 is safe if you update each record once. It is not safe if your code also inserts two or three child records for every parent.
- SOQL queries. A call can run 100 queries. Queries inside a loop over the scope are a problem whatever the batch size, but they fail much sooner at larger sizes.
- Heap size. Each call has a 6 MB heap limit. Large text fields, attachments, or maps built from related data can exhaust it.
- Callouts. A call can make 100 callouts, and the total callout time is limited. If each record needs a callout, the batch size must not exceed 100. In practice, it needs to be much lower.
The effective limit is whichever of these you reach first. This is why the right size depends on the job and not on the number of records.
A simple way to choose a size
Use the following approach, which is deliberately conservative:
- Start with the default of 200.
- Count the worst-case resource use per record: DML rows, callouts, queries and CPU time.
- Divide each limit by that per-record cost. The smallest result is the largest size you can use.
- Reduce that number by a margin, for example to 50 to 70 percent of it, to cover records that cost more than average.
- Test with realistic data and check the results.
For example, suppose each record triggers one callout and creates one child record. The callout limit of 100 gives a ceiling of 100 records. The DML row limit of 10,000 allows 5,000 records, because each record causes two DML rows (the parent update and the child insert). The callout limit is the smaller number, so the batch size has to be below 100. A size of 50 leaves room for retries or extra callouts.
Reasons to go larger
Raise the size above 200 when:
- The logic is simple, such as setting a field value.
- There are no callouts and no per-record queries.
- Triggers, flows and validation rules on the object are light.
- Total run time matters and the org has a short processing window.
Fewer, larger transactions mean less overhead. They also mean fewer database commits and fewer chances to hit row locks between jobs. Keep in mind that each larger transaction holds locks on more records for longer.
Reasons to go smaller
Lower the size below 200 when:
- You make callouts for each record, or one callout per small group of records.
- Triggers, flows or process automation on the updated object are expensive. They run inside your
executetransaction and use the same limits. - The records have large text or rich content that fills the heap.
- You see
UNABLE_TO_LOCK_ROWerrors. Fewer records per transaction means fewer locks held at once, and a shorter window for conflicts with other users. - You want failures to be easy to isolate. If a transaction fails, all records in that scope are affected, so a smaller scope limits the damage.
The cost of very small sizes
A batch size of 1 gives each record its own limits. It is tempting when a job keeps failing. It also creates a very large number of transactions, and each one is queued and started by the platform. A job that would finish in minutes at size 200 can take hours at size 1. Treat very small sizes as a short-term fix while you find the real cause, such as a query in a loop.
Tuning the batch size in practice
Tune by measuring. After a test run, query AsyncApexJob to see how the job behaved:
AsyncApexJob job = [
SELECT Id, Status, JobItemsProcessed, TotalJobItems, NumberOfErrors,
CreatedDate, CompletedDate
FROM AsyncApexJob
WHERE Id = :jobId
];
System.debug('Status: ' + job.Status);
System.debug('Chunks processed: ' + job.JobItemsProcessed + ' of ' + job.TotalJobItems);
System.debug('Errors: ' + job.NumberOfErrors);TotalJobItems is the number of execute calls. NumberOfErrors counts the calls that failed, not the records that failed. A rising NumberOfErrors after you increase the size tells you the new size is too high.
Inside execute, the Limits class lets you see how close a call came to the ceiling:
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = 'Cold';
}
update scope;
System.debug('Records: ' + scope.size());
System.debug('CPU: ' + Limits.getCpuTime() + ' / ' + Limits.getLimitCpuTime());
System.debug('DML rows: ' + Limits.getDmlRows() + ' / ' + Limits.getLimitDmlRows());
System.debug('Heap: ' + Limits.getHeapSize() + ' / ' + Limits.getLimitHeapSize());
}Run the job at one size, read the debug log and note which limit is closest to its ceiling. If the closest one is below about 50 percent, try a larger size. If it is above 80 percent, reduce the size. Repeat until the numbers are stable.
Common mistakes
- Choosing the size from the record count. The number of records in the org does not determine the right size. The work done per record does.
- Ignoring triggers and flows. Automation on the object adds to the limits you use in each call.
- Setting the size above the callout limit. If every record needs a callout, a size over 100 fails.
- Testing only with small data. A test with 10 records does not show heap or CPU problems that appear with 2,000.
- Hard-coding the size. A fixed number in code is hard to change. Consider reading it from a custom metadata type or a custom setting so that an administrator can adjust it without a deployment.
public class BatchConfig {
public static Integer sizeFor(String jobName, Integer fallback) {
Batch_Setting__mdt setting = Batch_Setting__mdt.getInstance(jobName);
if (setting != null && setting.Batch_Size__c != null) {
return Integer.valueOf(setting.Batch_Size__c);
}
return fallback;
}
}Integer size = BatchConfig.sizeFor('AccountRating', 200);
Database.executeBatch(new AccountRatingBatch(), size);This example assumes a custom metadata type named Batch_Setting__mdt with a number field Batch_Size__c, and a record whose developer name is AccountRating. Create these in your org before you run it.
Batch size in tests
In a test, Database.executeBatch runs only one execute call. If you insert more records than the batch size, the remaining records are not processed. Keep the test data within one batch, or set the size to at least the number of test records.
Exercise
A batch job updates each Contact and makes one callout per Contact to an external service. The job fails with a "Too many callouts" error at the default batch size. What is the largest batch size that can work, and what would you choose in practice?
Show answer
The limit is 100 callouts per transaction, and the job makes one callout per record, so the size cannot exceed 100. In practice, choose a lower value such as 50, which leaves room for extra callouts such as a token refresh or a retry. The batch class also needs to implement Database.AllowsCallouts.
Exercise
You raised the batch size from 200 to 2,000. The job now finishes faster but NumberOfErrors in AsyncApexJob is greater than zero, and the logs show a heap limit error. What should you do?
Show answer
Lower the batch size, because each execute call now holds too much data in memory. Use the Limits class to read heap usage, reduce the size until usage is well below the 6 MB limit, and consider querying fewer fields or releasing large collections once they are no longer needed.