Skip to main content
VTFriday

Queueable Apex: Chaining, Finalizers and Apex Cursors

Updated

Source: https://www.vtfriday.com/2026/08/master-salesforce-queueable-apex.html

In plain words: Queueable Apex is a Salesforce interface (System.Queueable) that runs Apex code asynchronously in the background with its own set of governor limits. Unlike @future methods—which only accept primitive data types and cannot be chained—a Queueable class accepts complex objects in its constructor, returns a trackable AsyncApexJob ID when enqueued, can enqueue a follow-up child job when it finishes, and supports attaching a Transaction Finalizer (System.Finalizer) to log errors or retry failed executions even after an uncatchable governor limit exception.

When a Salesforce trigger or Lightning Web Component needs to call an external web service, process heavy calculations, or coordinate a multi-step integration without freezing the user's screen, the work must move out of the synchronous transaction. For years, developers reached for @future methods first. However, as soon as an integration requires step two to wait for step one to finish—or needs to survive an unexpected CPU timeout or heap limit crash without losing data—@future methods fall short. Let's walk through how Queueable Apex and Transaction Finalizers solve sequential background processing, where platform governor limits draw the boundary, and how to write and verify a retry-capable job.

Diagram illustrating Salesforce Queueable Apex job chaining and Transaction Finalizer error recovery

See also: Queueable Apex: Job Chaining and Callouts in Practice

📌 Key Points

  • Stateful Constructors & Job Tracking: A Queueable class can accept sObjects, Lists, Maps, or custom Apex wrapper classes in its constructor, and System.enqueueJob() returns an AsyncApexJob ID immediately.
  • Strict Chaining Limit of 1 Child Job: From inside an asynchronous Queueable.execute() method, you can call System.enqueueJob() at most once to chain a single child job (whereas a synchronous transaction can enqueue up to 50 jobs).
  • Transaction Finalizers (System.Finalizer): Attaching a finalizer via System.attachFinalizer() runs post-processing logic in a separate transaction after the Queueable finishes—even if the parent job terminated due to an uncatchable LimitException.
  • Advanced Enqueue Controls: System.enqueueJob() supports an optional delay (0 to 10 minutes) or an AsyncOptions parameter to enforce deduplication signatures (QueueableDuplicateSignature) and custom maximum stack depths (MaximumQueueableStackDepth).

⚙️ 1. How Queueable Apex and Transaction Finalizers Work

When you implement the System.Queueable interface, you define a standard Apex class with an execute(QueueableContext context) method. Unlike @future methods—which must be static and only accept primitive types or collections of primitives—a Queueable is instantiated with the new keyword. Salesforce serializes the class instance's member variables when you call System.enqueueJob(new MyQueueable(payload)) and deserializes them when an asynchronous worker thread picks up the job from the queue.

  • Enabling HTTP Callouts: By default, asynchronous Apex transactions block outbound HTTP requests unless you explicitly declare Database.AllowsCallouts alongside Queueable on your class declaration.
  • Scheduled Delays & AsyncOptions: You can pass an integer delay between 0 and 10 minutes to System.enqueueJob(job, delayInMinutes), or pass an AsyncOptions instance to set MaximumQueueableStackDepth (limiting how many times a self-chaining job can recurse) and QueueableDuplicateSignature (preventing two identical jobs from sitting in the queue simultaneously).
  • How Transaction Finalizers Catch Uncatchable Failures: In standard Apex, if a job exceeds the 60-second asynchronous CPU limit, the 12 MB asynchronous heap limit, or the 200-SOQL-query limit, Salesforce terminates the transaction immediately. Standard try/catch blocks cannot catch a System.LimitException, and any error log records you tried to insert inside that transaction are rolled back. When you implement System.Finalizer and call System.attachFinalizer(finalizerInstance) at the start of execute(QueueableContext ctx), Salesforce guarantees that the finalizer's execute(FinalizerContext fc) method runs in a brand-new transaction after the parent Queueable finishes or crashes.
Example Scenario: Multi-Step Order Fulfillment Pipeline
Suppose an e-commerce company needs three steps to run strictly in sequence whenever an Order status changes to Shipped:
1. Job 1 (Courier Callout): Calls the shipping carrier's REST API to generate a tracking number.
2. Job 2 (Inventory Sync): Uses that tracking confirmation to deduct stock in an external ERP warehouse.
3. Job 3 (Customer Invoice): Generates and emails the final invoice PDF.

Why firing three @future methods fails: If a trigger fires three independent @future methods, Salesforce places all three in the async queue simultaneously with no execution order guarantee. Job 3 might attempt to email the invoice before Job 1 has even retrieved the tracking number. Furthermore, @future methods return void, cannot enqueue another @future method, and have no Transaction Finalizer hook.

How Queueable Chaining Solves It: The trigger enqueues only Job 1. When Job 1 finishes its courier callout and updates the Order, the last line of Job 1's execute() method calls System.enqueueJob(new InventorySyncJob(orderId)). Each step runs in order with its own fresh governor limits, and an attached Finalizer on each step logs any unhandled failure or re-enqueues the failed step up to a bounded retry count.

⚖️ 2. Choosing Between @future, Queueable, Batch Apex, and Apex Cursors

Salesforce provides multiple asynchronous tools because different background workloads fail in different ways:

  • Choose Queueable Apex when: You need to pass complex state (sObjects or custom wrapper objects), chain sequential multi-step workflows, make callouts with retry/logging guarantees via Transaction Finalizers, or process moderate data chunks recursively.
  • Choose @future when: You are maintaining an existing codebase or need a simple fire-and-forget callout or mixed-DML separation (such as inserting a User and an Account in the same workflow) where you only pass primitive IDs and do not need chaining or finalizers.
  • Choose Database.Batchable (Batch Apex) when: You need to run the same uniform logic across hundreds of thousands or millions of records on a scheduled basis, and you want the platform to automatically divide the query locator into 200-record chunks and provide a single finish() method at the end.
  • Choose Apex Cursors (Database.Cursor) with Queueable when: You need to iterate over large query results (up to 50 million rows) inside chained Queueable jobs with flexible forward/backward pagination via Database.getCursor() and cursor.fetch(position, count). Note: While Apex Cursors were introduced in beta in Summer '24, verify their current General Availability status and exact per-org limits in the official release notes for your org's API version before using them in production.

🛠️ 3. Illustrative Implementation: Self-Healing Queueable with a Transaction Finalizer

Let's examine a complete, runnable Apex class (OrderSyncQueueable.cls) that implements Queueable, Database.AllowsCallouts, and Finalizer on the same class. This pattern passes the current attempt count and target orderId into the constructor, attaches itself as a finalizer before running its main logic, and automatically re-enqueues the job up to 3 times if an unhandled exception occurs.

Prerequisites and Environment Context:

  • This is a complete runnable Apex class targeting API version 61.0+. It uses standard Account records to demonstrate safe re-querying without requiring custom objects.
  • To test actual external HTTP callouts inside execute(QueueableContext ctx), you must configure a Named Credential or Remote Site Setting in Salesforce Setup.
  • Because this code has not been executed in your specific environment, deploy and test it in a Sandbox, Scratch Org, or Developer Edition org before moving to production.
// OrderSyncQueueable.cls
public with sharing class OrderSyncQueueable implements Queueable, Database.AllowsCallouts, Finalizer {

    private Id targetAccountId;
    private Integer attempt;
    private static final Integer MAX_ATTEMPTS = 3;

    public OrderSyncQueueable(Id targetAccountId, Integer attempt) {
        this.targetAccountId = targetAccountId;
        // Default to attempt 1 if null is passed
        this.attempt = (attempt != null) ? attempt : 1;
    }

    // 1. Main Queueable Execution Context
    public void execute(QueueableContext ctx) {
        // Attach this instance as the Transaction Finalizer FIRST,
        // before running callouts, queries, or DML that could hit a limit.
        System.attachFinalizer(this);

        if (this.targetAccountId == null) {
            return;
        }

        // Re-query the record inside execute() rather than relying on a stale
        // sObject passed into the constructor while the job sat in the queue.
        List<Account> accounts = [
            SELECT Id, Name, Description
            FROM Account
            WHERE Id = :this.targetAccountId
            WITH USER_MODE
            LIMIT 1
        ];

        if (accounts.isEmpty()) {
            return;
        }

        Account acc = accounts[0];
        acc.Description = 'Synced via Queueable on attempt #' + this.attempt
            + ' (Job ID: ' + ctx.getJobId() + ')';

        Database.update(acc, AccessLevel.USER_MODE);
    }

    // 2. Transaction Finalizer Execution Context
    // Runs in a separate transaction after execute(QueueableContext) completes or fails.
    public void execute(FinalizerContext fc) {
        Id parentJobId = fc.getAsyncApexJobId();

        if (fc.getResult() == ParentJobResult.SUCCESS) {
            System.debug('Parent Queueable job [' + parentJobId + '] succeeded on attempt ' + this.attempt);
        } else if (fc.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
            Exception ex = fc.getException();
            System.debug(
                LoggingLevel.ERROR,
                'Parent Queueable job [' + parentJobId + '] failed on attempt '
                + this.attempt + ': ' + ex.getMessage()
            );

            // Bounded retry: Re-enqueue with a 1-minute delay if under MAX_ATTEMPTS
            if (this.attempt < MAX_ATTEMPTS) {
                Id retryJobId = System.enqueueJob(
                    new OrderSyncQueueable(this.targetAccountId, this.attempt + 1),
                    1
                );
                System.debug('Scheduled retry attempt ' + (this.attempt + 1) + ' as Job ID: ' + retryJobId);
            } else {
                System.debug(LoggingLevel.ERROR, 'Max retry attempts reached for Account: ' + this.targetAccountId);
            }
        }
    }
}

How to Validate and Test This Class in Your Org

  1. Deploy OrderSyncQueueable.cls to a Sandbox or Developer Edition org.
  2. Open the Developer Console (Debug → Open Execute Anonymous Window) and run the following snippet to create a test Account and enqueue the job:
    Account testAcc = new Account(Name = 'Queueable Verification Co');
    insert testAcc;
    
    Id jobId = System.enqueueJob(new OrderSyncQueueable(testAcc.Id, 1));
    System.debug('Enqueued Job ID: ' + jobId);
  3. In Salesforce Setup, navigate to Environments → Jobs → Apex Jobs (or query SELECT Id, Status, NumberOfErrors FROM AsyncApexJob WHERE Id = :jobId).
  4. Expected Result: You will see the Queueable job complete with status Completed, followed immediately by a Queueable finalizer execution in the debug logs, and the Account's Description field will display the sync message and Job ID.
  5. Writing an Apex Unit Test: When unit testing a Queueable class in an @IsTest method, wrap System.enqueueJob(...) inside Test.startTest() and Test.stopTest(). Calling Test.stopTest() forces Salesforce to execute the asynchronous Queueable job synchronously before running your Assert.areEqual() checks. Note that Salesforce unit tests cannot chain a second child Queueable job inside Test.stopTest()—trying to enqueue a chained job while Test.isRunningTest() is true throws a System.AsyncException: Maximum stack depth has been reached unless guarded with if (!Test.isRunningTest()) or configured with AsyncOptions in supported test contexts.

⚠️ 4. Common Mistakes and Architectural Traps

Common Mistake 1: The Fan-Out Trap (Enqueuing 60 Jobs in One Transaction)
Q2: One transaction needs to enqueue 60 Queueables. What limit do you hit and what is the redesign?
Symptom & Limit Hit: When a synchronous trigger or controller calls System.enqueueJob() inside a loop 60 times, the transaction crashes on the 51st call with System.LimitException: Too many queueable jobs added to the queue: 51. Even worse, if that code runs inside an already-asynchronous context (such as a Batch execute or another Queueable), the limit is just 1 System.enqueueJob() call per transaction!
Correction (Fan-Out via Data, Not Jobs): Never call System.enqueueJob() inside a loop over records. Instead, choose one of three bulkified designs:
  • Pass a Collection to One Queueable: Change your Queueable constructor to accept a List<Id> or Set<Id> of all 60 record IDs. Enqueue one job that processes the first batch of records and, if needed, chains a single follow-up job with the remaining IDs.
  • Staging Work-Queue Object + Single Dispatcher: Insert the 60 work items into a custom staging object (Async_Work_Item__c) and enqueue a single self-chaining Queueable worker that drains the table in chunks.
  • Batch Apex or Platform Events: Use Database.executeBatch() with an appropriate scope size, or publish Platform Events and process them in bulk inside an event trigger.
Common Mistake 2: Mutating an sObject Passed into the Constructor Without Re-Querying
Symptom: You pass an Account sObject from an after update trigger into new MyQueueable(acc) and later call update this.acc; inside execute(). Randomly, changes made by users or flows a few seconds after the trigger fired get overwritten with old field values.
Cause: When you pass an sObject into a Queueable constructor, Salesforce serializes a snapshot of that record as it existed at the moment System.enqueueJob() was called. If the job waits in the queue for 5 seconds while another process updates that record, your serialized sObject holds stale field values.
Correction: Prefer passing a Set<Id> or Id into the constructor (or re-querying the sObject inside execute() using FOR UPDATE when appropriate) so your asynchronous DML operates on fresh database state.
Common Mistake 3: Attaching a Finalizer at the End of execute() or Allowing Unbounded Retries
Symptom: A Queueable job hits a SOQL limit halfway through execute(), and its Transaction Finalizer never runs—or a failing job retries infinitely in the background every few seconds.
Cause: If you place System.attachFinalizer(this) at the bottom of execute() and an exception occurs before that line is reached, no finalizer was ever registered for the transaction. Conversely, if your finalizer blindly calls System.enqueueJob() on UNHANDLED_EXCEPTION without tracking an attempt counter, a permanent data error will loop forever.
Correction: Always make System.attachFinalizer() the very first statement inside execute(QueueableContext ctx), and always guard retries with a strict maximum counter (such as attempt < 3) or AsyncOptions.MaximumQueueableStackDepth.
Core Rule: Enqueue once per asynchronous transaction by passing collections of IDs rather than looping System.enqueueJob(), attach your Transaction Finalizer on the first line of execute(), and always bound your chain depth and retry count.

🧭 5. 360 Decision & Tradeoff Card

360 Summary: Queueable Apex & Transaction Finalizers
  • When to Choose It: Sequential asynchronous workflows ("do step A, then step B"), post-trigger callouts requiring complex state, or background jobs that require guaranteed post-failure logging and bounded retry logic.
  • Primary Benefit: Combines stateful object constructors, trackable AsyncApexJob IDs, sequential chaining, and a platform-level Finalizer safety net that survives uncatchable LimitException crashes.
  • Key Tradeoff: Unlike Batch Apex, Queueable does not automatically chunk a 1-million-row query into 200-record scopes for you; you must manage pagination or work-queue draining yourself.
  • Platform Boundaries & Limits (Apex Governor Limits):
    • Synchronous Enqueue Limit: Up to 50 System.enqueueJob() calls per synchronous transaction.
    • Asynchronous Chaining Limit: Maximum 1 System.enqueueJob() call inside an executing Queueable.execute() method (note: a Transaction Finalizer's execute(FinalizerContext) runs in its own transaction and can enqueue 1 retry/follow-up job even if the parent failed).
    • Chain Depth Limits: In Production and Sandbox orgs, chain depth is unrestricted by default (though Salesforce throttles execution speed as depth increases), and can be capped explicitly via AsyncOptions.MaximumQueueableStackDepth. In Developer Edition and Trial orgs, maximum chain depth is strictly capped at 5 jobs (1 initial job + 4 chained children).

❓ 6. Core Q&A and Scenario Follow-Ups

Q: When does Queueable beat Batch Apex, and how do Finalizers change your retry architecture?
Interview Quick Answer:
"Queueable beats Batch Apex for event-driven workflows, sequential step-by-step chaining, and passing complex non-primitive parameters without waiting for Batch's start() locator overhead. Transaction Finalizers upgrade retry architecture because execute(FinalizerContext) runs in a separate transaction even after an uncatchable LimitException—letting you inspect fc.getResult(), commit an error log that won't roll back, and safely re-enqueue the job with an incremented retry counter."

Detailed Explanation: Batch Apex is designed to run the same logic across a massive SOQL QueryLocator (up to 50 million records), which introduces scheduling overhead between start(), execute(), and finish(). When you only need to process a single order payload, make a REST callout after a record saves, or run three distinct business steps in sequence, Queueable starts faster and lets you pass rich custom state directly between steps. Furthermore, before Transaction Finalizers existed, if a Queueable hit a CPU or heap limit, the job died silently in AsyncApexJob with status Failed and rolled back any custom log records. Attaching a Finalizer ensures your recovery code runs regardless of how the parent job exited.

Q1: What are the chaining depth rules, and how do you process an unbounded queue with them?

A1: In Production and Sandbox orgs, there is no fixed hard limit on how many sequential child jobs a Queueable chain can reach (one child enqueued per execute()), whereas Developer Edition and Trial orgs enforce a strict ceiling of 5 jobs in a chain (4 chained links after the initial job). You can also enforce a custom ceiling in any org using AsyncOptions.MaximumQueueableStackDepth.

How to process an unbounded work queue safely: Store pending work items as rows in a custom staging object (for example, Integration_Queue__c with Status__c = 'Pending'). Each Queueable execution queries one bounded batch of pending records, processes them, updates their status to 'Completed' or 'Failed', and checks if any 'Pending' rows remain. If—and only if—more rows exist, it enqueues a fresh instance of itself. Because a chain in Developer Edition stops at depth 5 (or could halt in Production if an unexpected org maintenance window occurs), pair this self-draining chain with a lightweight scheduled Apex "sweeper" job that checks periodically for stranded 'Pending' records and kicks off a new chain when none is currently running.

Q: (Compare) Queueable chaining vs. Batch Apex — both process big work in pieces; how do you choose?

A: Match the tool to the shape of the problem:

  • Volume Problem → Choose Batch Apex: When the requirement is "query 2 million Contact records every night, recalculate a score using the exact same logic, and send one summary email at the end," Batch Apex handles the Database.QueryLocator chunking natively and gives you a built-in finish() method.
  • Workflow / Sequence Problem → Choose Queueable Chaining: When the requirement is "Step 1: call an external tax API; Step 2: generate an invoice PDF from the response; Step 3: email the customer," each step does completely different work and depends on the output of the prior step. Chaining dedicated Queueable classes keeps each step modular and fast.

Q: What are Apex Cursors, and when do they beat Batch Apex?

A: Introduced in beta in Summer '24 (and expanded toward General Availability in subsequent releases—check your org's current release notes for exact GA status and governor limits), Apex Cursors (Database.Cursor) let you work with large SOQL result sets (up to 50 million rows) inside Queueable chains without loading all rows into memory at once:

  • Calling Database.Cursor locator = Database.getCursor('SELECT Id FROM Account...'); creates a stateless cursor reference to the query result.
  • Inside a Queueable job, you call locator.fetch(startPosition, count) to retrieve a specific slice of records, process them, and then chain the next Queueable job by passing the same cursor and the updated startPosition + count offset.
  • Unlike a Batch QueryLocator—which only moves forward in fixed-size chunks—an Apex Cursor allows you to adjust chunk sizes dynamically or navigate backward and forward by index position, and provides System.TransientCursorException handling so you can retry a single failed slice inside a Transaction Finalizer without restarting the entire 10-million-row job.
When Batch Apex still wins: If you simply need a standard nightly job that processes uniform chunks and runs a finish() summary without writing custom cursor offset tracking and chaining logic, standard Batch Apex requires less boilerplate code.

Q: Two quick "are you current" Apex checks interviewers use?

A:

  1. The Null Coalescing Operator (??): Generally Available since Spring '24 (API version 60.0), the leftExpr ?? rightExpr operator returns leftExpr if it is not null, and evaluates and returns rightExpr only when leftExpr is null. For example, in our constructor above, this.attempt = attempt ?? 1; cleanly replaces verbose ternary checks like (attempt != null) ? attempt : 1.
  2. Retirement of Salesforce Functions: Salesforce officially retired Salesforce Functions (reaching end of sale in 2023 and retirement in early 2025). If an interviewer asks where elastic, high-compute workloads that exceed Apex CPU or heap limits should run today, the current answer is offloading compute to Heroku or an external cloud microservice (AWS, Azure, GCP) invoked asynchronously from a Queueable callout or Platform Event—not Salesforce Functions.

Self-Check Question:
A developer writes a Queueable class that makes an HTTP callout to an external payment gateway inside execute(QueueableContext ctx). The class compiles without error, but when the job runs in the background, it immediately fails with System.CalloutException: Callout fromQueueable not supported (or callouts not allowed). What did the developer forget to add to the class declaration?

Answer: The developer implemented Queueable alone instead of adding the marker interface Database.AllowsCallouts (for example, public class PaymentJob implements Queueable, Database.AllowsCallouts). Without Database.AllowsCallouts, Salesforce blocks outbound HTTP requests inside Queueable.execute().
🔗 Follow-Up Question: How do you prevent two triggers or users from accidentally enqueuing the exact same Queueable job twice at the same time?

Answer: Use the AsyncOptions class with a QueueableDuplicateSignature when calling System.enqueueJob(job, asyncOptions). You instantiate AsyncOptions options = new AsyncOptions(); and assign options.DuplicateSignature = QueueableDuplicateSignature.Builder().addId(accountId).addString('OrderSync').build();. If another Queueable job with that identical signature is already waiting in the queue or currently executing, Salesforce suppresses the duplicate enqueue call and throws a catchable System.DuplicateMessageException (or returns without adding a redundant job, depending on how you handle the exception), preventing race conditions and wasted async executions.

Was this article helpful?

Have a question or spotted a mistake? Ask here about this article

Found this guide useful? Buy me a coffee (opens in a new tab)

Comments

Questions, corrections and your own experience are all welcome.