Governor Limits In SalesForce Tutorial Learning Path - Complete Guide
job opening acte

Governor Limits In SalesForce Tutorial Learning Path – Complete Guide

Last updated on 09th Jul 2020, Blog, Tutorials

About author

Joseph (Senior Salesforce Developer )

Joseph has 8+ years of expertise in Salesforce and has intense knowledge of Apex, Visualforce, Lightning Component framework, Triggers, Batch, Schedulers, and Apex Test Classes. His articles assist in sharing information and abilities in core fields and provide students with informative knowledge.

(5.0) | 19547 Ratings 1341

Simply put, Salesforce Governor Limits are usage caps enforced by Salesforce to ensure efficient processing. They allow for multiple users of the platform without impeding performance.

There are many different types of governor limits, some of which are tied to your Salesforce edition. For example, Professional Edition enables one to have 50 custom objects but 2,000 for Unlimited and Performance.

What are Governor Limits?

  • As we know, Apex runs in multi-tenant environment, i.e., a single resource is shared by all the customers and organizations. So, it is necessary to make sure that no one monopolizes the resources and hence Salesforce.com has created the set of limits which governs and limits the code execution. Whenever any of the governor limits are crossed, it will throw error and will halt the execution of program.
  • From a Developer’s perspective, it is important to ensure that our code should be scalable and should not hit the limits.All these limits are applied on per transaction basis. A single trigger execution is one transaction.As we have seen, the trigger design pattern helps avoid the limit error. We will now see other important limits.
  • Some other governor limits have ‘soft’ limits that can either be solved by Salesforce or by purchasing additional add-ons. For example, the current limit is 6MB of Apex code per org but this can be increased on a case by case basis by Salesforce Support. Other limits are based on a combination of both your Salesforce edition but also the number of user licenses on the org. For example, API and data storage limits.
  • Other governor limits are associated more with programming in Apex: for example, an Apex class / execute anon script can only have 100 SELECT statements per synchronous transaction. Some of these limits are ‘hard’, meaning that they cannot be increased and so a new approach by the developer would be needed to achieve the desired result.This multi-tenancy and this Salesforce Summary article go into more detail on this subject.

The Different Types of Salesforce Governor Limits:

Per-Transaction Apex Limits

These limits count for each Apex transaction. For Batch Apex, these limits are reset for each execution of a batch of records in the execute method.

Per Transaction Certified Managed Package Limits

If a managed package developed by a Salesforce ISV has passed security review, they are provided with generally higher per-transaction limits.

    Subscribe For Free Demo

    [custom_views_post_title]

    Lightning Platform Apex Limits

    • These limits aren’t specific to an Apex Transaction and are enforced by the Lightning platform.

    Static Apex Limits

    • Apex Limits that are applied across all transactions.

    Size-Specific Apex Limits

    • Apex Limits related to the size of code.

    Miscellaneous Apex Limits

    • …other Limits! 

    Why are Salesforce Governor Limits Important?

    Governor Limits are a concept that all Salesforce Developers (and Admins to a lesser extent), must grasp. They will fundamentally shape the way that you architect Salesforce solutions, as well as how the code is written.

    If a Salesforce Governor Limit is hit, the associated governor issues a runtime exception that cannot be handled. Which translates to, your code breaks and won’t work.

    Types-Governor-Limits

    How to Overcome Governor limits in Salesforce?

    To overcome Salesforce Governor Limits a special care must be taken while writing code.

    • Never make any SOQL and DML operation inside the loop.
    • Use les number of script statements.
    • Use batch apex, when working with above 50000 records.
    • Use @future.
    • Use Batch Apex.
    • Use Annotations.
    • Use for loop.
    • Using ‘in’ clause.

    Governor Limit Best Practices

    As per the official docs, there are a huge number of different types of governor limits. This article will cover some of the more common ones associated with Apex programming and outline approaches that can be taken to resolve them.

    1. SOQL 100 Limit

    One of the most well known governor limits is that an apex class / execute anonymous script can ‘only’ have 100 SELECT statements per apex transaction.

    By the way, an apex transaction is a set of operations that are executed in a single unit. For example, when a trigger runs on every Account that has its name updated, processing is done to update all references across tasks and events from the old Account name to the new Account name. The sum of operations and resources that are leveraged that take place to achieve this is the apex transaction.

    To demo this particular governor limit, go to a sandbox and navigate to the Developer Console. Either input cmd + E or Debug | Open Execute Anonymous Window and input the following:

    • for (integer i = 0; i <= 100; i++) { Integer countOfAccounts = [SELECT COUNT() FROM Account];}
    SOQL-100-Limit

    Upon highlighting and then selecting ‘Execute Highlighted’ in the Dev console, you’ll receive the following error:

    Anonymous-error

    This is happening as per the docs: you can only have 100 SELECT statements in a synchronous context.

    Course Curriculum

    Learn from JOB Oriented Salesforce Certification Courses with In-Depth Industry Modules

    Weekday / Weekend BatchesSee Batch Details
    synchronous-context

    SOQL 100 Limit Fix

    Most commonly, this governor limit will be hit because there is a SOQL statement in a for loop; which is considered one of the ‘cardinal sins’ of programming in Apex.

    • List accounts = [SELECT Id, Name FROM Account];
    • Integer> contactCount = new List<Integer>();
    • for (Integer i = 0; i <= accounts.size(); i++) {  
    • Integer count = [SELECT COUNT() FROM CONTACT WHERE AccountId IN : accounts];  
    • contactCount .add(count);}

    The moment that there are more than 99 accounts in the variable ‘accountList’, then the code will fail.

    A simple solution is simply to move all SOQL statements outside of for loops, and especially if the for loop iterator is dynamic (the number of accounts in the list could change but if the iterator is a number, then that is fixed). To do that, you’ll likely be depending more on other collections and inventive SOQLs.

    An approach can be like so:

    • Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id FROM Account]);
    • Map<String, Integer> accountNamesAndRespectiveContactCounts = new Map<String, Integer>();
    • for(Account accountObject :
    • [SELECT Name, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :accountMap.keySet()]){      accountNamesAndRespectiveContactCounts.put(accountObject.Name, accountObject.Contacts.size());}
    • system.debug(‘accountObject map is: ‘ + accountNamesAndRespectiveContactCounts);

    2. DML 150 Limit

    Probably the second most well known governor limit concerns the number of DML operations in a single transaction. As per the docs, the limit is 150:

    DML-statements

    To demonstrate this, in a developer sandbox, you can run the following execute anonymous code:

    • List<Account> accountList = new List<Account>();
    • Account accountObject;for (Integer i = 0; i < 150; i++){    
    • accountObject = new Account();  
    •   accountObject.Name = ‘Test ‘ + i;    
    • accountList.add(accountObject);}
    • insert accountList;

    This will create 150 Accounts. 

    Now, try to execute the following code:

    • Contact contactObject;
    • for (Account accountIterator : [SELECT Id, Name FROM Account]){    
    • contactObject = new Contact();   
    •  contactObject.AccountId = accountIterator.Id;    
    • contactObject.LastName = ‘Surname ‘ + accountIterator.Name;    
    • insert contactObject;}

    Your execute anon should look like this:

    execute-anon

    You will hit the following error:

    Anonymous-error

    DML 150 Limit Fix

    Again, it’s a fairly straight forward fix. You should not use DML statement inside for loops (btw this is something that good code scanning tools such as PMD will pick up on) and instead, you should leverage collections to store the data and then when you do a DML operation on a collection, it only counts as one DML!

    To demonstrate that, let’s execute the following code and for good measure, let’s leverage some of the helpful methods from the Limits class.

    DML-150-Limit-Fix

    • List<Contact> contactList = new List<Contact>();
    • Contact contactObject;
    • for (Account accountIterator : [SELECT Id, Name FROM Account LIMIT 150]){
    • contactObject = new Contact();
    • contactObject.AccountId = accountIterator.Id;contactObject.LastName = ‘Surname ‘ + accountIterator.Name;
    • contactList.add(contactObject);}
    • if (contactList.size() > 0){  
    • insert contactList;}
    • system.debug(‘Size of contact list is: ‘ + contactList.size());
    • system.debug(‘Count of DML statements: ‘ + Integer.valueOf(Limits.getDmlStatements()));

    Opening up the debug log will display the following:

    Course Curriculum

    Get Practical Oriented Salesforce Training to UPGRADE Your Skill Set

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum
    Display-log

    That is very cool – you could have a collection with tens of thousands of records (or much more) and yet still only use 1 of your 150 available DML statements. Talk about efficient!

    Advantages of Governor Limits in Salesforce

    • Governor limits in Salesforce prevent other org from using and hence executing lengthy code, which can take up a lot of space in the memory and even the entire cloud CPU.
    • Apex has completely different or unique coding limits.
    • These governor limits help us stay in the right space of coding with Apex.

    How can you avoid Salesforce Governor Limits?

    As a developer, we need to ensure that our code is scalable and does not exceed the governor limits. But how? Follow this process to meet the governor limits in Salesforce:

    • Do not have DML statements or SOQL queries in our FOR loop
    • Try not to use SOQL or DML operations in the loop
    • Try to bulkify the code and helper methods
    • Query large data sets
    • Use Batch Apex if we want to process 50,000 records
    • Streamline various triggers on the same object
    • Use streamlining queries and collections for loops
    Salesforce Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    I hope you now understand how governor limits work in Apex and how to avoid them.

    CONCLUSION:

    In conclusion, there are many different types of governor limits across Salesforce and for good reason – to help us become more efficient developers and admins. There are some general patterns that you can adopt to ensure that you stay below the limits. Generally speaking, the most well-known limits are those around SOQL and DML limits in a single transaction. You also learned that getting past governor limits can be challenging and fun at the same time.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free