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 ..you 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 salesforce.stackexchange.com) 


http://salesforce.stackexchange.com/questions/18244/how-do-sf-calculate-the-cpu-limit


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 .


http://blogs.developerforce.com/engineering/2013/09/script-limits-begone.html


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
- SOSL
- 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

TLS 1.0 has been disabled For Sandbox - Salesforce

Salesforce has finally disabled TLS 1.0 in sandboxes .This is in preparation for disablement later in 2017 for PRODUCTION instances .

Now this would have not impacted your integrations in PRODUCTION org but if your integration is broken in your sandbox ,this means you have only few months to sort this and fix before this affects your integration for PROD live users .
Before we deep drive on how to possibly fix this and work with your external systems to figure solution ,lets first understand what is TLS and why did SFDC moved to 1.x and had to disable TLS 1.0
TLS 1.0 Explained























TLS 1.1 Improvements 
Added protection against cipher-block chaining (CBC) attacks. Support for IANA registration of parameters.

Clearly TLS 1.1 is more secure(Compared to 1.0) and protects salesforce resources against CBC attacks .
Identify if this change broke anything .The things that can be affected in your instances are as below Web requests to Salesforce URLs that require authenticationWeb requests to the login pag…

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
    -SalesLeaderBoard
    …

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; …