Ask Krrish Contact
Home
Developer & Admin
Apex Triggers Mastery Asynchronous Apex SOQL & SOSL Governor Limits Flows & Process Builder
Advanced Topics
LWC Essentials Security & Sharing Managed Packages Deployment & CI/CD Integration Patterns
Interview Prep
Practice interview questions
Resources
Sales Cloud Class Diagram
Blog AI News
Available Now
Agentforce Pricing Calculator New Debug Log Analyzer SFX Forge New SFX Grove SFX Travel Manager
Salesforce + AI
AI Agent Development Salesforce Agentforce Development Custom RAG Solutions AI + Salesforce Integration Customer Support AI Agents AI Lead Qualification AI Knowledge Base Assistant AI Workflow Automation
Salesforce work
Issue Fix Sprint Automation Sprint LWC & integrations Overflow support for partners Agentforce & AI usage review All services →
About Ask Krrish Contact

Asynchronous Apex: @future, Queueable, Batch and Scheduled Apex Explained

Dive into the world of Asynchronous Apex, a critical skill for any Salesforce developer. This module will teach you how to overcome governor limits, handle long-running operations, and integrate with external systems efficiently.

Need hands-on help?

Which type of asynchronous Apex should I use?

Use Queueable Apex for most background work: it accepts sObjects, returns a job Id and can chain another job. Use Batch Apex for large data sets, processed in chunks of 200 by default with fresh governor limits per chunk. Use Scheduled Apex to run code at set times. For new code, prefer Queueable over @future methods.

  • Asynchronous transactions get higher limits: 200 SOQL queries, 60,000 ms CPU time and a larger heap.
  • A synchronous transaction can enqueue up to 50 Queueable jobs; a Queueable job can enqueue one child.
  • Up to 5 batch jobs can be queued or active at once, with up to 100 more waiting in the flex queue.
  • Scheduled Apex runs with synchronous limits.
  • Track every job in AsyncApexJob or Setup > Apex Jobs.

1. Introduction to Asynchronous Apex

Salesforce operates within a multi-tenant environment, meaning resources are shared among many customers. To ensure fair usage, Salesforce imposes strict governor limits on synchronous Apex transactions.

What is Asynchronous Apex?

Asynchronous Apex executes in the background, at a later time, in a separate thread. This allows the main transaction to complete without waiting. This is crucial for:

  • Separate Limits: Async operations run in separate transactions and can have higher limits, such as SOQL query and CPU limits. Scheduled Apex uses synchronous limits.
  • Long-Running Operations: Complex calculations, large data processing, or extensive callouts.
  • Callouts to External Systems: Callouts originating from triggers must be asynchronous; other contexts can make synchronous callouts.
  • Better User Experience: Prevents users from waiting for long processes to complete.

How do transaction boundaries and capacity affect async work?

Async work runs in a separate transaction, and a submitted Queueable job is not processed if its submitting transaction rolls back. Submission does not guarantee an immediate start. Plan for the shared 24-hour async execution quota across future, Queueable, Batch, and Scheduled Apex: the greater of 250,000 executions or the number of applicable user licenses multiplied by 200. Batch executions consume capacity per execution, so estimate the effect of chunk size and other org workloads. Monitor DailyAsyncApexExecutions, queue depth, and job failures, and allow for delays when designing service expectations.

When to use Asynchronous Apex?

Consider asynchronous Apex when your business logic involves:

  • Making callouts to external web services.
  • Processing a large number of records (e.g., batch updates).
  • Performing complex calculations that require more CPU time.
  • Executing operations that don't need to happen immediately.
  • Chaining multiple operations together.

Salesforce provides several async options:

  • @future Methods
  • Queueable Apex
  • Batch Apex
  • Scheduled Apex

2. @future Methods

@future methods run Apex code in its own thread, at a later time. Particularly useful for making callouts to external web services and offloading long-running operations.

Key Characteristics:

  • Static Method: Must be a static method.
  • @future Annotation: Must be annotated with @future.
  • Void Return Type: Must return void.
  • Parameters: Use primitives or arrays or collections of primitives. Pass record IDs and query sObjects within the method.
  • Callouts: If making a callout, annotate with @future(callout=true).
  • No Chaining: One @future method cannot call another.
  • Submission Limits: A synchronous or Queueable transaction can submit up to 50 future calls; batch and future contexts cannot submit future calls.

Example: Making a Callout

Apex Code Example
public class ExternalServiceCallout {
    public class AccountSyncException extends Exception {}

    @future(callout=true)
    public static void sendAccountToExternalSystem(Set<Id> accountIds) {
        List<Account> accounts = [
            SELECT Id, Name, AnnualRevenue FROM Account WHERE Id IN :accountIds
        ];
        HttpRequest request = new HttpRequest();
        request.setEndpoint('callout:External_Accounts/accounts/bulk');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json');
        request.setBody(JSON.serialize(accounts));
        HttpResponse response = new Http().send(request);
        if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
            throw new AccountSyncException('Account callout failed: HTTP ' + response.getStatusCode());
        }
    }
}

trigger AccountAfterInsert on Account (after insert) {
    Set<Id> accountIds = new Map<Id, Account>(Trigger.new).keySet();
    if (!accountIds.isEmpty()) {
        if (System.isBatch() || System.isFuture() ||
            Limits.getFutureCalls() >= Limits.getLimitFutureCalls()) {
            for (Account account : Trigger.new) {
                account.addError('Account integration could not be queued.');
            }
        } else {
            ExternalServiceCallout.sendAccountToExternalSystem(accountIds);
        }
    }
}

Configure External_Accounts as a Named Credential with an HTTPS endpoint and appropriate authentication. The endpoint must accept a bulk payload and report failure with a non-success HTTP status. If it reports individual failures in a successful response, inspect those results as well. This trigger rejects the affected records when no future call is available, including batch and future contexts. For production, consider a durable outbox and a separate dispatcher so requests can be retained and retried without rejecting the source transaction.

Limitations:

  • Cannot monitor progress directly.
  • No guaranteed execution order for multiple @future calls.
  • Cannot pass sObjects directly, requiring extra SOQL queries.

3. Queueable Apex

Queueable Apex provides a more flexible and robust way to run async Apex. Implements the Queueable interface and allows chaining jobs and passing sObjects.

Key Characteristics:

  • Queueable Interface: Implement System.Queueable, normally written Queueable.
  • execute Method: Must contain a single execute method.
  • sObject Parameters: Can accept sObjects and collections as parameters.
  • Chaining: Each running job can enqueue one child. Developer and Trial orgs have a default depth limit; a configured stack-depth limit can also apply.
  • Job ID: System.enqueueJob returns a job ID for monitoring.
  • Capabilities: Queueable offers job IDs, complex inputs, and chaining; it does not generally have a higher heap limit than future methods.

Example: Chaining Updates

Apex Code Example
public class AccountContactUpdater implements Queueable {
    public class EnqueueException extends Exception {}
    private List<Id> accountIds;

    public AccountContactUpdater(List<Id> accountIds) {
        this.accountIds = accountIds;
    }

    public void execute(QueueableContext context) {
        Set<Id> currentIds = new Set<Id>();
        List<Id> remainingIds = new List<Id>();
        for (Integer i = 0; i < accountIds.size(); i++) {
            if (i < 100) {
                currentIds.add(accountIds[i]);
            } else {
                remainingIds.add(accountIds[i]);
            }
        }
        Map<Id, Account> accounts = new Map<Id, Account>([
            SELECT Id, BillingCity, Description FROM Account WHERE Id IN :currentIds
        ]);
        List<Contact> contactsToUpdate = [
            SELECT Id, AccountId, MailingCity FROM Contact WHERE AccountId IN :currentIds
        ];
        for (Contact contact : contactsToUpdate) {
            contact.MailingCity = accounts.get(contact.AccountId).BillingCity;
        }
        for (Account account : accounts.values()) {
            account.Description = 'Processed by Queueable Apex.';
        }
        List<Account> accountsToUpdate = accounts.values();
        if (!accountsToUpdate.isEmpty()) {
            update accountsToUpdate;
        }
        if (!contactsToUpdate.isEmpty()) {
            update contactsToUpdate;
        }
        if (!remainingIds.isEmpty()) {
            if (Limits.getQueueableJobs() >= Limits.getLimitQueueableJobs()) {
                throw new EnqueueException('Next account chunk could not be queued.');
            }
            System.enqueueJob(new AccountContactUpdater(remainingIds));
        }
    }
}

trigger AccountQueueableTrigger on Account (after insert, after update) {
    List<Id> accountIds = new List<Id>();
    for (Account account : Trigger.new) {
        if (account.AnnualRevenue != null && account.AnnualRevenue > 1000000 &&
            account.Description != 'Processed by Queueable Apex.') {
            accountIds.add(account.Id);
        }
    }
    if (!accountIds.isEmpty()) {
        if (Limits.getQueueableJobs() >= Limits.getLimitQueueableJobs()) {
            for (Account account : Trigger.new) {
                account.addError('Account processing could not be queued.');
            }
        } else {
            System.enqueueJob(new AccountContactUpdater(accountIds));
        }
    }
}

This example processes one account chunk per job and queries its contacts once. The marker prevents this trigger from re-enqueuing its own account updates, but it also prevents later changes from being processed while the marker remains set. Production recursion protection should reflect the actual fields and events to process. Use this pattern only when the contact count is bounded; use Batch Apex for unbounded contact volumes. If the transaction has no enqueue capacity, the trigger rejects the affected records. A durable outbox with a separate dispatcher can retain work for later submission. The two account triggers in this guide are independent examples and need an integrated design before being used together.

Queueable options also include a minimum delay, a duplicate signature, and a maximum stack depth. A transaction finalizer can observe a Queueable job's outcome in a separate transaction and support recovery. Design retries with a bounded policy, backoff, and durable failure records; external operations should be idempotent.

4. Batch Apex

Batch Apex processes large numbers of records in chunks. A batch QueryLocator can retrieve up to 50 million records; SOQL queries used by an iterable remain subject to normal row limits.

Key Characteristics:

  • Database.Batchable Interface: Class must implement Database.Batchable<sObject>.
  • Three Methods:
    • start(): Called once. Returns a Database.QueryLocator or Iterable.
    • execute(): Called per batch chunk (up to 200 records by default). Main processing logic here.
    • finish(): Called once after all batches. Used for notifications or cleanup.
  • Higher Limits: Each execute call runs with its own set of governor limits.
  • Monitoring: Visible in Setup → Apex Jobs.
  • Queue: Up to 5 batch jobs can be queued or active concurrently; the flex queue can hold up to 100 additional jobs. Execution can be delayed by resource availability and fair-use scheduling.

Example: Mass Data Update

Apex Code Example
public class AccountRatingBatch implements Database.Batchable<sObject>, Database.AllowsCallouts {
    public String query;
    public String newRating;

    public AccountRatingBatch(String q, String rating) {
        this.query = q;
        this.newRating = rating;
    }

    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext bc, List<Account> scope) {
        List<Account> accountsToUpdate = new List<Account>();
        for (Account acc : scope) {
            acc.Rating = newRating;
            accountsToUpdate.add(acc);
        }
        if (!accountsToUpdate.isEmpty()) {
            update accountsToUpdate;
        }
    }

    public void finish(Database.BatchableContext bc) {
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
                            FROM AsyncApexJob WHERE Id = :bc.getJobId()];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {'admin@example.com'});
        mail.setSubject('Account Rating Batch Completed');
        mail.setPlainTextBody('Status: ' + job.Status + '. Processed: ' + job.JobItemsProcessed);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

// Execute:
Database.executeBatch(new AccountRatingBatch(
    'SELECT Id, Name, Rating FROM Account WHERE CreatedDate = LAST_N_DAYS:30', 'Hot'), 200);

Each batch chunk is a separate transaction and chunks are not guaranteed to run in order. A failed chunk does not roll back successful chunks. Instance state is not retained between transactions unless the class implements Database.Stateful. If using partial DML, inspect every result and record failures for recovery; otherwise, allow an all-or-none DML failure to surface.

5. Scheduled Apex

Scheduled Apex executes Apex classes at specific times — ideal for daily cleanups, weekly reports, or monthly data syncs.

Key Characteristics:

  • Schedulable Interface: Class must implement Schedulable.
  • execute Method: Takes a SchedulableContext parameter.
  • Cron Expression: E.g., '0 0 1 * * ?' for 1 AM daily.
  • Scheduled Jobs: The same class can have multiple uniquely named jobs. An org normally permits 100 scheduled Apex jobs; Developer Edition permits 5.
  • Combine with Batch: Often used to schedule Batch jobs.

Example: Daily Data Cleanup

Apex Code Example
public class DailyDataCleanupScheduler implements Schedulable {
    public void execute(SchedulableContext sc) {
        List<Task> oldTasks = [SELECT Id FROM Task WHERE CreatedDate < LAST_N_DAYS:365 LIMIT 10000];
        if (!oldTasks.isEmpty()) {
            delete oldTasks;
        }
    }
}

// Schedule it:
System.schedule('Daily Cleanup Job', '0 0 0 * * ?', new DailyDataCleanupScheduler());

6. Choosing the Right Asynchronous Tool

Select the appropriate tool based on your requirements:

  • @future Methods: Existing simple background tasks or callouts. No sObject passing or chaining; Salesforce recommends Queueable for new work.
  • Queueable Apex: Need to pass sObjects, chain jobs, or require more flexibility than @future. Returns a job ID for monitoring.
  • Batch Apex: Processing thousands to millions of records. Separate governor limits per chunk, built-in monitoring.
  • Scheduled Apex: Run a class at a predetermined time or recurring schedule. Often used to kick off a Batch or Queueable job.

General Rule of Thumb:

  1. Consider Flow Builder first for suitable declarative automation.
  2. For fire-and-forget callouts → prefer Queueable Apex.
  3. If you need sObjects or chaining → Queueable Apex.
  4. For large data volumes → Batch Apex.
  5. For recurring tasks → Scheduled Apex (often kicking off Batch or Queueable).

7. Monitoring & Debugging Asynchronous Apex

Monitoring and debugging async jobs is crucial for ensuring background processes run correctly.

Monitoring Asynchronous Jobs:

  • Setup → Apex Jobs: Lists all async jobs with status, submission date, errors.
  • Setup → Scheduled Jobs: Shows all currently scheduled jobs.
  • AsyncApexJob Object: Query programmatically to get job info.
Apex Code Example
List<AsyncApexJob> jobs = [
    SELECT Id, JobType, Status, ApexClass.Name, JobItemsProcessed, TotalJobItems, NumberOfErrors
    FROM AsyncApexJob
    WHERE JobType IN ('BatchApex', 'Queueable', 'Future')
    ORDER BY CreatedDate DESC LIMIT 10];

for (AsyncApexJob job : jobs) {
    System.debug('Job: ' + job.ApexClass.Name + ' | Status: ' + job.Status);
    if (job.NumberOfErrors > 0) {
        System.debug('Errors: ' + job.NumberOfErrors);
    }
}

How do you test asynchronous work and callouts?

Enqueue the work between Test.startTest() and Test.stopTest(), then assert the resulting records or other observable outcomes. Use HttpCalloutMock and Test.setMock to supply controlled HTTP responses instead of making real callouts. Test successful responses, failures, bulk inputs, and submission-limit behavior. Keep batch test data within the scope supported by the test, and test chained jobs individually where needed rather than assuming an entire chain runs in one test. Verify that failures are surfaced or durably recorded.

How do you enforce data access in async jobs?

Choose the execution and data-access context deliberately, and enforce record sharing and object and field permissions appropriate to the operation. Sharing declarations govern record access but do not by themselves enforce object or field permissions. For Apex API version 67.0 and later, database operations default to user mode; specify the intended access mode explicitly when behavior must be clear across versions. Review the permissions of the submitting or running user, the data sent to external systems, and the Named Credential configuration. Test both authorized and restricted access paths.

Debugging Asynchronous Jobs:

  • Debug Logs: Set up logs for the user who initiated the async job. Use appropriate logging levels.
  • System.debug(): Use liberally to track execution flow and variable values.
  • Exception Handling: Surface failures or record actionable details in durable storage. Inspect partial DML results when using partial success.
  • Limits.get*() Methods: Monitor governor limit consumption, especially in Batch execute methods.
Apex Code Example
public class DebuggingBatchExample implements Database.Batchable<sObject> {
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT Id, Name FROM Account');
    }

    public void execute(Database.BatchableContext bc, List<Account> scope) {
        System.debug('Heap: ' + Limits.getHeapSize() + ' / ' + Limits.getLimitHeapSize());
        System.debug('Queries: ' + Limits.getQueries() + ' / ' + Limits.getLimitQueries());
        for (Account acc : scope) {
            if (acc.Name == 'Error Account') {
                throw new MyCustomException('Error Account encountered!');
            }
            acc.Description = 'Processed';
        }
        update scope;
    }

    public void finish(Database.BatchableContext bc) {
        System.debug('Batch Finished.');
    }

    public class MyCustomException extends Exception {}
}

8. Conclusion & Best Practices

Asynchronous Apex can help Salesforce applications handle background work within the limits of separate transactions.

Key Takeaways:

  • Governor Limits: Async transactions have their own limits, which can be higher; Scheduled Apex uses synchronous limits.
  • Callouts: Callouts originating from triggers must be asynchronous. Synchronous callouts are permitted in other contexts.
  • Tool Selection: Match the tool to the use case — @future, Queueable, Batch, or Scheduled.
  • Bulkification: Always avoid SOQL/DML inside loops.
  • Error Handling: Surface failures or record actionable errors, and inspect partial DML results.
  • Monitoring: Regularly check Apex Jobs and query AsyncApexJob.

General Best Practices:

  • Keep it Lean: Focus async methods on their core task. Delegate complex logic to helper classes.
  • Idempotency: Design operations so running them multiple times with the same input produces the same result.
  • Test Thoroughly: Write unit tests covering positive, negative, and bulk scenarios.
  • Consider Platform Events: For complex, decoupled integrations, Platform Events are a powerful async option.
  • Right Tool for the Job: Evaluate requirements carefully before picking an async method.

By mastering these asynchronous patterns, you'll build more powerful and resilient Salesforce applications.

Frequently asked questions

What is the difference between a future method and Queueable Apex?

Future methods only accept primitive parameters, return no job Id and can't be chained. Queueable Apex accepts sObjects and custom types, returns a job Id from System.enqueueJob that you can monitor, and can enqueue a follow-up job. For new code, Queueable is usually the better choice.

What is the maximum batch size in Batch Apex?

The default scope is 200 records. When the start method returns a QueryLocator, you can set the scope up to 2,000 in Database.executeBatch. Each execute call gets its own set of governor limits.

Can you call a future method from Batch Apex?

No. Future methods can't be called from batch or future contexts. Use Queueable Apex from the finish method or chain another batch instead.

How do you make callouts from Batch Apex?

Implement Database.AllowsCallouts on the batch class, then make the callouts inside the execute method. Callout limits apply per execute transaction.

What does Database.Stateful do in Batch Apex?

By default, instance variables in a batch class are reset between execute calls. Implementing Database.Stateful keeps their values across chunks, which is useful for running totals or error lists, at some cost to performance.

What is the difference between synchronous and asynchronous Apex?

Synchronous Apex runs immediately while the user or calling process waits, with limits such as 100 SOQL queries and 10 seconds of CPU time. Asynchronous Apex (Queueable, Batch, Scheduled and @future) runs later in its own transaction with higher limits, such as 200 SOQL queries and 60 seconds of CPU time.

How do you chain Queueable jobs?

Call System.enqueueJob for the next job inside the execute method of the current one. Each Queueable can add only one child job, so the chain runs one job after another.

How many scheduled Apex jobs can an org have?

Up to 100 Apex classes can be scheduled at the same time, or 5 in a Developer Edition org.

Sources: Asynchronous Apex · Queueable Apex · Batch Apex · Execution governors and limits

Get Expert Help

SFX Support — Salesforce + AI solutions. Independent: not affiliated with, endorsed by, or a partner of Salesforce, Inc. Salesforce and Agentforce are trademarks of Salesforce, Inc.