• Articles
  • Tutorials
  • Interview Questions

Future Method in Salesforce

Future Method in Salesforce
Tutorial Playlist

In this blog, we will explore what Future Methods are in Salesforce, why they are useful, key examples of using Future Methods, their limits, and how they differ from Queueable Methods. By the end, you will have a solid understanding of implementing Future Methods in your Salesforce applications.

Learn about Salesforce with the help of the video below:

What is a Future Method in Salesforce?

A Future Method is an asynchronous method in Salesforce that runs in the background, separate from the main execution thread. It lets you offload a long-running process from your main code and execute it independently. This prevents issues like governor limits from being hit and improves overall performance.

Some key points about Future Methods:

  • They are defined using the @future annotation.
  • They run asynchronously in a separate thread from your main code. 
  • The calling process continues executing and does not wait for the Future Method to complete.
  • Future Methods have their limits separate from your main transaction.
  • Results from a Future Method are not available immediately and must be handled asynchronously.

Enroll now in Salesforce Course to get certified in Salesforce.

Why Do we Use Future Methods?

There are a few main reasons why Future Methods are useful in Salesforce:

Why Future Methods are useful in Salesforce
  • Avoid Governor Limits – By offloading long-running processes to a Future Method, you prevent issues with governor limits in your main transaction. Future Methods have separate limits, so you can do more processing overall.
  • Improve Performance – Future Methods run asynchronously, so your main code does not have to wait for them to complete. This results in faster execution of the overall process.
  • Handle External Callouts – It is best practice to do so from a Future Method if you need to call an external API or system. This prevents the external callout from timing out and impacting your main transaction.
  • Process Many Records – If you need to loop through and process many records (thousands or millions), it is best to do it in a Future Method to avoid performance issues. Your main code can invoke the Future Method and continue on, while the Future Method handles the bulk processing in the background.
  • Callouts to Salesforce – Just like external callouts, any Salesforce callout (API, Visualforce page, etc.) should be done from a Future Method to prevent timeout issues.

Salesforce Master Course

Future Method Examples in Salesforce

Here are a few concrete examples of using Future Methods in Salesforce:

Let’s start with some basic and real-life examples first:

  • Sending Email Notifications: Future methods can be used to send email notifications to users when certain events occur in Salesforce, such as the creation of a new record or the completion of a task. By using a future method, the email can be sent in the background, without blocking the user interface.
  • Updating External Systems: Future methods can also be used to update external systems, such as a customer relationship management (CRM) platform when a record is created or updated in Salesforce. This can help keep data in sync between different systems and improve overall data accuracy.
  • Running Complex Reports: Running complex reports in Salesforce can be time-consuming and may cause the user interface to freeze. By using a future method, the report can be generated in the background, without impacting the user experience.
  • Integrating with External APIs: Future methods can be used to make API calls to external systems, such as a payment gateway or shipping provider. By using a future method, the API call can be made asynchronously, allowing the user to continue working without interruption.

Let’s discuss the other examples

Example 1: Bulk record update

This Future Method takes a list of record IDs and updates the Name field on all associated Account records. By using a Future Method, we avoid governor limits and performance issues that could result from updating thousands of records in our main transaction.

public static void bulkUpdateRecords(List<Id> recordIds) {
    List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :recordIds];
    for(Account a : accounts) {
        a.Name = 'Updated';
    }
    update accounts; 
}

Example 2: Callout to external API   

This Future Method performs a callout to an external API. Using a Future Method prevents the callout from timing out and impacting our main transaction. The main code can invoke this method and continue processing while it executes in the background.

public static void callExternalAPI() {
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('https://example.com/api/data');
    request.setMethod('GET'); 
    HttpResponse response = http.send(request);
    // Parse response and handle data
}

Example 3: Recursive process

This recursive Future Method can call itself multiple times without issue. Had this been done in our main transaction, we would quickly hit recursion governor limits. But Future Methods have their own limits, so we can recurse much deeper by using one.

public static void recursiveMethod() {
    if (/* condition */) {
        // Call self again
        recursiveMethod();  
    } 
}

Check out Salesforce Interview Questions to ace your next interview!

Can We call a Future Method from a Trigger in Salesforce?  

Yes, you can absolutely call a Future Method from a trigger in Salesforce. This is a great way to offload logic from your trigger to avoid issues with trigger governor limits.

When you call a Future Method from a trigger, the main trigger transaction completes as soon as the Future Method is invoked. The Future Method then begins executing asynchronously in the background, accessing context from the completed trigger transaction.

Any DML operations performed in the Future Method from a trigger will not fire recursive triggers. The trigger context is locked as soon as the initial trigger completes.

So calling Future Methods from triggers is a very useful pattern to maximize what you can accomplish in your triggers without hitting governor limits. The trigger can kick off one or more Future Methods to handle the bulk of the work in the background.

Also, check out the blog on Salesforce Order of Execution.

Get 100% Hike!

Master Most in Demand Skills Now !

Differences Between Future Methods and Queueable Methods

Differences Between Future Methods and Queueable Methods

Future Methods and Queueable Methods are both asynchronous tools in Salesforce, but they differ in a few key ways:

FeatureFuture MethodsQueueable Methods
Execution LimitsFuture methods are subject to asynchronous execution limits, which include a limit of 50 calls per transaction and a maximum timeout of 60 seconds.Queueable methods have higher execution limits than future methods. The maximum timeout for a queueable method is 60 minutes.
Return ValuesFuture methods do not return values synchronously. Instead, they return a unique identifier (ID) that can be used to track the status of the asynchronous operation.Queueable methods can return values synchronously, allowing the developer to process the result immediately.
SchedulingFuture methods are scheduled automatically by the Salesforce platform when system resources become available.Queueable methods can be scheduled to execute at a specific time, or they can be added to a queue and executed in order.
Error HandlingFuture methods do not support try-catch blocks. Instead, errors are handled using the Salesforce exception handling mechanism.Queueable methods support try-catch blocks, allowing for more robust error handling and recovery.

Salesforce Future Method Limits  

Just like synchronous Apex transactions, Future Methods have governor limits. However, Future Methods have higher limits than standard Apex since they run asynchronously. If your Future Method exceeds any of these limits, you will receive an “AsyncApexJob limit exceeded” error upon execution. So while Future Methods do have higher limits, they are still limited and you must architect your logic efficiently.

Some key Future Method Limits to be aware of:

  • Timeout – Can run for up to 10 minutes. After 10 minutes, the Future Method is aborted.  
  • DML statements – Can execute up to 200 DML statements. 
  • SOQL queries – Can execute up to 120 SOQL queries.
  • Callouts – Can make a maximum of 100 callouts to Salesforce APIs or external services. 
  • Loops – Can have up to 200 loops.
  • Record locking – Can lock up to 500 records.

Want to learn more about Salesforce? Salesforce Tutorial is a great place to check out. Salesforce Future Method Limits  

The Future of Future Methods in Salesforce

Salesforce continues investing in asynchronous and elastic computing tools, so we can expect Future Methods to become even more capable over time. Future Methods unlock a lot of potential in complex Salesforce applications and workflows. With tools like Batch Apex, Queueable Apex, Salesforce Events, and Platform Events, Future Methods allows you to build incredibly scalable applications on Salesforce with asynchronous functionality.

Some possible enhancements include:

  • Higher limits for calls, queries, DML, and loops. 
  • “Chaining” Future Methods to execute a series of asynchronous processes.  
  • Event-driven architecture where Future Methods are invoked in response to platform events.  
  • Managed packages of common Future Methods that can be deployed to end users.  

Conclusion

Future methods in Salesforce are a powerful tool that allows developers to perform asynchronous operations and avoid the limitations of synchronous processing. They are incredibly useful in scenarios where data processing takes a long time, and users must not wait for the results. 
The Future method executes in a separate thread and returns results at a later time. Developers must be aware of the best practices for using Future methods to ensure they are used correctly and effectively. 

If you have any questions; drop them at the Salesforce Community!

Course Schedule

Name Date Details
Salesforce Certification 01 Jun 2024(Sat-Sun) Weekend Batch
View Details
Salesforce Certification 08 Jun 2024(Sat-Sun) Weekend Batch
View Details
Salesforce Certification 15 Jun 2024(Sat-Sun) Weekend Batch
View Details