Salesforce has a timeout limit for transactions based on CPU usage. The apex CPU time limit exceeded means your transaction is taking too much time to complete the code execution. Let see how to resolve System.LimitException: Apex CPU time Limit exceeded error in Salesforce.
What Is Apex CPU Time Limit Exceeded Error?
Salesforce CPU time limits usage to 10 seconds for synchronous transactions and 60 seconds for asynchronous processing. The “Apex CPU time limit exceeded” error means your transaction is taking too long and can’t be completed.
System.LimitException: Apex CPU time Limit exceeded
What is not counted for Apex CPU Time Limit?
- Database operations like database operation for DML, SOQL and SOSL.
- Wait time for Apex Callout.
- Aggregate SOQL.
How to debug Salesforce CPU Time Limit
Let see how to debug and fix Apex CPU Time Limit in Salesforce. Follow below step to check all process.
- Open Debug log and then Select a log from the “Logs” tab.
- Select Debug on the top menu then select Switch Perspective. Then click on Analysis (Predefined).
- Click on Timeline.
How to resolve the Apex CPU Time Limit
How to resolve CPU Timeout Error in Salesforce.
- Write one Trigger per object.
- Avoid using Process Builder.
- Use one flow per object and per event.
- Avoid nested for loop.
- Stop Recursion in Apex Code.
Best practices to reduce CPU timeout
You can refer to Apex Best Practices to help reduce the CPU timeout. We’ll go over some of the suggestions below.
1. Avoid Multiple automation on a Single Object
Every object should have an automation strategy based on the needs of the business and the Salesforce team supporting it. In general, you should choose one automation tool per object. One of the many scenarios of older orgs is to have Apex triggers mixed in with Auto launched flows/processes or, more recently, Process Builders mixed in with Record-Triggered flows. This can lead to a variety of issues.
2. Trigger Framework
Follow Trigger Framework to avoid recursion in triggers. Trigger framework Ensures triggers are consistently handled and only required code is needed.
3. Avoid multiple Validation Rules
Multiple validation rules also introduce CPU time limit issues. Avoid multiple validation rules on a single object and an excessive number of statements in a single validation rule.
4. Using Map based query
Use map to avoid extra loops. In the below example we are using for loop to get record id which increases the CPU time.
List<Account> accList=[Select Id,Name from Account limit 100];
Set<Id> setIds=new Set<Id>();
for(Account acc: accList){ //More CPU time for sure due to looping
setIds.add(acc.id);
}
We can use the map to avoid an extra loop like the below code. Using Map query saves CPU time.
//Fetching all account in map
Map<id,account> aMap = new Map<id,account>([Select Id,Name from Account limit 50000]);
//Creating list of accounts
List<account> accList = aMap.values() ;
//Creating set of ids
Set<id> accIds = aMap.keySet() ;
5. Use Async Apex
If possible then try to execute your business process asynchronously. If you change the context then we will have high limit of 60seconds(6X of the synchronous process). Use @Future function to get extra limit for cpu time limit.
6. Aggregate SOQL usage
Since the database time is not calculated in CPU time it is always better to explore the usage of aggregate SOQL for your business use case. Push your calculations at database layer to reduce chances of hitting CPU time out issue.
7. Avoid Nested For loop
Multiple for loop and nested for loop can introduce the CPU time error. If possible filter down and process only selected record in for loop and use map to avoid nested for loop executions.
Nested loops should be avoided in Apex controllers because they may slow down the processing of the page or may hit the governing limits for the page. One easy way, and which gives some nice structure to the code is to make the inner loop a separate function, or minimize using loops altogether.
Often we encounter code where we have two or three or more nested Loops which definitely affect performance. A simple way of avoiding nested loops is using Maps. For example, you can find or create a key for each item of the second loop and put the key and the value into the Map.
8. Avoid using process builder
Process builder processing also introduce Apex CPU Time Limit. As per Salesforce use Salesforce Flow to automation and avoid using process builder and workflow.
9. Salesforce Solution Design – Performance considerations
Check out our session Salesforce Solution Design – Performance considerations session. In that session we share come comparison of performance between Process Builder, Workflow and Apex Trigger.
10. Use Return Early Pattern
Return early is the way of writing functions or methods so that the expected positive result is returned at the end of the function and the rest of the code terminates the execution.
static void someAction(Case record)
{
if (/*condition 1*/){
// do stuff
return;
}
if (/*condition2*/)
{
// do stuff
return;
}
// do stuff
return;
}
Summary
In this article we understand what is System.LimitException. Apex CPU time Limit exceeded error in Salesforce and how to avoid Apex CPU time Limit exceeded error in Salesforce. Let us know if you got this issue in your project and how you resolved it.
Thank you so much @Amit. It was a nice session and very helpful. Keep doing this in the future as well.