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.
Join the DZone community and get the full member experience.
Join For FreeWhen 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.
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.
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.
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.
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.
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.
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.
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:
- An instance of the Batch Apex class.
- An optional batch size parameter, which specifies the number of records per batch. The maximum batch size you can specify is 2000.
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.
Opinions expressed by DZone contributors are their own.
Comments