Sub topic 13
Rules and limits for finalizers
This chapter lists the rules a transaction finalizer must follow and the limits it runs under. It assumes you can write a Queueable class, attach a finalizer, and read a FinalizerContext. It also assumes you know the basic Apex governor limits and the difference between a synchronous and an asynchronous transaction.
A finalizer is a small safety net, and it behaves differently from the job it protects. Most finalizer bugs come from treating it like a second execute method with the same permissions. It isn't one.
Where a finalizer fits
A finalizer runs after its parent queueable ends, whether the parent succeeded or failed. It runs in its own transaction, so a failure in the parent does not roll back anything the finalizer does.
The rules
| Rule | What it means in practice |
|---|---|
| Queueable only | You attach a finalizer from the `execute` method of a class that implements `Queueable`. Future methods and Batch Apex don't use this mechanism. |
| One finalizer per job | Calling `System.attachFinalizer` a second time in the same `execute` throws an exception. |
| Attach before the risky work | The call must run before the code that might fail. If the parent throws first, no finalizer is registered. |
| Own transaction | The finalizer has fresh governor limits and commits independently of the parent. |
| One enqueue | The finalizer's `execute` can enqueue one asynchronous job with `System.enqueueJob`. |
| Runs on success and failure | `ctx.getResult()` returns `ParentJobResult.SUCCESS` or `ParentJobResult.UNHANDLED_EXCEPTION`. |
| State comes from the constructor | The finalizer is a separate object. It can't read the parent's local variables. |
Attach exactly once
The parent's execute can contain branches, helper methods, and loops. Attach the finalizer at the top, in one place, so that no path can attach it twice or skip it.
public class GuardedJob implements Queueable {
private List<Id> recordIds;
public GuardedJob(List<Id> recordIds) {
this.recordIds = recordIds;
}
public void execute(QueueableContext context) {
// Attach first, so the finalizer exists even if the work below throws.
System.attachFinalizer(new GuardedFinalizer(recordIds));
try {
// A second attach in the same execute is a programming error.
System.attachFinalizer(new GuardedFinalizer(recordIds));
} catch (Exception e) {
System.debug(LoggingLevel.WARN, 'Second attach rejected: ' + e.getMessage());
}
// Real work goes here.
}
}
public class GuardedFinalizer implements Finalizer {
private List<Id> recordIds;
public GuardedFinalizer(List<Id> recordIds) {
this.recordIds = recordIds;
}
public void execute(FinalizerContext ctx) {
System.debug('Finalizer ran for job ' + ctx.getAsyncApexJobId());
}
}The try block is there only to show the rule. In real code you would not attach twice. If you need several follow-up actions, put them all inside one finalizer's execute method.
State is fixed when you attach
The finalizer receives data through its constructor. Treat that data as a snapshot taken at attach time. If the parent keeps changing a collection after it attaches the finalizer, don't count on the finalizer seeing the change.
Two practical consequences follow:
- Pass identifiers and counters, not large record lists. A finalizer that re-queries by ID gets current data.
- A finalizer can't know how far the parent got. If you need that, store progress somewhere the parent commits, such as a record the parent updates, and have the finalizer read it. Remember that an unhandled exception rolls back the parent's DML, so that progress record is also rolled back on failure. For failure handling, design the retry to be safe to repeat from the start of the slice.
The finalizer has its own limits
Because the finalizer is a new transaction, it gets a fresh set of asynchronous governor limits. The parent having used 90 percent of its CPU time doesn't matter to the finalizer.
This is also what makes a finalizer useful for logging. If the parent fails, its inserts are rolled back, but a log record inserted by the finalizer is committed.
public class LoggingFinalizer implements Finalizer {
private Id parentRecordId;
private Integer attempt;
private static final Integer MAX_ATTEMPTS = 3;
public LoggingFinalizer(Id parentRecordId, Integer attempt) {
this.parentRecordId = parentRecordId;
this.attempt = attempt;
}
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.SUCCESS) {
return;
}
// getException() is null when the parent succeeded, so read it only here.
Exception ex = ctx.getException();
String message = ex == null ? 'Unknown error' : ex.getMessage();
System.debug(LoggingLevel.ERROR, 'Job ' + ctx.getAsyncApexJobId()
+ ' failed for ' + parentRecordId + ': ' + message);
// Only one System.enqueueJob call is allowed here.
if (attempt < MAX_ATTEMPTS) {
System.enqueueJob(new RetryableJob(parentRecordId, attempt + 1));
}
}
}
public class RetryableJob implements Queueable {
private Id parentRecordId;
private Integer attempt;
public RetryableJob(Id parentRecordId, Integer attempt) {
this.parentRecordId = parentRecordId;
this.attempt = attempt;
}
public void execute(QueueableContext context) {
System.attachFinalizer(new LoggingFinalizer(parentRecordId, attempt));
// Work that may fail goes here.
}
}One enqueue, and what that implies
The finalizer can call System.enqueueJob once. That is enough for a retry, but it affects how you design the job.
- Branch with
if, not with a loop. Two enqueue calls in one finalizer break the limit, so write the code so that only one runs. - A retry is a new link in a chain. Chain-depth rules still apply to it, including a
MaximumQueueableStackDepthset throughAsyncOptions. A depth cap that is too low can stop a retry you expected to run. - The finalizer's enqueue allowance is separate from the parent's. A parent that chains to a child and a finalizer that also enqueues a job can both run, which gives you two jobs where you meant one. Decide which of the two owns the next step, and make the other stay quiet. A common choice is that the parent chains on success and the finalizer enqueues only when the result is
UNHANDLED_EXCEPTION. - Always bound the retries. The
attemptcounter in the example is the only thing that stops an infinite failure loop, and the counter has to travel through the constructors of both classes.
What a finalizer can't promise
Plan for these edge cases:
- The finalizer can fail too. An unhandled exception inside
executeis a failure in a transaction with no further finalizer behind it. Keep the code short and wrap risky steps, such as the DML that writes a log record, intry/catch. - Don't rely on it as the only record.
AsyncApexJobshows the job's status and any error message. Query it by the ID fromctx.getAsyncApexJobId()when you need a second source. - Not every failure is the same. The result tells you only whether the parent hit an unhandled exception. A failed callout the parent caught and handled counts as
SUCCESS. If you want the finalizer to react, rethrow the exception or record the outcome somewhere the finalizer can read. - Permanent failures need a different response. Retrying a limit exception on the same input will probably fail again. Reduce the slice size on retry, or log and stop.
Checklist
- Attach the finalizer once, at the start of
execute. - Pass identifiers and counters through its constructor.
- Check
ctx.getResult()first and return early on success. - Read
ctx.getException()only after you know the parent failed. - Make at most one
System.enqueueJobcall, and put an attempt cap on it. - Guard anything in the finalizer that could throw.
Exercise
A queueable attaches a finalizer, then calls System.attachFinalizer a second time in a helper method with a different finalizer. A separate finalizer, on failure, calls System.enqueueJob once for a retry and once more for an alert job. Name the two rule violations, and say how you would restructure the code.
Show answer
The first violation is attaching two finalizers to one job, since only one is allowed per queueable. The second is two System.enqueueJob calls in one finalizer, since only one is allowed. Restructure by attaching a single finalizer at the top of execute, and move any extra follow-up work into that finalizer's execute. Enqueue only the retry job, and send the alert by another route, such as inserting a log record or platform event inside the finalizer's own transaction.
Exercise
A parent job inserts 200 records and then throws an unhandled exception. Its finalizer inserts one log record. Which of these records exist afterward, and why?
Show answer
Only the log record exists. The parent's transaction rolled back on the unhandled exception, so its 200 inserts are gone. The finalizer runs in its own transaction, so its insert commits independently.