Skip to main content

Battling CPU time out limit in apex sfdc

As per winter 14 release a new Limit was introduced for apex transactions which was brought in instead of number of script statements (2,00,000 script statement was maximum script statements allowed ).If you are guessing its CPU time out limit i am blogging on are right .Its this new feature which asks for developer to be more smart and more thoughtful in designing and approaching any apex design going forward 

One question that quickly came to my mind when this was announced is what will happen to previous code which took more than 10s (Please note for synchronous transactions 10 seconds is the CPU limit ) ?

I found answer to this in my favorite community that i spent lot of my time in(Yes its the

Read the technical  discussion that went deep to exploring OS concepts in computer science .So the answer why the previous code wont break is because salesforce analyzed all their previous code and for each org they took the maximum CPU time that a code took to execute and have set the time out equal to that .Example assume before winter 14 i have an org A and that had a code which did not hit script execution limit but took 15 seconds of CPU time in that case for org A the CPU time limit is 15 seconds .

It wont be fair if i dont explain whats this CPU time of apex transaction here.

CPU Time :Read the below blog link from apex product manager himself to dig deeper .

The time taken by the apex transaction in a context including validations,workflows apex code and  excluding time taken in DML,queries,callouts is called CPU time .

Lets be once more clear on whats counted in CPU time and whats not

What's counted:

- All Apex code
- Library functions exposed in Apex
- Workflow execution
What's not counted:

- Database operations, e.g. DML, SOQL
- HTTP callouts

Now lets discuss some of the best practices  in code which will help to reduce the CPU time out 

1)Using Map Based Query 

Very clear this was taught to us when we had to reduce script statements ,well same best practice is also useful when you want to reduce the CPU time

2)Explore option to see if your business scenario allows you to do the operation asynchronously 

In some cases business process may not be real time and hence if there is a chance to make code execute in @future ,this will break the context and also the CPU time out limit for asynchronous process is 60seconds(6X of synchronous process).So do consider a thought on this if you are in trouble of hitting this limit

3)Aggregate SOQL usage 

Since the database time is not calculated in CPU time its always better to explore the usage of aggregate SOQL for your business use case .

Say you want summation of field value  of some records ,if you use normal for loop to get these obvious you have spent CPU time there .Instead try to push your calculation using SUM,AVG aggregate functions at the database layer itself so that you have reduced CPU time and have pushed the process on database layer itself.Explore options to group by or create some sort of filtering at database layer and push your calculations at database layer to reduce chances of hitting CPU time out issue .

4)Make sure you take only necessary data and run a loop .

This is essential now to filter only specific data while doing a for on a list of records as too much looping will increase CPU time .Same held good when we had no of script statements limit .

So conclusion is clear some of best practices we used to reduce script statements still hold good and its essential to follow these .

If you have come across any other techniques in apex to reduce the CPU time consumed please post below and i am happy to learn and share .

Happy coding !

Popular posts from this blog

Invoking Apex Callout From Process Builder

Process builder is GA in Spring 15 and one of the queries I came across was around how to invoke apex callouts from Process builder .

Before process builder came we had two common approaches of calling webservice 

1)We have outbound messages as one of the Actions for workflows.This works if other party implements the WSDL that is generated once Outbound messaging is defined with appropriate end point .

2)Most of times future method invoked through triggers allowed to do apex callouts and invoke external web service provided the future method is annotated with @future(callout=true).This provides lot of flexibility and one of the best approaches .

3)Flow triggers was in BETA and this was also one of the ways we could invoke callouts provided the Flow implements process plugin .To understand in detail how to implement process plugin refer to the below example

The purpose of this blogpost is to demonstrate the new possibility of invoking apex callout through Process Builder 

I tried initi…

Opening Modal Using Lightning Component Framework of SFDC

One of my friend from India threw a challenge .The challenge was to open a modal by using latest and greatest lightning components framework and modals design from SLDS .For the love of community I thought of sharing the entire code base that I did .

So here we start ..

Business Use Case - Need a handy SalesLeader board component that can be used to display the Sales revenue generated by each sales rep for current year in the order of decreasing total revenue .On click of the tile ,we will show detail opportunity list aggregating the revenue .

The component can be dragged in lightning design experience or in App builder lightning Page .

Video Demonstration-

SalesLeaderBoard from Mohith Kumar Shrivastava on Vimeo.

Frameworks Used -
Lightning Design Systems (SLDS) for CSSLightning Component Framework for client side logicApex aura enabled class for backend logicApproach
The component hierarchy is very important to imagine or mindmap before we dig deeper- SalesLeaderMain

Writing Test Classes For Apex Rest Service

I came across a question in a developer community on how to write Unit Test Classes for the Rest API service for POST HTTP calls

Unit Test Classes for REST API following link is very useful and inspired by this jeff had an article on his blog on how to write the test method for same .

Here is the Jeff Blog Link Test Class for REST API(Good reference for GET Rest Services)

In one of my previous blog post i demonstrated how to use native parsing technique for Rest api for User Defined Type
I wrote the Test class for the same and this post is helpful for all those searching for how to write test classes for apex rest service annotated with POST Call
Here is the Rest Service Class for which i attempted the test class
@RestResource(urlMapping='/DemoUrl/*') global with sharing class MyRestResourcedemo { global class RequestWrapper{ public Account acct; public Contact[] cons; } global class ResponseWrapper { public String StatusCode; …