Sub topic 10
Attaching a transaction finalizer
This chapter assumes you can write and enqueue a Queueable class. It also assumes you know that each async job runs in its own transaction with its own governor limits. If an unhandled exception ends a transaction, Apex rolls back that transaction's database changes. The queueable you write may fail halfway, and the caller usually isn't around to see it. A transaction finalizer is a small class that Apex runs after your queueable ends, whether it succeeded or failed. This chapter covers how to attach one and what to expect when it runs.
Why a finalizer exists
A try/catch block inside execute handles exceptions you can catch. It cannot handle the ones you can't:
- Governor limit violations, such as too many SOQL queries or CPU time exceeded, are uncatchable.
- If an unhandled exception ends the job, any code after the failure never runs, including a cleanup line placed in a
finallyblock. - Before finalizers, a failed queueable left only an
AsyncApexJobrow with a status ofFailed. Nothing could react to it.
A finalizer runs in a separate transaction after the parent job finishes. Because it is a separate transaction, it gets fresh limits. It also runs when the parent's own transaction hit a limit and was rolled back.
The Finalizer interface
The Finalizer interface has one method:
public interface Finalizer {
void execute(FinalizerContext context);
}Apex passes a FinalizerContext object into execute. It describes how the parent job ended. The next chapter covers its methods in detail. Here you only need to know that it exists and that getResult() returns ParentJobResult.SUCCESS or ParentJobResult.UNHANDLED_EXCEPTION.
Attaching a finalizer to a queueable
Call System.attachFinalizer from inside the queueable's execute method. Pass it an instance of a class that implements Finalizer.
public class ReportJob implements Queueable {
private List<Id> accountIds;
public ReportJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
System.attachFinalizer(new ReportFinalizer(accountIds.size()));
List<Account> accounts = [
SELECT Id, Description FROM Account WHERE Id IN :accountIds
];
for (Account a : accounts) {
a.Description = 'Reported';
}
update accounts;
}
}public class ReportFinalizer implements Finalizer {
private Integer requestedCount;
public ReportFinalizer(Integer requestedCount) {
this.requestedCount = requestedCount;
}
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.SUCCESS) {
System.debug('Job ' + ctx.getAsyncApexJobId()
+ ' finished. Requested records: ' + requestedCount);
} else {
System.debug(LoggingLevel.ERROR, 'Job ' + ctx.getAsyncApexJobId()
+ ' failed: ' + ctx.getException().getMessage());
}
}
}Two details matter here. The finalizer is a separate class, which can be a top-level class or an inner class. The queueable passes data to it through the constructor, the same way you pass state to a queueable.
What happens at run time
The sequence has two transactions. The first is the queueable's. The second is the finalizer's, and it starts only after the first has finished.
Because the transactions are separate, DML from the parent that failed has been rolled back by the time the finalizer runs. DML from a parent that succeeded has been committed. The finalizer sees the database as the parent left it.
When the finalizer runs
The finalizer runs for every way the parent can end after the attach call succeeded.
| How the parent ends | Parent's DML | Finalizer runs? | `getResult()` |
|---|---|---|---|
| `execute` returns normally | Committed | Yes | `SUCCESS` |
| Unhandled exception thrown | Rolled back | Yes | `UNHANDLED_EXCEPTION` |
| Uncatchable governor limit error | Rolled back | Yes | `UNHANDLED_EXCEPTION` |
| Exception thrown before `attachFinalizer` | Rolled back | No | Not applicable |
The last row is the main way to get this wrong.
If the parent catches an exception and finishes normally, the result is SUCCESS. The finalizer reports what the platform saw, which is an unhandled exception or none. It does not report what your code swallowed. If you want the finalizer to know about a handled problem, store it in a member variable and read it from the finalizer, or rethrow.
Rules for attaching
These rules apply to the attach call itself:
- Attach only from a queueable's
executemethod. CallingSystem.attachFinalizerfrom a future method, a Batch Apex class, or anonymous code outside a queueable throws an error. - Attach at most one finalizer per job execution. A second
attachFinalizercall in the sameexecutethrows aSystem.AttachFinalizerException. - Do not reuse the instance in a way that depends on shared static state. The finalizer runs in a new transaction, so static variables reset. Pass what you need through member variables.
- Each execution needs its own attach. If a chained child job should also have a finalizer, the child's
executemust attach one. Finalizers do not carry over to children.
State in the finalizer
Member variables on the finalizer are serialized when you attach it and restored before execute runs. This is the same mechanism as for a queueable, and the same restrictions apply. Use serializable types such as primitives, SObjects, collections, and your own classes whose members are serializable. Mark anything that can't be serialized as transient, and expect it to be null when the finalizer runs.
Copy values into the finalizer as they are at attach time. The finalizer holds its own copy, so later changes to your queueable's variables do not show up in it. If you need the value at the moment of failure, such as the index reached in a loop, a variable in the queueable can't give it to you. Write the progress to a record in a way that survives the rollback. A platform event published with "publish immediately" behavior is one option, and a log record written from the finalizer is another.
What a finalizer can do
The finalizer is ordinary Apex in a transaction of its own. Inside execute you can:
- Run SOQL and DML with a fresh set of synchronous limits.
- Write a log record or send a notification, for example a custom object row recording the job ID and error.
- Enqueue one new queueable job, for example to retry. Only one asynchronous job is allowed from a finalizer.
- Make callouts, if the finalizer class also implements
Database.AllowsCallouts.
public class AlertFinalizer implements Finalizer, Database.AllowsCallouts {
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
// A callout to a monitoring service could go here.
System.debug(LoggingLevel.ERROR, ctx.getException().getMessage());
}
}
}If the finalizer itself throws an unhandled exception, nothing else catches it. Apex does not run a finalizer for a finalizer, and the failure appears only in the debug log. Keep the finalizer short and wrap risky work, such as a logging DML, in try/catch.
Common mistakes
- Attaching late. The attach call sits after a query that fails, so no finalizer runs. Move it to the top of
execute. - Expecting parent changes to be visible after a failure. The parent's DML is rolled back before the finalizer starts. Query the records again if you need current data.
- Expecting
staticstate to carry over. Static variables set in the queueable are gone in the finalizer. - Attaching two finalizers. Combine the logic into one class.
- Using the finalizer for the main work. It is a place to react, not a second job. Heavy processing belongs in a queueable.
Checking what you attached
After a job runs, you can see the result of the parent in AsyncApexJob. The finalizer's own work runs in a separate transaction, so look for its debug log or log records. In a test, Test.stopTest() runs the queueable and then its finalizer synchronously, so assertions after stopTest can see the effects of both. The testing chapter covers this.
Exercise
A queueable's execute method runs a SOQL query on its first line and then calls System.attachFinalizer(new MyFinalizer()) on the second line. The query throws a QueryException because of a bad filter. Does MyFinalizer.execute run, and what should you change?
Show answer
No. The exception happens before attachFinalizer runs, so Apex has no finalizer registered for that execution. Move System.attachFinalizer to the first line of execute, ahead of any code that can fail. After the change, the finalizer runs with a result of UNHANDLED_EXCEPTION.
Exercise
Why can't a queueable pass its loop counter to a finalizer by assigning to a finalizer member variable after the finalizer is attached, and what are two ways to keep progress information that survives a failure?
Show answer
The finalizer holds a serialized copy of its member variables from the moment it is attached, so later changes in the queueable are not seen. Two ways to keep progress are to publish a platform event with "publish immediately" behavior, or to write a log record from a context that is not rolled back. The finalizer can then read it, for example by querying the log record.