Sub topic 10
Attaching a transaction finalizer
This chapter assumes you can write a Queueable class, enqueue it with System.enqueueJob, and read basic governor limit rules. You should also know how to run Apex tests. Here you will learn what a finalizer is and how to attach one. Reading its result and building retries come in later chapters.
What a finalizer does
A queueable job can fail with an unhandled exception or hit a governor limit. A try/catch block cannot catch a limit exception, so your code gets no chance to react. A transaction finalizer fills that gap. It is a separate piece of code that Salesforce runs after the queueable's transaction ends, whether the job succeeded or failed.
A finalizer is a class that implements the Finalizer interface. The interface has one method, execute(FinalizerContext ctx). Salesforce calls it after the parent job finishes. The finalizer runs in its own transaction, so it gets fresh limits.
Attaching a finalizer
You attach a finalizer from inside the queueable's execute method. Call System.attachFinalizer with an instance of your finalizer class.
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.
}
}The attach call comes first in execute. If the job throws before the finalizer is attached, no finalizer exists to run. Attaching first means every later failure in the method is covered.
Writing the finalizer class
The finalizer receives its data through its constructor, the same way a queueable does. This example is the finalizer that ImportJob attaches.
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));
}
}
}For now, focus on the structure. The class implements Finalizer, stores state in member variables, and does its work in execute. The ctx argument describes how the parent job ended. The next chapter covers it in detail.
Common mistakes
- Attaching late. Put
System.attachFinalizerat the top ofexecute, before any work that can fail. - Expecting a rollback. The parent job's database changes are already rolled back if it failed. The finalizer runs in a new transaction and cannot undo or repeat that rollback.
- Treating it as a catch block. A finalizer runs after the transaction ends. It cannot fix the failed work in place. It can only log, notify, or enqueue new work.
- Assuming it only runs on failure. It also runs after success, so check the result first, as the example does.
Exercise
Why should System.attachFinalizer be the first statement in a queueable's execute method?
Show answer
The finalizer only exists if the attach call runs. If the job throws an exception or hits a limit before that line, no finalizer is attached and nothing runs afterward. Attaching first covers every failure that happens later in the method.
Exercise
A finalizer runs in its own transaction. Name one practical benefit and one limitation.
Show answer
Benefit: it gets fresh governor limits, so it can log or enqueue a retry even when the parent hit a limit. Limitation: it cannot undo or fix the parent's work. The parent's changes have already rolled back, and the finalizer can only react, for example by logging or enqueuing new work.