Sub topic 12
Bounded retries and failure logging
This chapter assumes you can write a Queueable class and enqueue it with System.enqueueJob. It also assumes you know how to attach a finalizer and read FinalizerContext. Here you combine those pieces into a retry pattern that logs each failure and stops after a fixed number of attempts.
Why retries need a bound
When a queueable throws an unhandled exception or hits a governor limit, the platform rolls back that job's transaction. A try/catch inside execute cannot catch a limit exception. A finalizer runs afterward in its own transaction, so it can still react.
A finalizer that always re-enqueues the job fails in a loop if the cause is permanent, such as bad data. Each retry then uses queue capacity and produces the same error. A bound avoids this: the job carries an attempt counter, and the finalizer re-enqueues only while the counter is below a maximum.
The pattern
The job passes its attempt number to the finalizer. The finalizer reads the result, logs a failure, and decides whether to retry.
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 or hit a limit goes here.
}
}
public class ImportFinalizer implements Finalizer {
private static final Integer MAX_ATTEMPTS = 3;
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;
}
System.debug(LoggingLevel.ERROR, 'Job ' + ctx.getAsyncApexJobId()
+ ' failed: ' + ctx.getException().getMessage());
if (attempt < MAX_ATTEMPTS) {
System.enqueueJob(new ImportJob(recordIds, attempt + 1));
}
}
}Start the first attempt with System.enqueueJob(new ImportJob(ids, 1)). With MAX_ATTEMPTS set to 3, the job runs at most three times.
Logging failures
System.debug is enough for learning, but debug logs are short-lived and need a trace flag. For production, write the failure somewhere durable. Common choices are a custom log object, or a platform event that a trigger turns into a log record. A finalizer has its own DML limits, so an insert there is allowed. Record these fields:
ctx.getAsyncApexJobId()to find the failed job inAsyncApexJob.ctx.getException().getMessage()for the cause.- The attempt number, so you can see how far a record got.
Points to check
- Check
getResult()before callinggetException(). On success the exception isnull. - Attach the finalizer at the start of
execute. If you attach it after code that fails, it never registers. - Only one finalizer can be attached per queueable execution, and a finalizer can enqueue only one new async job. That is why the retry enqueues a single job.
- Retry only failures that can clear on their own, such as row locks or a busy remote service. Do not retry validation errors.
Exercise
A finalizer has MAX_ATTEMPTS = 3 and the first job is enqueued with attempt = 1. The job fails every time. How many times does the job run, and what happens after the last failure?
Show answer
It runs three times. After the third failure, attempt (3) is not less than MAX_ATTEMPTS (3), so the finalizer logs the error and does not enqueue another job.
Exercise
Why is it safe for the finalizer to call ctx.getException().getMessage() only after the SUCCESS check?
Show answer
On a successful parent job, getException() returns null, so calling getMessage() on it would throw a null pointer exception. The early return on SUCCESS prevents that.