Sub topic 9
Handling partial failures
This chapter assumes you can write a basic Database.Batchable class and know what Database.Stateful does. It covers what happens when some records in a batch job fail, and how to make the job report those failures instead of losing them.
Why partial failure is the normal case
A job that processes a million records will meet bad data. Validation rules fire, required fields are empty, records are locked, and triggers throw exceptions. The design question is not how to prevent every failure. It is how much work each failure destroys, and whether you find out about it.
Each execute call runs in its own transaction. That gives you three levels of failure.
| Failure | What is rolled back | What happens next |
|---|---|---|
| A record fails inside `Database.update(scope, false)` | Only that record | The rest of the chunk saves. The job continues. |
| An unhandled exception in `execute` | The whole chunk, including its DML and any callouts' side effects in Salesforce | The job logs an error for that chunk and moves on to the next chunk. |
| An exception in `start` | Nothing has run yet | The job ends and no `execute` or `finish` call happens. |
Earlier chunks stay committed when a later chunk fails. A batch job is not one transaction, so you cannot roll the whole job back.
What a plain DML statement does
A statement such as update scope; is all-or-none. If one record in the chunk fails, Salesforce throws a DmlException and rolls back every change in that execute call. If you do not catch it, all 200 records fail because of one bad record.
Salesforce then starts the next chunk. The failed chunk is not retried. The job's NumberOfErrors field on AsyncApexJob goes up, and finish still runs.
Use partial-success DML
Pass false as the allOrNone argument. Salesforce saves every record that passes and returns one result per record, without throwing an exception for data errors.
Database.insertandDatabase.updatereturnList<Database.SaveResult>.Database.upsertreturnsList<Database.UpsertResult>.Database.deletereturnsList<Database.DeleteResult>.
The result list is in the same order as the input list. You can use the index to find the record that failed. For an insert, a failed record has no Id, so the index is the only link back to the input.
public class AccountRatingBatch implements Database.Batchable<SObject>, Database.Stateful {
private static final Integer MAX_LOGGED = 200;
public Integer succeeded = 0;
public Integer failed = 0;
public Map<Id, String> errors = new Map<Id, String>();
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Rating 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++) {
Database.SaveResult sr = results[i];
if (sr.isSuccess()) {
succeeded++;
} else {
failed++;
if (errors.size() < MAX_LOGGED) {
Database.Error err = sr.getErrors()[0];
errors.put(scope[i].Id, err.getStatusCode() + ': ' + err.getMessage());
}
}
}
}
public void finish(Database.BatchableContext bc) {
AsyncApexJob job = [
SELECT Id, Status, NumberOfErrors
FROM AsyncApexJob WHERE Id = :bc.getJobId()
];
System.debug('Status: ' + job.Status + ', succeeded: ' + succeeded
+ ', failed: ' + failed + ', chunk errors: ' + job.NumberOfErrors);
for (Id recordId : errors.keySet()) {
System.debug(recordId + ' -> ' + errors.get(recordId));
}
}
}The class implements Database.Stateful, so succeeded, failed and errors keep their values from one execute call to the next. Without it, each chunk would start with fresh fields and finish would see zeros.
Keep failure logs small
State is serialized between chunks, and the job holds it in heap. Storing the full record and message for every failure in a million-record job can exhaust the heap or slow every chunk. The example above counts every failure but keeps details for only the first 200.
For a complete record of failures, write them out as you go instead of holding them in memory. Typical choices are:
- Insert rows into a custom log object in each
executecall, using a separateDatabase.insert(logs, false). - Publish a platform event for each failure.
- Keep only the failed record Ids, which are small, and retry them later.
If you write log rows, remember that they count against the same DML limits as your main work in that chunk.
Unhandled exceptions and platform events
Some failures cannot be caught. A governor limit exception such as System.LimitException cannot be handled with try/catch, and it fails the chunk. You will also see failures from a trigger or a flow that you did not write.
If your class also implements Database.RaisesPlatformEvents, Salesforce publishes a BatchApexErrorEvent whenever an unhandled exception ends a chunk, including limit exceptions. You can subscribe with a trigger.
public class ContactCleanupBatch implements Database.Batchable<SObject>, Database.RaisesPlatformEvents {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id, Description FROM Contact WHERE Description = null]);
}
public void execute(Database.BatchableContext bc, List<Contact> scope) {
for (Contact c : scope) {
c.Description = 'Reviewed';
}
update scope; // all-or-none: one bad record fails the whole chunk
}
public void finish(Database.BatchableContext bc) {}
}trigger BatchApexErrorTrigger on BatchApexErrorEvent (after insert) {
for (BatchApexErrorEvent evt : Trigger.new) {
System.debug('Job ' + evt.AsyncApexJobId + ' failed in phase ' + evt.Phase
+ ': ' + evt.ExceptionType + ' - ' + evt.Message);
System.debug('Records in the failed chunk: ' + evt.JobScope);
}
}JobScope holds the comma-separated Ids of the records in the failed chunk. That is what lets you reprocess exactly those records.
Which approach to choose
Use Database.update(scope, false) when a single bad record should not stop its neighbours, which is the usual case for data cleanup and enrichment. Use all-or-none DML when the records in a chunk depend on each other, for example a parent and its children, and a partial save would leave inconsistent data. In that case, keep related records in the same chunk by choosing the scope carefully, and rely on the platform event to tell you when a chunk failed.
Whatever you choose, the finish method is the place to decide what the failures mean. Check NumberOfErrors for chunk-level failures and your own counters for record-level ones. Then send an email, create a log record or start a retry job.
Making re-runs safe
A failed chunk is not retried, so you will usually run the job again. Design for that.
- Select only records that still need work, as in
WHERE Rating = null. A second run then skips records that already succeeded. - Avoid side effects that cannot be repeated, such as incrementing a counter field or sending an email for each record.
- If the selection criteria cannot show which records are done, add a status field and update it when a record succeeds.
- To retry only the failures, pass the failed Ids into a new batch's constructor and use them in the query.
public class RetryRatingBatch implements Database.Batchable<SObject> {
private Set<Id> ids;
public RetryRatingBatch(Set<Id> ids) {
this.ids = ids;
}
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Rating FROM Account WHERE Id IN :ids AND Rating = null
]);
}
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) {}
}Use this for a small, capped set of failures. A very large Set<Id> held in a constructor argument has the same heap cost described earlier.
Common mistakes
- Ignoring the return value.
Database.update(scope, false)never throws for data errors. If you drop the result list, failures disappear silently. - Assuming
Status = 'Completed'means success. A job can complete with chunk errors. Always checkNumberOfErrors. - Catching
Exceptionand doing nothing. This hides the failure and also leaves the transaction in whatever state it reached. - Storing every error in a stateful list. This can run the job out of heap on large runs.
Exercise
A batch job with a scope size of 200 uses update scope;. Record 57 of chunk 3 fails a validation rule. What happens to chunks 1, 3 and 4, and what would you change so that only record 57 fails?
Show answer
Chunk 1 stays committed, because it ran in its own transaction. Chunk 3 is rolled back completely, so all 200 records in it are unchanged. The exception increases NumberOfErrors, and chunk 4 still runs. To make only record 57 fail, call Database.update(scope, false), loop over the returned SaveResult list, and count or log the results where isSuccess() is false. Add Database.Stateful if you want the counts and logged errors available in finish.