Sub topic 12
Bounded retries and failure logging
This chapter assumes you can write a Queueable class, attach a finalizer with System.attachFinalizer, and read a FinalizerContext. It also assumes you know that DML in a failed transaction is rolled back. Here you combine those pieces into a retry that stops after a fixed number of attempts and records every failure.
Why retries need a bound
A finalizer runs after its parent queueable ends, whether the parent succeeded or not. When the parent died with an unhandled exception, the finalizer can enqueue the same work again. That is useful for transient failures such as a row lock, a timeout, or a remote system that is briefly down.
Without a bound, the same job fails and re-enqueues itself forever. It burns async capacity, floods the logs, and hides the real defect. A bounded retry has three parts:
- A counter that travels with the job.
- A rule that decides whether the failure is worth another attempt.
- A durable record of each failure, so a person can find out what happened.
Where the counter lives
A finalizer can't read the parent's variables after the parent ends. Both objects get the counter through their constructors. The queueable passes the current attempt number to the finalizer. If the finalizer re-enqueues, it passes attempt + 1 to the new job.
Putting the decision in one testable place
The retry rule should be a plain static method with no dependency on the platform's context objects. Plain methods are easy to test, and the finalizer stays short.
public class RetryPolicy {
public static final Integer MAX_ATTEMPTS = 3;
public static Boolean shouldRetry(ParentJobResult result, Integer attempt) {
return result == ParentJobResult.UNHANDLED_EXCEPTION
&& attempt < MAX_ATTEMPTS;
}
// Grows with each attempt and stays inside the 0-10 minute range
// that AsyncOptions.MinimumQueueableDelayInMinutes accepts.
public static Integer delayMinutes(Integer attempt) {
return Math.min(attempt * 2, 10);
}
}Attempts are numbered from 1. With MAX_ATTEMPTS = 3, the job runs at most three times: the original run and two retries.
The failure log object
The examples write to a custom object named Job_Failure__c. It has these fields:
| Field | Type | Purpose |
|---|---|---|
| `Job_Id__c` | Text(18) | The `AsyncApexJob` ID of the failed run |
| `Class_Name__c` | Text(80) | The queueable that failed |
| `Attempt__c` | Number(2,0) | Which attempt failed |
| `Message__c` | Text(255) | The exception message, shortened |
| `Will_Retry__c` | Checkbox | Whether another attempt was queued |
A custom object is better than System.debug here. Debug logs are only kept when a trace flag is active, and they expire. A record can be queried, put on a report, and used to trigger an alert.
The finalizer
public class ImportJob implements Queueable {
private List<Id> recordIds;
private Integer attempt;
public ImportJob(List<Id> recordIds, Integer attempt) {
this.recordIds = recordIds;
this.attempt = attempt;
}
public void execute(QueueableContext context) {
System.attachFinalizer(new ImportFinalizer(recordIds, attempt));
// Work that might throw an unhandled exception goes here.
}
}public class ImportFinalizer implements Finalizer {
private List<Id> recordIds;
private Integer attempt;
public ImportFinalizer(List<Id> recordIds, Integer attempt) {
this.recordIds = recordIds;
this.attempt = attempt;
}
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.SUCCESS) {
return;
}
Boolean retry = RetryPolicy.shouldRetry(ctx.getResult(), attempt);
Exception ex = ctx.getException();
String message = (ex == null) ? 'No exception detail' : ex.getMessage();
try {
insert new Job_Failure__c(
Job_Id__c = ctx.getAsyncApexJobId(),
Class_Name__c = 'ImportJob',
Attempt__c = attempt,
Message__c = message.abbreviate(255),
Will_Retry__c = retry
);
} catch (DmlException logError) {
System.debug(LoggingLevel.ERROR, 'Could not write failure log: '
+ logError.getMessage());
}
if (retry) {
AsyncOptions options = new AsyncOptions();
options.MinimumQueueableDelayInMinutes = RetryPolicy.delayMinutes(attempt);
System.enqueueJob(new ImportJob(recordIds, attempt + 1), options);
}
}
}Start the first attempt with System.enqueueJob(new ImportJob(ids, 1));.
Three details in this finalizer are deliberate:
- The log insert is wrapped in
try/catch. If the insert threw and nothing caught it, the finalizer would end with an exception before reachingSystem.enqueueJob, and the retry would be lost. Logging is secondary, so a logging failure must not stop the retry. - The delay grows with the attempt number. A rolled-back row lock or a struggling endpoint often needs time to recover.
MinimumQueueableDelayInMinutesgives a simple backoff without a scheduler. - The finalizer reads
ctx.getResult()instead of assuming failure. A finalizer also runs after a successful parent, so the first check must return early.
Deciding what to retry
ParentJobResult has only two values, SUCCESS and UNHANDLED_EXCEPTION, so the result alone can't tell a transient failure from a permanent one. If you retry a permanent failure, every attempt fails the same way. You can look at the exception to separate them.
| Failure | Retry? | Reason |
|---|---|---|
| `UNABLE_TO_LOCK_ROW` during DML | Yes | Another transaction held the lock and has probably finished |
| Callout timeout (`System.CalloutException`) | Yes, with a delay | The remote system may recover |
| `System.LimitException` from too much work in one run | Usually no | The next run does the same work and hits the same limit. Split the work first. |
| Validation rule or required field error | No | The data is wrong, and retrying won't fix it |
| `NullPointerException` or other code defect | No | Deploy a fix, then re-run from the log |
A rule that matches on the exception message is brittle, because messages can change. Prefer matching on the exception type when you can:
public static Boolean isTransient(Exception ex) {
if (ex == null) {
return false;
}
return ex instanceof System.CalloutException
|| (ex instanceof DmlException
&& ex.getMessage().contains('UNABLE_TO_LOCK_ROW'));
}If you add this check, change shouldRetry to also take the exception. A failure that isn't transient is then logged with Will_Retry__c = false and not re-enqueued.
Limits and failure modes
- The platform also caps consecutive retries. Salesforce documents a limit on how many times a finalizer can re-enqueue the same job after consecutive failures. Check the current Apex Developer Guide for the exact number. Keep
MAX_ATTEMPTSbelow it, and don't treat the platform cap as your retry policy. - A finalizer can enqueue only one job. A finalizer that tries to enqueue several jobs fails on the second call. Re-enqueue a single job that carries all the IDs.
- A finalizer that fails is not retried. If the finalizer throws, nothing runs after it. This is why the logging code above catches its own errors.
- Chain depth limits still apply. A retry job counts as part of the chain. If the original job was deep in a chain, a retry may hit a depth cap, particularly if you set
MaximumQueueableStackDepththroughAsyncOptions. - A retry can repeat work. The failed run was rolled back, so nothing it did was saved. The retry starts from clean data. This changes if the queueable made callouts before failing. A remote system may have already accepted a request, so retrying can send it twice. Use an idempotency key, or check the remote state, before you resend.
- A retry restarts the whole job. If a chain job processes slices and slice 7 fails, the finalizer should re-enqueue slice 7 and the remaining slices. It should not restart from slice 1.
Testing the retry rule
Because RetryPolicy is a plain class, you can test every branch without running a job:
@IsTest
private class RetryPolicyTest {
@IsTest
static void retriesFailuresUntilTheLimit() {
System.assert(RetryPolicy.shouldRetry(ParentJobResult.UNHANDLED_EXCEPTION, 1));
System.assert(RetryPolicy.shouldRetry(ParentJobResult.UNHANDLED_EXCEPTION, 2));
System.assert(!RetryPolicy.shouldRetry(ParentJobResult.UNHANDLED_EXCEPTION, 3));
}
@IsTest
static void neverRetriesSuccess() {
System.assert(!RetryPolicy.shouldRetry(ParentJobResult.SUCCESS, 1));
}
@IsTest
static void delayIsCappedAtTenMinutes() {
System.assertEquals(2, RetryPolicy.delayMinutes(1));
System.assertEquals(10, RetryPolicy.delayMinutes(20));
}
}Test the finalizer's log-and-enqueue path separately, in an integration test that forces a failure and calls Test.stopTest(). Keep that test small. The decision logic is already covered by the tests above.
Exercise
A queueable fails because a validation rule rejects one record. The finalizer from this chapter retries it twice and logs three failures. What change stops the pointless retries, and what should the log show for the final failure?
Show answer
Add an exception check to the retry rule, such as an isTransient method, so validation errors (a DmlException without a lock error) are not retried. The finalizer should log the first failure with Will_Retry__c = false and not enqueue a new job. The result is one log record instead of three, and it shows the validation message so someone can fix the data.
Exercise
Why does the finalizer wrap its insert of the failure log in a try/catch before it calls System.enqueueJob?
Show answer
If the insert throws an unhandled exception, the finalizer ends before it reaches System.enqueueJob, so the retry is lost. A failed finalizer is not retried. The catch keeps a logging problem from cancelling the retry.