Queueable Apex: chaining, Finalizers, AsyncOptions and cursors
The default async tool: objects as input, job IDs, chaining, transaction Finalizers for failure handling, delays, duplicate signatures and stack-depth control.
Simple explanation
A Queueable class implements Queueable and is started with System.enqueueJob(...), which returns an AsyncApexJob ID.
What makes it the default
- Any serialisable input (lists of sObjects, wrapper classes), set through the constructor.
- Chaining: enqueue the next job from
execute()(one child per job) to build multi-step processes. - Callouts: implement
Database.AllowsCallouts. - Finalizers: attach a
System.FinalizerwithSystem.attachFinalizer(...). It runs after the job finishes even if the job failed with an uncatchable limit exception, so you can log, retry or alert. - Delay:
System.enqueueJob(job, delayInMinutes)with a 0β10 minute minimum delay, useful for back-off. AsyncOptions: set a duplicate signature (so the same logical job isn't queued twice), a maximum stack depth for chains, and a minimum delay.- Apex Cursors: hold a
Database.Cursoras an instance variable and fetch chunks across a chain, as an alternative to Batch Apex for large volumes.
Limits: up to 50 jobs enqueued from a synchronous transaction, 1 from inside a queueable. Developer and trial orgs limit chain depth (historically 5).
Real-world analogy
A Queueable chain is a relay race. Each runner (job) carries the baton (state) for one leg and hands it to the next. A Finalizer is the team coach at the finish line: whatever happened in the leg, even a fall, the coach records it and decides whether to send a substitute runner.
Worked example
A queueable that submits won opportunities to ERP, with a Finalizer that retries with back-off and logs a permanent failure:
public with sharing class ErpOrderSubmissionJob implements Queueable, Database.AllowsCallouts {
private final Set<Id> opportunityIds;
private final Integer attempt;
public ErpOrderSubmissionJob(Set<Id> opportunityIds) { this(opportunityIds, 1); }
public ErpOrderSubmissionJob(Set<Id> opportunityIds, Integer attempt) {
this.opportunityIds = opportunityIds;
this.attempt = attempt;
}
public void execute(QueueableContext ctx) {
System.attachFinalizer(new RetryFinalizer(opportunityIds, attempt));
List<Opportunity> opps = [
SELECT Id, Name, Amount, Account.ERP_Customer_Id__c
FROM Opportunity WHERE Id IN :opportunityIds
];
ErpClient.submitOrders(opps); // callout via Named Credential; throws on failure
}
public class RetryFinalizer implements Finalizer {
private final Set<Id> ids;
private final Integer attempt;
public RetryFinalizer(Set<Id> ids, Integer attempt) { this.ids = ids; this.attempt = attempt; }
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.SUCCESS) {
return;
}
if (attempt < 3) {
// Back off: 1, then 2 minutes.
System.enqueueJob(new ErpOrderSubmissionJob(ids, attempt + 1), attempt);
} else {
IntegrationLog.error('ERP order submission', ids, ctx.getException());
}
}
}
}
Avoiding duplicate jobs for the same record set with AsyncOptions:
AsyncOptions options = new AsyncOptions();
options.DuplicateSignature = QueueableDuplicateSignature.Builder()
.addString('ErpOrderSubmission')
.addId(accountId)
.build();
System.enqueueJob(new ErpOrderSubmissionJob(oppIds), options);
Diagram
Key points
System.enqueueJobreturns a job ID; inputs can be sObjects and wrappers.- Chain one child job per execution; control depth with
AsyncOptions.MaximumQueueableStackDepth. - Finalizers run even after uncatchable failures: log, retry or alert.
- Delay of 0β10 minutes for back-off; duplicate signatures prevent double queuing.
Database.AllowsCalloutsfor callouts; use Named Credentials.- Cursor + chained queueable handles large volumes without batch slots.
Limits and gotchas
- Only one child job can be enqueued from a running queueable; fan-out needs a different design (batch, or a coordinator).
- Chains without a stop condition run forever. Always have an exit condition, and a maximum depth.
- Variables marked
transientare not serialised between enqueue and execution. - In tests, only the first job in a chain runs at
Test.stopTest(); chained jobs are not executed. - Cursors have daily org-wide quotas (instances and rows) and expire; don't create a new cursor in every chain step β verify current quotas.
π€ How to say this in an interview
Show the Finalizer retry pattern: it's the clearest proof you've run async integrations in production. Mention duplicate signatures for idempotency, and when you'd still choose Batch Apex.
Common follow-ups
How do you make a queueable integration idempotent?
Use an external ID or correlation ID so a retried call doesn't create duplicates in the target, check state before acting (already submitted?), and use AsyncOptions duplicate signatures so the same logical job isn't queued twice.
When would you still choose Batch Apex over Queueable + Cursor?
When the team and tooling already standardise on batch, when you need Database.Stateful with a finish step and the familiar Apex Jobs monitoring, or for scheduled maintenance jobs where five-slot concurrency is not a constraint. For high-concurrency or chained processing, cursors are attractive.