DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Leveraging Infrastructure as Code for Data Engineering Projects: A Comprehensive Guide
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  • Integrating Apache Doris and Hudi for Data Querying and Migration
  • Problem Analysis in Apache Doris StreamLoad Scenarios

Trending

  • Top Book Picks for Site Reliability Engineers
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Docker Base Images Demystified: A Practical Guide
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  1. DZone
  2. Software Design and Architecture
  3. Performance
  4. An Overview of Asynchronous Processing in Salesforce

An Overview of Asynchronous Processing in Salesforce

Asynchronous processing in Salesforce lets you run long tasks outside the main transaction, improving performance and avoiding governor limits.

By 
Jaseem Pookandy user avatar
Jaseem Pookandy
DZone Core CORE ·
Mar. 10, 25 · Analysis
Likes (0)
Comment
Save
Tweet
Share
3.1K Views

Join the DZone community and get the full member experience.

Join For Free

When running a process in Salesforce, the first question you should ask is whether to execute it synchronously or asynchronously. If the task can be delayed and doesn't require an immediate result, it's always beneficial to leverage Salesforce's asynchronous processes, as they offer significant advantages to your technical architecture.

What Is Asynchronous Processing?

Asynchronous processes run in their own thread, allowing the task to complete without keeping the user waiting. Here are the key benefits:

1. Improved User Experience and Performance

Since asynchronous processes run in the background, users don’t have to wait for them to finish. This enables users to continue their work uninterrupted while also improving page load times and overall system performance.

2. Higher Limits

Salesforce imposes strict limits on synchronous transactions, such as the number of queries or DML operations per transaction. Asynchronous processing provides additional execution limits, giving you more room to scale your operations.

3. Scalability

By offloading complex or resource-intensive tasks to run in the background, asynchronous processing helps your business scale efficiently without compromising system performance.

Here are the various tools Salesforce provides for asynchronous processing.

Various tools Salesforce provides for asynchronous processing

Key Considerations

So far, we've explored asynchronous processing, its benefits, and the various tools Salesforce provides for these tasks. However, there are several important factors to consider before choosing asynchronous processing for your business needs.

1. Asynchronous Processing Has No SLA

Keep in mind that asynchronous processes have no guaranteed Service Level Agreement (SLA). They run in their own thread whenever resources are available, meaning there’s no assurance the task will complete within a specific time frame. As such, it's important to avoid using asynchronous processing for business flows that are time-sensitive.

2. Choose the Right Tool for the Job

As mentioned earlier, Salesforce offers various tools for asynchronous processing, each designed for different use cases. Understanding the strengths and limitations of each tool will help you select the most suitable one for your specific needs.

3. Bulkify Your Code

While Salesforce provides higher execution limits for asynchronous processes, it's still critical to bulkify your operations. This ensures your code can efficiently handle multiple records, staying within the platform's limits and maintaining performance.

4. Implement Error Handling and Monitoring

Since asynchronous jobs run in the background, robust error handling and monitoring are essential. Use try-catch blocks and log errors to custom objects for easier tracking. Additionally, implement retry logic to manage intermittent failures, such as API callout issues, to ensure the reliability of your processes.

Asynchronous Tools Deep Dive

Let's take a closer look at each of the asynchronous tools in Salesforce.

Future Methods

Future methods are used for operations that can run independently in their own thread. One common use case is executing external web service callouts where the user doesn't need to wait for the operation to complete.

To define a future method, simply annotate the method with the @future annotation.

Java
 
public class FutureClass {
@future
 public static void myFutureMethod(list<id> recordIds){
   //long-running operation code
 }  
}


Key points about future methods:

  • Static. Future methods must be static.
  • Void return type. They can only return void.
  • Primitive data types. Future methods can only accept primitive data types (e.g., String, Integer, Id). They cannot take complex objects as parameters.
  • Callouts. If the future method needs to make a web service callout, you must include the callout=true attribute in the annotation to allow the method to perform the callout.
Java
 
public class FutureClass {
@future(callout = true)
 public static void myFutureMethod(){
   //callout here
 }  
}


Queueable Apex

Similar to future methods, Queueable Apex allows you to run operations in their own thread, making it ideal for long-running tasks. It leverages the Apex job queue and provides a more flexible and powerful approach to asynchronous processing compared to future methods.

To implement Queueable Apex, your class must implement the Queueable interface. The class should always define an execute method, which contains the logic for the asynchronous operation.

Java
 
public class QueueableClass implements Queueable{
public void execute(QueueableContext context){
  //long-running operation
}
}


You can execute Queueable Apex by calling System.enqueueJob(), which adds the job to the queue and returns a job ID. This job ID can be used to monitor the job's status by querying the AsyncApexJob object.

Java
 
ID jobID = System.enqueueJob(new QueueableClass());


Key points about Queueable Apex:

  • Non-primitive data types. Unlike future methods, you can use non-primitive data types as member variables in a Queueable class.
  • Job chaining. Queueable jobs can be chained, allowing you to start a second job from an already executing one, creating a sequence of asynchronous operations.

Batch Apex

When you need to run asynchronous operations on a large number of records, Batch Apex is the ideal solution. It divides your large dataset into smaller, manageable chunks for processing.

To implement Batch Apex, your class must implement the Database.Batchable interface. The Batch Apex class should define three methods: start, execute, and finish.

1. Start Method

This method is executed at the beginning of the batch job. It should contain the SOQL query to collect the large dataset and return a QueryLocator. The governor limit on the total number of records retrieved by a SOQL query is bypassed in the start method when using Batch Apex.

Java
 
public Database.QueryLocator start(Database.BatchableContext bc) {}


2. Execute Method

The execute method is called for each batch of records. Note that the order in which records are processed is not guaranteed.

Java
 
public void execute(Database.BatchableContext bc, list<Object>){}


3. Finish Method

The finish method is called after all batches of records have been processed. It’s typically used for post-processing tasks, such as sending notification emails. Each execution of the batch job is considered a single transaction, and governor limits are reset for each batch.

To trigger a batch job, use the Database.executeBatch method. This adds the batch job to the asynchronous queue.

The Database.executeBatch method takes two parameters:

  1. An instance of the Batch Apex class.
  2. An optional batch size parameter, which specifies the number of records per batch. The maximum batch size you can specify is 2000.
Java
 
ID batchprocessid = Database.executeBatch(new BatchApex(),2000);


Best Practices When Using Asynchronous Apex

Avoid Triggering Future or Queueable Methods in High-Volume Processes

Be cautious when triggering future or queueable methods from processes that could exhaust daily asynchronous limits, such as Apex triggers. These processes can quickly consume available asynchronous resources.

Optimize Performance

Ensure the performance of future or queueable methods is optimized. This includes:

  • Optimizing queries to reduce processing time.
  • Minimizing web service callout durations.
  • Streamlining any associated logic, such as triggers or flows, to prevent bottlenecks.

Use Batch Apex for Large Data Volumes

For processing large numbers of records, always prefer Batch Apex over future or queueable methods. Batch Apex is designed to handle massive data sets efficiently, while future and queueable methods are better suited for smaller tasks.

Queueable Apex Provides Greater Flexibility

Queueable Apex offers more control over job execution compared to future methods, such as the ability to chain jobs together or handle larger data volumes more efficiently.

Conclusion

In conclusion, asynchronous Apex in Salesforce is a powerful tool for handling long-running, resource-intensive processes while maintaining system performance and user experience. By understanding the different asynchronous methods available — such as Future Methods, Queueable Apex, and Batch Apex — and following best practices, you can design efficient, scalable solutions that optimize both your code and your system’s resources. Remember to consider factors like governor limits, performance optimization, and error handling to ensure your asynchronous jobs run smoothly and reliably.

Data processing Scalability Web development tools

Opinions expressed by DZone contributors are their own.

Related

  • Leveraging Infrastructure as Code for Data Engineering Projects: A Comprehensive Guide
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  • Integrating Apache Doris and Hudi for Data Querying and Migration
  • Problem Analysis in Apache Doris StreamLoad Scenarios

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!