Asynchronous Apex in Salesforce

Asynchronous Apex in Salesforce.png
Chinmaya By Chinmaya
7 Min Read

Introduction

Salesforce’s Apex programming language is known for its robust capabilities in managing business logic.

However, some operations—like processing large datasets or making external API calls—can be time-consuming and might exceed governor limits if they are executed synchronously.

This is where Asynchronous Apex comes into play. It allows developers to run longer or resource-intensive processes without blocking the execution of other tasks.

In this blog post, we’ll cover the basics of Asynchronous Apex, its different types, and best practices to leverage it effectively.

What is Asynchronous Apex?

Asynchronous Apex allows you to perform operations that don’t need to be completed immediately and can run in the background which can be completed at a later point of time.

In simple words, we can say that – Asynchronous apex are those processes that do not run immediately and operate independently of other processes.

Now, before moving further, lets discuss what are differences between Synchronous apex and Asynchronous apex?

Difference between Synchronous and Asynchronous Apex

Synchronous Apex

    1. Executes immediately.
    2. Operates within strict governor limits (e.g., 100 SOQL queries, 150 DML statements).
    3. May time out if the process takes too long.

Asynchronous Apex:

    1. Executes in the background.
    2. Has higher limits (e.g., 200 SOQL queries in Batch Apex).
    3. Ideal for long-running, resource-intensive tasks.

Where Asynchronous Apex is useful?

Asynchronous apex is useful for the tasks that may exceed synchronous execution limits or that take time to complete, such as:

    1. Long-running operations (like complex calculations or data processing)
    2. Integrating with external systems (making callouts to external web system)
    3. Processing large volumes of records (batch operations)
    4. Avoiding governor limits in real-time operations.

Real time use case of Asynchronous Apex

While giving any Salesforce interview, you will always face real time scenario questions.

So, if interviewer asks you – Where have you used Asynchronous apex in your project? 

You can answer – I have used asynchronous apex while:

    1. To do Callout from Trigger
    2. To fix Mixed DML Exception
    3. To fix Apex CPU Time Limit Exception
    4. To process (insert/update/delete) large set of records in Salesforce
    5. To run a transaction at a specific time.

Types of Asynchronous Apex

There are different types of asynchronous apex provided by Salesforce to meet various use-cases as per the requirement.

    1. Future Method
    2. Batch Apex
    3. Queueable Apex
    4. Scheduled Apex
    5. Change Data Capture (Apex Triggers)
    6. Platform Events (Events Based)
    7. Continuation (UI)

1. Using Future Methods

Future Methods are the simplest way to run Apex asynchronously.

They allow you to run processes in the background and are especially useful for making external web service callouts.

Example Code:

				
					public class ExampleFuture {
    @future(callout=true)
    public static void makeCallout() {
        // Code to make an HTTP callout
        HttpRequest req = new HttpRequest();
        req.setEndpoint ('https://api.example.com /data');
        req.setMethod('GET');
        HttpResponse res = new Http().send(req);
        System.debug (res.getBody());
    }
}
				
			

Key Features

    1. Run processes in the background.
    2. Can make callouts to external web services.
    3. Use for short-running tasks (up to 200 method calls per Apex invocation).

Check out the post below to learn more about Future Methods in Salesforce!

2. Batch Apex:

Batch Apex is used to process large volumes of records efficiently by dividing them into smaller batches that are processed separately.

It is ideal for bulk data operations that would otherwise hit the governor limits if they are executed in synchronous transactions.

Syntax of Batch Apex:

				
					global class ExampleBatch implements Database.Batchable <SObject> {
    global Database.QueryLocator start (Database.BatchableContext bc) {
        return Database.getQueryLocator ('SELECT Id FROM Account');
    }
    
    global void execute (Database.BatchableContext bc, List<Account> scope) {
        for (Account acc : scope) {
            acc.Status__c = 'Processed';
        }
        update scope;
    }
    
    global void finish (Database.BatchableContext bc) {
        System.debug('Batch job completed.');
    }
}
				
			

To execute the batch apex, use the following code:

				
					ExampleBatch batch = new ExampleBatch();
Database.executeBatch (batch, 200);  // 200 records per batch
				
			

Key Features

  1. Can process up to 50 million records.
  2. Supports bulk DML operations in smaller chunks.
  3. You can monitor the status of a batch job.

Check out the post below to learn more about Batch Apex in Salesforce!

3. Queueable Apex

Queueable Apex allows you to submit jobs that can be processed asynchronously, with more flexibility than future methods.

It also supports chaining, meaning that you can queue subsequent jobs after one job finishes.

Example Code:

				
					public class ExampleQueueable implements Queueable {
    public void execute(QueueableContext context) {
        // Business logic here
        List<Account> accounts = [SELECT Id, Name FROM Account];
        for (Account acc : accounts) {
            acc.Status__c = 'Updated via Queueable';
        }
        update accounts;
    }
}
				
			

To queue the job:

				
					ExampleQueueable job = new ExampleQueueable();
System.enqueueJob(job);
				
			

Key Features

  1. More flexible than future methods.
  2. Supports complex logic and chaining multiple jobs.
  3. Can hold object types and state across job executions.

Check out the post below to learn more about Queueable Apex in Salesforce!

4. Scheduled Apex

Scheduled Apex allows you to schedule Apex classes to run at specific times, either once or on a recurring basis (e.g., daily, weekly, or monthly).

Scheduled Apex is perfect for automating repetitive tasks.

				
					global class ExampleScheduled implements Schedulable {
    global void execute(SchedulableContext sc) {
        // Code to run periodically
        List<Account> accounts = [SELECT Id FROM Account WHERE Status__c = 'New'];
        for (Account acc : accounts) {
            acc.Status__c = 'Reviewed';
        }
        update accounts;
    }
}
				
			

To schedule the above job:

				
					String cron = '0 0 12 * * ?';  // Every day at noon
ExampleScheduled job = new ExampleScheduled();
System.schedule('Daily Account Review Job', cron, job);
				
			

Check out the post below to learn more about Scheduled Apex in Salesforce!

Conclusion

In conclusion, Asynchronous Apex is a powerful feature in Salesforce that allows developers to handle long-running and resource-intensive processes efficiently.

By leveraging tools like Future Methods, Batch Apex, Queueable Apex, and Scheduled Apex, you can bypass synchronous Governor limits, ensure scalability, and optimize performance for complex operations.

Implementing Asynchronous Apex not only helps avoid governor limits but also improves user experience by running tasks in the background without interrupting real-time processes.

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
3 Comments