Sub topic 6
Transaction Finalizers for cleanup and failure handling
This chapter assumes you can write a Queueable class, know that each async job runs in its own transaction, and can read basic Apex tests. It covers what a finalizer is and when it runs. It also covers what it can and can't do, and how to use it to log failures and retry safely.
The problem finalizers solve
A Queueable job runs in the background, so nobody sees an exception it throws. When execute throws an unhandled exception, three things happen:
- Salesforce rolls back the DML the job performed.
- The job's status becomes
FailedinAsyncApexJob. - Your code gets no chance to react.
A try/catch inside execute covers many errors. It does not cover uncatchable ones, such as exceeding a governor limit. Once a limit exception is thrown, no catch block runs, and the parent job is gone.
A Transaction Finalizer is a class that Salesforce runs after a Queueable job finishes, whether the job succeeded or failed. It runs in its own transaction, so it still executes after the parent's transaction has been rolled back.
The Finalizer interface
A finalizer implements Finalizer, which has a single method, execute(FinalizerContext ctx). The context gives you four things:
| Method | Returns |
|---|---|
| `getAsyncApexJobId()` | The Id of the parent Queueable job |
| `getRequestId()` | An identifier shared by the transaction chain that started the job, useful for correlating log entries |
| `getResult()` | A `ParentJobResult` value: `SUCCESS` or `UNHANDLED_EXCEPTION` |
| `getException()` | The exception that ended the parent job, or `null` when the job succeeded |
Always check getResult() before you call getException(). Calling a method on a null exception causes a second failure inside the code meant to handle the first.
Attaching a finalizer
You attach a finalizer from inside the parent's execute method with System.attachFinalizer:
public class LogFailureFinalizer implements Finalizer {
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
System.debug(LoggingLevel.ERROR, 'Job failed: ' + ctx.getException().getMessage());
}
}
}
public class AccountReviewJob implements Queueable {
private List<Account> accounts;
public AccountReviewJob(List<Account> accounts) {
this.accounts = accounts;
}
public void execute(QueueableContext ctx) {
System.attachFinalizer(new LogFailureFinalizer());
for (Account a : accounts) {
a.Description = 'Reviewed';
}
update accounts;
}
}In a real org, each class goes in its own file. Three rules apply:
- Attach one finalizer per job. A second call to
System.attachFinalizerin the sameexecutethrows an error. - Attach it first. If the job fails before the attach line, no finalizer exists to run. Put the call at the top of
execute. - Finalizers are for Queueable jobs only. Future methods, Batch Apex, and Scheduled Apex have no equivalent. Batch Apex has its own
finishmethod, and you can catch row-level errors withDatabase.update(records, false).
When the finalizer runs
The sequence below shows how a failing job and its finalizer relate.
Two consequences follow from this order.
- The finalizer starts with fresh governor limits. If the parent used up the SOQL limit, the finalizer can still run queries and DML.
- The parent's DML is already rolled back when a failure reaches the finalizer. Anything you write in the finalizer is committed, so it is the right place to record the failure.
System.debug output disappears when the debug log expires. For failures you need to find later, insert a record into a custom logging object or publish a platform event. The finalizer's DML commits even though the parent's did not.
Retrying a failed job
A finalizer can enqueue one new async job. That makes a retry possible. The retry needs a counter. Without one, a job that always fails will re-enqueue itself on every run.
The finalizer stores the Ids and the attempt number. Both are held in member variables, which a finalizer can use like any other class.
public class AccountReviewRetryJob implements Queueable {
private List<Id> accountIds;
private Integer attempt;
public AccountReviewRetryJob(List<Id> accountIds, Integer attempt) {
this.accountIds = accountIds;
this.attempt = attempt;
}
public void execute(QueueableContext ctx) {
System.attachFinalizer(new RetryFinalizer(accountIds, attempt));
List<Account> accts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accts) {
a.Description = 'Reviewed';
}
update accts;
}
}public class RetryFinalizer implements Finalizer {
private static final Integer MAX_ATTEMPTS = 3;
private List<Id> accountIds;
private Integer attempt;
public RetryFinalizer(List<Id> accountIds, Integer attempt) {
this.accountIds = accountIds;
this.attempt = attempt;
}
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.SUCCESS) {
return;
}
System.debug(LoggingLevel.ERROR,
'Job ' + ctx.getAsyncApexJobId() + ' failed on attempt ' + attempt
+ ': ' + ctx.getException().getMessage());
if (attempt < MAX_ATTEMPTS) {
System.enqueueJob(new AccountReviewRetryJob(accountIds, attempt + 1));
} else {
System.debug(LoggingLevel.ERROR, 'Giving up after ' + attempt + ' attempts.');
}
}
}Start the first run with System.enqueueJob(new AccountReviewRetryJob(ids, 1));.
Salesforce also caps how many times in a row a finalizer can re-enqueue the same job. Treat that cap as a backstop. Keep your own counter, as the example does, so your code decides when to stop.
What a finalizer can and cannot do
| Capability | Finalizer behavior |
|---|---|
| Governor limits | A fresh set, separate from the parent |
| DML and SOQL | Allowed, and committed independently of the parent |
| Enqueue async work | One `System.enqueueJob` call per finalizer |
| Attach to other job types | Not possible, Queueable only |
| Count per job | One finalizer per Queueable job |
| Undo the parent's rollback | Not possible. The finalizer must redo the work or enqueue a retry |
A finalizer is also code that can fail. If it throws, the parent's result does not change, and your error handling is lost. Keep finalizers short and put a try/catch around anything that can fail, such as the logging DML.
Passing data to the finalizer
The finalizer can only see what you give it. The context has the job Id and the exception, but not the parent's member variables. Pass what the finalizer needs through its constructor, as RetryFinalizer does with accountIds. Pass Ids rather than full records. The finalizer then re-queries current data, and the serialized job state stays small.
Cleanup uses
Failure handling is the main use, but the finalizer also runs on success. That makes it a place for steps that must happen either way:
- Writing a "job finished" log entry with the job Id and result.
- Releasing a custom lock record that the parent set at the start, so a failed job doesn't leave the lock held.
- Enqueueing the next job in a process only after the current one has fully completed.
The lock example matters. If the parent sets a flag such as Processing__c = true and then fails, only code outside the parent's transaction can clear it, because the parent's own DML was rolled back. Strictly, a rolled-back flag was never saved. The risk is a lock committed in an earlier transaction, for example by the code that enqueued the job.
Testing a finalizer
Finalizers run in tests like other async work. Place the enqueue call between Test.startTest() and Test.stopTest(), and the finalizer runs by the time stopTest returns. To make testing easier, keep the decision logic, such as "should we retry at attempt N", in a plain static method that takes primitives. You can then unit test that method directly without building a FinalizerContext. A later chapter covers async testing in full.
Exercise
A Queueable job inserts 50 records, then throws an unhandled exception. Its finalizer inserts one log record and enqueues a retry. After the finalizer finishes, how many of those records exist from the first run, and why?
Show answer
Only the log record exists. The parent's transaction rolled back, so the 50 inserts are gone. The finalizer runs in a separate transaction, so its log insert commits. The retry is a new job and starts from scratch.
Exercise
A finalizer re-enqueues its parent job whenever the result is UNHANDLED_EXCEPTION, with no counter. The job fails every time because of a validation rule. What goes wrong, and what is the fix?
Show answer
The job and finalizer repeat the failure and re-enqueue each time, using async capacity until a platform cap stops them. The fix is to pass an attempt counter through the job and finalizer, stop at a maximum such as 3, and only retry failures that are likely to be transient.
Exercise
Where in execute should you call System.attachFinalizer, and why?
Show answer
At the top, before the job does any work. If the job fails before the attach call runs, no finalizer is registered, so nothing handles the failure.