Salesforce governor limits are crucial for maintaining Salesforce stability and efficiency. Given that Salesforce (and Apex) run in a multitenant environment with shared resources, Governor limits serve to ensure no single user consumes all the resources, keeping the platform fair and responsive for everyone.
This article will help you understand what these limits are and how to work within them effectively.
1. What is a Salesforce Governor?
Definition:
A Salesforce Governor is a system mechanism within Salesforce that enforces specific limits on resource usage. Think of it as a checkpoint ensuring fair distribution of system resources.
Role:
Governors prevent any single tenant from monopolizing resources. This keeps the Salesforce environment stable and efficient for all users.
2. What are Salesforce Governor Limits?
SFDC Governor Limits are the specific restrictions enforced by Salesforce to maintain system performance and security.
Consider Governor Limits in Salesforce as the borrowing rules in a library. The library allows you to borrow a certain number of books (resources) at a time to ensure everyone has access. Each operation in Salesforce is like borrowing a book. There are limits on how many books (queries, DML statements) you can borrow to ensure fair usage and availability of its
➡️ Please note that Salesforce governor limits do not include storage.
For information on Salesforce data and storage limits, check out our other articles
Salesforce Data: Cut Costs and Boost Compliance and Salesforce Storage Limit Exceeded.
API calls limits are also beyond the scope of this article, but be aware that a daily API call limit exists. The limit varies based on your organization type and license. You can check the Salesforce API limits (programmatically) using the OrgLimits class. More information on the API Request Limits and Allocations article.
3. Common Types of Salesforce Governor Limits
SOQL Query Limits:
- The "Too Many SOQL Queries" error occurs when more than the maximum number of SOQL queries are executed in a single transaction. In a SOQL query with parent-child subqueries, each parent-child relationship counts as an extra query.
- Maximum queries: 100 (synchronous), 200 (asynchronous).
Result Row Limits:
- The "Too many Query rows" error occurs when the queries in a single transaction return more than the allowed number of rows.
- Maximum Query rows: 50 000
DML Statement Limits:
- The "Too many DML statements" error occurs when more than the allowed number of DML operations are executed within a single transaction.
- Maximum DML operations: 150 (synchronous), 300 (asynchronous).
Heap Size Limits:
- The "Apex heap size too large" error occurs when too much data is stored in memory during processing.
- Maximum heap size: 6 MB (synchronous), 12 MB (asynchronous).
CPU Time Limits:
- The “Apex CPU time limit exceeded” error means your transaction took too long, exceding the maximum CPU time.
- Maximum CPU time: 10,000 ms (synchronous), 60,000 ms (asynchronous).
For other types of governor limits, check the Apex Developer Guide.
4. Exceeding the Governor Limits: An Example and Solution
One common issue developers face is the "101 Too Many SOQL Queries" governor limit exception. This error occurs when more than 100 SOQL queries are executed in a single transaction (in synchronous mode).
Example: Consider the following code snippet that tries to fetch account details inside a loop:
public class AccountProcessor {
public void processAccounts() {
List<Account> accounts = [SELECT Id, Name FROM Account];
for (Account acc : accounts) {
// This query within a loop can easily exceed the SOQL limit if there are many accounts
List<Contact> contacts = [SELECT Id, Name FROM Contact WHERE AccountId = :acc.Id];
// Process contacts
}
}
}
This code will quickly hit the 101 SOQL queries limit if the number of accounts exceeds 100.
Solution: A better approach would be to bulkify the query:
public class AccountProcessor {
public void processAccounts() {
List<Account> accounts = [SELECT Id, Name FROM Account];
Set<Id> accountIds = new Set<Id>();
for (Account acc : accounts) {
accountIds.add(acc.Id);
}
List<Contact> contacts = [SELECT Id, Name, AccountId FROM Contact WHERE AccountId IN :accountIds];
Map<Id, List<Contact>> accountContactsMap = new Map<Id, List<Contact>>();
for (Contact con : contacts) {
if (!accountContactsMap.containsKey(con.AccountId)) {
accountContactsMap.put(con.AccountId, new List<Contact>());
}
accountContactsMap.get(con.AccountId).add(con);
}
for (Account acc : accounts) {
List<Contact> acctContacts = accountContactsMap.get(acc.Id);
// Process contacts
}
}
}
This refactored code might be a bit longer, but it fetches all related contacts in a single query, avoiding the SOQL limit.
The "101 Too Many SOQL Queries" Governor Limit Exception is also common when uploading files, when you use a query to upload each file.
5. How to Monitor Salesforce Governor Limits
Monitoring your resource usage is essential to make sure you don’t hit these limits. For this you should use the Salesforce Developer Console.
If you do see one of the errors mentioned previously, the debug logs can help. Salesforce also provides a Limits class and built-in methods like
- getQueries();
- getDML();
Returns the number of records that have been processed with any statement that counts against DML limits
The most common causes for governor limit errors are:
- Having Queries and Operations within loops: Avoid DML operations and queries inside loops.
- Improper Error Handling: Implement proper exception handling to prevent unexpected limit errors.
7. Best Practices for Managing Governor Limits
To stay within limits, follow these best practices:
Efficient Querying:
- Try to retrieve all necessary data in a single query rather than in a loop. If a loop is necessary, use the for loops of SOQL. If your issue is with the result set having too many rows, use Limit and Filter in your queries.
Bulk Processing:
- Use bulk processing methods and design patterns. Combine records into collections and perform bulk DML operations.
Use of Collections:
- Minimize DML operations by using collections.
Code Optimization:
- Write efficient, optimized code. Avoid unnecessary loops and use efficient algorithms.
Governing Transactions:
- Opt for asynchronous processing to manage large-scale operations.
8. Advanced Strategies for Large Data Volumes
Managing large data volumes requires strategies like asynchronous processing, batch processing, and queuing your jobs.
Use @future methods, Batch Apex, and Queueable Apex to handle extensive operations without going over the different limits.
9. Governor Limits In Short
Governor limits ensure fair use of resources in Salesforce's multitenant architecture. By understanding what these limits are and how they function, you can avoid errors and optimize your application's performance.
We've discussed key types of Governor Limits like SOQL query limits, DML statement limits, heap size, and CPU time limits. We've also shown how to monitor these limits using the Developer Console and the OrgLimits class. It's important to follow best practices such as efficient querying, bulk processing, and asynchronous processing to stay within these limits.
For example, breaking down large data transactions using Batch Apex or Queueable Apex can help manage and optimize resource usage. Likewise, understanding pitfalls like running queries or DML operations within loops can prevent common errors.
Remember, efficient code and proper resource management not only mitigate risks of hitting limits but also ensure smooth operation for all users sharing the Salesforce environment.
10. Frequently Asked Questions (FAQ)
- What are Salesforce Governor Limits?
- Governor Limits are restrictions Salesforce enforces to manage system resources.
- Why does Salesforce enforce Governor Limits?
- They ensure fair resource usage and maintain system performance.
- How can I check if I'm approaching Governor Limits?
- Use the Salesforce Developer Console and tools like the Limits class to monitor usage.
- What happens if I exceed a Governor Limit?
- Exceeding a limit results in errors and failed transactions.
- Can I Bypass Salesforce Governor Limits?
- Limits are strictly enforced, but you can change your code to work within existing limits, as seen in this example.
About the Author
By Ana Neto, technical advisor at Connecting Software.
“I have been a software engineer since 1997, with a more recent love for writing and public speaking. Do you have any questions or comments about this article? I would love to have your feedback, leave a comment below!"