Sub topic 16
Designing for millions of records
This chapter assumes you can write Apex classes and SOQL, and that you have already built a basic Database.Batchable class with start, execute and finish. It also assumes you know the earlier topics on batch size, Database.Stateful, partial failures and the job queue. Here those pieces are combined into design rules for jobs that touch millions of rows.
What changes at scale
A batch job with 5,000 records and one with 20 million records use the same interface. The risks are different.
- A job with 20 million records and a batch size of 200 runs 100,000
executecalls. A small cost per call becomes hours of runtime. - A single bad record, a locked parent record or a slow callout happens many times in a job of that size.
- A job that cannot be restarted safely becomes a manual cleanup task after the first failure.
The design goal is a job that is selective, cheap per chunk, tolerant of failure and safe to run again.
Limits that still apply to the job as a whole
Each execute call gets fresh per-transaction governor limits. Some limits are not per transaction.
| Limit | Value | Design consequence |
|---|---|---|
| Records returned by a `QueryLocator` in `start` | Up to 50 million | A larger set must be split across several jobs. |
| Records returned by an `Iterable` in `start` | The normal SOQL row limit of 50,000 applies to queries run in `start` | Use a `QueryLocator` for large sets. |
| Concurrent running batch jobs | 5 | Extra jobs wait in the queue. |
| Jobs waiting in the Holding (Flex Queue) status | 100 | Do not submit jobs in an unbounded loop. |
| Asynchronous Apex executions per 24 hours | The larger of 250,000 or 200 times the number of user licenses | Every `execute` call counts toward this total. |
Check the current values in the Salesforce Apex limits documentation before you rely on them, because Salesforce changes them between releases.
The last row matters most. Each chunk uses one asynchronous execution, so a job over 20 million records at batch size 200 uses 100,000 of them. Raising the batch size to 2,000 for the same job uses 10,000.
Make the query selective
The start query decides how much work the job does. A query on millions of rows with a non-selective filter can time out when it is opened.
Follow these rules.
- Filter on indexed fields.
Id,Name, lookup and master-detail fields,CreatedDate,SystemModstampand fields marked External ID or unique are indexed. - Avoid leading wildcards such as
LIKE '%abc', and avoid!=orNOTfilters on large tables. They usually prevent index use. - Select only the fields that
executereads. Fewer columns means less heap per chunk. - Avoid formula fields in the
WHEREclause. Most are not indexed. - Ask Salesforce to add a custom index if a field you must filter on is not indexed. Support can do this for custom fields.
The query plan tool in the Developer Console shows whether a filter uses an index. Use it on a sandbox that has production-like data volumes. A query that is fast on 1,000 test rows can fail on 10 million.
Make the job safe to re-run
A job that can fail partway through must be able to start again without doing the work twice. This property is called idempotence. Two techniques provide it.
The first is to filter out records that are already done. The example from the earlier chapters does this with Rating = null. After a record gets a rating, a second run does not select it.
The second is to record a marker on each record, for example a custom checkbox or a date field named Processed_On__c. The query then selects only rows where the marker is empty.
public class AccountRatingBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Rating
FROM Account
WHERE Rating = null
AND CreatedDate < :System.now()
]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = 'Cold';
}
Database.update(scope, false);
}
public void finish(Database.BatchableContext bc) {
}
}Avoid designs where the marker is set in a later step than the work itself. If the work succeeds and the marker update fails, the next run repeats the work. Set the marker in the same DML statement as the change.
Keep each chunk cheap
Because the platform runs every chunk in its own transaction, the cost of one chunk is the cost of your execute code. Keep it lean.
- Query related data once per chunk, not once per record. Collect the Ids in a
Set<Id>, run one query withIN :ids, and put the results in aMap. - Perform one DML statement per object type per chunk, on a list.
- Avoid
SELECT COUNT()and other queries over large tables insideexecute. Each one scans the table once for every chunk. - Skip work when possible. Check in memory whether a record needs a change before you add it to the list that is updated. Fewer DML rows means a faster job and less record locking.
public void execute(Database.BatchableContext bc, List<Contact> scope) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : scope) {
accountIds.add(c.AccountId);
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
List<Contact> toUpdate = new List<Contact>();
for (Contact c : scope) {
Account parent = accounts.get(c.AccountId);
if (parent != null && c.Description != parent.Industry) {
c.Description = parent.Industry;
toUpdate.add(c);
}
}
if (!toUpdate.isEmpty()) {
Database.update(toUpdate, false);
}
}Reduce side effects
Each updated record can fire triggers, flows, validation rules and duplicate rules. At 20 million rows these dominate the job's runtime.
- Review the automation on the object before you run a large job. A flow that sends an email for each update turns a batch job into millions of emails.
- Bypass automation only when the business agrees, and do it with a documented switch, for example a custom permission or a custom setting that your triggers check. Never remove validation permanently for a one-time job.
- Order the data to avoid lock conflicts. Many child records in the same chunk that share one parent can cause
UNABLE_TO_LOCK_ROWerrors when another job runs at the same time. Querying withORDER BY ParentIdgroups children of one parent into the same chunk, which reduces cross-chunk contention. Sorting can slow the query, so test it first.
Bound the state you keep
Database.Stateful serializes the class's fields after every chunk. A field that grows with each chunk, such as a list of every Id processed, makes each chunk slower and can eventually hit the heap limit.
Keep counters and small summaries. For per-record outcomes, write rows to a log object from execute instead of storing them in memory. Cap what you keep in a stateful list, for example the first 100 error messages.
Plan the failure path
At this scale some records will fail. Decide what happens before the job starts.
- Use
Database.update(scope, false)so one bad record does not roll back the whole chunk. - Count failures in a stateful field and log the record Id and message for each.
- Catch exceptions that affect the whole chunk, such as a callout timeout, and record the chunk's Ids so you can retry them.
- In
finish, compare the count of successes and failures with the expected total, and notify someone when failures exceed a threshold.
An unhandled exception in execute fails only that chunk. Earlier chunks stay committed, and the job continues with later chunks. The job status can still end as Completed, so check NumberOfErrors in finish.
Splitting very large sets
If the data set exceeds what one job should handle, split the input and run several jobs in sequence. Common approaches are by date range, by record Id range, or by a partition field such as region.
public class RangeAccountBatch implements Database.Batchable<SObject> {
private Datetime fromDate;
private Datetime toDate;
public RangeAccountBatch(Datetime fromDate, Datetime toDate) {
this.fromDate = fromDate;
this.toDate = toDate;
}
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Rating FROM Account
WHERE Rating = null
AND CreatedDate >= :fromDate AND CreatedDate < :toDate
]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = 'Cold';
}
Database.update(scope, false);
}
public void finish(Database.BatchableContext bc) {
}
}Run each range as its own job and chain them from finish, one at a time, so you stay within the concurrency and queue limits.
A design checklist
Test before production
- Run the job in a full or partial copy sandbox that has realistic data volume. Developer sandboxes rarely show query and locking problems.
- Start with a small range and check the result, then widen it.
- Time one chunk and multiply by the number of chunks to estimate total runtime.
- Test with failing records to confirm the logging and the
finishnotification work.
Exercise
A batch job must update 12 million Contact records. Each run takes eight hours, and the job sometimes fails midway because of lock errors. Name two design changes that make a restart safe and reduce the lock errors.
Show answer
Make the job idempotent by selecting only records that are not yet processed, for example with a Processed_On__c = null filter that is set in the same DML statement as the change, so a restart skips finished records. Reduce lock contention by ordering the query by AccountId so children of one parent fall in the same chunk, and by splitting the data into ranges that run one after another instead of at the same time.
Exercise
A stateful batch class stores every processed record Id in a List<Id> field. What goes wrong at 10 million records, and what is a better design?
Show answer
The list is serialized after every chunk, so each chunk gets slower, and the list can exceed the heap limit. Keep only counters and a capped list of errors in state, and write per-record results to a custom log object from execute if you need them.