Apex CPU time limit exceeded Errors

If your org has a lot of synchronous triggers or Process Builder flows, you may occasionally see a message like "Apex CPU time limit exceeded" when inserting or updating records. It may look like the following:

geopointe.GP_Account: System.LimitException: Apex CPU time limit exceeded. For details, see API Exceptions.

You might assume this is a Geopointe error because it says "geopointe," but this is not exactly the case, and we'll dive into why. 

Salesforce puts limits in place to prevent one customer from hogging all the server resources. Limiting CPU time per transaction is one of these limits. This also prevents issues like infinite loops that would run forever if not stopped. For insert and update operations, Salesforce limits the amount of CPU time to 10 seconds. This may seem like plenty of time but this quota can quickly be eaten up by inefficient triggers, Process Builder Flows, and more. 

A key concept to understand is that this limit is shared by all Apex code executing. This includes the customer's code, Process Builder Flows, and all other managed packages installed (like Geopointe). You can think of this CPU limit as a bucket of resources. Every time something runs that requires CPU time, it will reach in to the bucket and take a little bit of CPU time. This is fine until some part of the process reaches into the bucket and there is nothing left. This is when the code gets in trouble and displays an error like "Apex CPU time limit exceeded." There may have been another process using 9.9 seconds seconds of that CPU time, but the next process that runs for only 0.1 seconds is the code that meets trouble for hitting the limit. This is why it sometimes says a Geopointe trigger caused the error, when in reality it was simply the piece of code to hit the limit, not the piece of code to use up all the resources. Below is an image to help you visualize this:

We have performed significant amounts of diligence to make sure our triggers follow all best practices and are tuned for performance. In our testing, most of our triggers use less than 100ms of CPU time. What is probably using up most of the CPU time is other Apex Triggers and Process Builder flows.

The obvious question is: 
What can I do to reduce CPU time?
- If you are performing mass inserts or updates, reduce the batch size.
- Use @future calls and asynchronous processing to move non-critical business logic out of triggers. 
- Convert Process Builder flows to Apex Triggers if possible.
- See this Salesforce.com article on writing efficient Apex code.
- Follow best practices for Triggers and Bulk processing
- Vote for this idea on the Salesforce Idea Exchange.

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页