Sub topic 16
Designing for millions of records
This chapter assumes you can write a Database.Batchable class, know the start, execute and finish methods, and understand Database.Stateful and Database.update(records, false). It covers the design choices that keep a job with millions of records fast, cheap to retry and safe to run.
Make the query selective
A QueryLocator can return up to 50 million records, but the query still has to run. A filter on an unindexed field or a negative filter such as != can force a full table scan. Filter on indexed fields (Id, lookups, CreatedDate, external IDs), and select only the fields execute uses. Fewer fields means less memory per chunk.
Make the job safe to re-run
A job over millions of rows will eventually fail partway, or you will abort it. Design execute so that running it twice on the same record does no harm. The simplest way is to let the query exclude records that are already done.
public class AccountRatingBatch implements Database.Batchable<SObject>, Database.Stateful {
private static final Integer MAX_LOGGED = 100;
public Integer succeeded = 0;
public Integer failed = 0;
public List<String> sampleErrors = new List<String>();
public Database.QueryLocator start(Database.BatchableContext bc) {
// Finished records no longer match, so a re-run picks up only the rest.
return Database.getQueryLocator([
SELECT Id FROM Account WHERE Rating = null
]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = 'Cold';
}
List<Database.SaveResult> results = Database.update(scope, false);
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
succeeded++;
} else {
failed++;
if (sampleErrors.size() < MAX_LOGGED) {
sampleErrors.add(scope[i].Id + ': ' + results[i].getErrors()[0].getMessage());
}
}
}
}
public void finish(Database.BatchableContext bc) {
System.debug('Succeeded: ' + succeeded + ', failed: ' + failed);
}
}Records that failed still match Rating = null, so the next run retries them. A batch job also does not need a new status field for this. Any condition that naturally becomes false after processing works.
Keep state small
Database.Stateful serializes the instance between every execute call. Counters are cheap. A list holding every failed record is not, and it can exhaust the heap late in a long run. In the code above, the counters grow without limit but the error list stops at 100. If you need a full error record, insert rows into a custom log object from execute instead.
Tune around the whole system
- Batch size: pick the largest size that stays inside CPU, heap and DML limits. Lower it if triggers, flows or callouts make each record expensive.
- Automation: each
updatefires triggers and flows on that object. Heavy automation is often the real bottleneck, so measure before you change the batch size. - Concurrency: up to five batch jobs can be queued or active at once. Extra jobs wait in the Flex Queue, which holds up to 100. Avoid starting many large jobs on the same object, because they can cause row lock errors.
- Order: chain jobs from
finishwhen one depends on another.
Exercise
A nightly batch job fails halfway through 5 million records. Name two design choices that make the next run cheap and safe.
Show answer
First, filter the query on a condition that finished records no longer match (or a processed flag), so the re-run only reads the remaining records and repeats no work. Second, use Database.update(scope, false) and keep only counters or a capped error list in Database.Stateful fields, so one bad record does not roll back a chunk and the saved state does not grow until it exhausts the heap.