Open In App

Governor Limits in Salesforce

Last Updated : 23 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Salesforce operates in a multitenant environment, where multiple organizations share the same system resources. To ensure fair resource allocation, Salesforce imposes governor limits that define the maximum resource usage for each organization or process. These limits are critical for maintaining system performance and stability, preventing any single operation or tenant from consuming excessive resources.

This article explores the concept of governor limits, why they exist, common limits, and best practices for working within them efficiently. Examples and solutions are provided to help you avoid and resolve governor limit issues.

What Are Salesforce Governor Limits?

Governor limits are restrictions set by Salesforce to ensure efficient resource use in a multitenant environment. These limits apply to various resources such as database operations, memory, and processing time.

Why Do Governor Limits Exist?

In Salesforce’s multitenant architecture, a single server hosts multiple Salesforce organizations (orgs). This is comparable to an apartment building where residents share utilities like water, electricity, and internet. Without limits, one tenant’s excessive usage could negatively impact others. Governor limits act as safeguards, ensuring equitable resource distribution among all tenants.

Example:

  • SOQL Queries: Each transaction is limited to 100 SOQL queries to prevent inefficient data retrieval.
  • DML Statements: A maximum of 150 DML operations per transaction ensures database performance optimization.

Types of Salesforce Governor Limits

Salesforce governor limits can be broadly categorized into the following types:

1. Per-Transaction Apex Limits

These limits apply to individual Apex transactions. For example:

  • Maximum 100 SOQL queries.
  • Maximum 150 DML statements.
  • Total heap size: 6 MB (synchronous) or 12 MB (asynchronous).

2. Per-Transaction Certified Managed Package Limits

  • Managed packages developed by Independent Software Vendors (ISVs) that pass Salesforce's security review often have separate governor limits. This allows ISV applications to coexist without interfering with the main org’s resources.

3. Lightning Platform Apex Limits

These limits are not tied to a specific transaction but are enforced at the platform level. For example:

  • Maximum API requests per 24-hour period (varies by license and edition).

4. Static Apex Limits

These limits are fixed across all transactions, such as:

  • Maximum CPU time per transaction: 10 seconds (synchronous) or 60 seconds (asynchronous).

5. Size-Specific Apex Limits

These limits pertain to data and code size:

  • Maximum size of a SOAP request or response: 6 MB.
  • Maximum size of callout request or response: 6 MB.

6. Miscellaneous Apex Limits

  • Other limits include email services, push notifications, and asynchronous job execution.

Common Governor Limits and How to Resolve Them

1. SOQL Query Limit

Limit: A single transaction can execute a maximum of 100 SOQL queries.

Example of Exceeding the Limit:

for (Integer i = 0; i <= 100; i++) {
Integer count = [SELECT COUNT() FROM Account];
}

This runs a SOQL query in a loop, exceeding the limit.

Resolution:

Move SOQL queries outside loops by using collections and batch processing.

Improved Code:

apex
List<Account> accounts = [SELECT Id, Name FROM Account];
Map<Id, Integer> contactCounts = new Map<Id, Integer>();

for (Account acc : accounts) {
    contactCounts.put(acc.Id, [SELECT COUNT() FROM Contact WHERE AccountId = :acc.Id]);
}
System.debug(contactCounts);

2. DML Statement Limit

Limit: A single transaction can execute a maximum of 150 DML statements.

Example of Exceeding the Limit:

for (Account acc : [SELECT Id, Name FROM Account]) {
Contact con = new Contact(AccountId = acc.Id, LastName = 'Test');
insert con;
}

This inserts one record per loop iteration, quickly exceeding the 150 DML limit.

Resolution:

Perform bulk DML operations by using collections.

Improved Code:

List<Contact> contacts = new List<Contact>();

for (Account acc : [SELECT Id, Name FROM Account]) {
contacts.add(new Contact(AccountId = acc.Id, LastName = 'Test'));
}
insert contacts;

3. Heap Size Limit

Limit: Total heap size for a transaction is 6 MB (synchronous) or 12 MB (asynchronous).

Example of Exceeding the Limit:

List<String> largeData = new List<String>();
for (Integer i = 0; i < 100000; i++) {
largeData.add('Sample Data ' + i);
}
System.debug(largeData);

This code generates a large data structure that may exceed the heap size limit.

Resolution:

  • Use SOQL to query data as needed, instead of storing large collections.
  • Use Limits.getHeapSize() to monitor heap usage.

Improved Code:

List<String> largeData = new List<String>();
for (Integer i = 0; i < 100; i++) { // Reduce iterations
largeData.add('Sample Data ' + i);
}
System.debug(largeData);
System.debug('Heap size: ' + Limits.getHeapSize());

Best Practices to Avoid Governor Limits

  1. Bulkify Code: Always design Apex code to handle multiple records at once. Use collections to perform bulk operations on SOQL queries and DML statements.
  2. Avoid SOQL or DML in Loops: Never include SOQL queries or DML operations inside loops. Instead, move them outside the loop and process them in bulk.
  3. Use Collections and Maps: Use collections like List, Set, and Map to process data efficiently.
  4. Leverage Built-In Limits Class: Salesforce provides the Limits class to monitor resource usage. For example:
    • System.debug('SOQL queries used: ' + Limits.getQueries());
  5. Optimize SOQL Queries: Query only the fields you need instead of retrieving all fields with SELECT *.
  6. Use Asynchronous Processing: For large data volumes, use Batch Apex or Future Methods to process data in chunks.
  7. Monitor and Debug: Use the Developer Console or debug logs to monitor resource usage and identify areas for improvement.
  8. Leverage Tools: Use tools like Salesforce PMD or SonarQube to scan code for violations of best practices.

Importance of Governor Limits

Understanding and adhering to governor limits is critical for Salesforce developers. These limits:

  1. Ensure Stability: Prevent any single org or process from monopolizing shared resources.
  2. Encourage Best Practices: Promote efficient, scalable, and maintainable code.
  3. Protect Multitenancy: Preserve performance for all orgs sharing the Salesforce instance.

Failure to respect governor limits results in unhandled exceptions that halt code execution, negatively impacting user experience and business processes.

Conclusion

Governor limits are a fundamental aspect of Salesforce’s architecture, ensuring performance, scalability, and fairness in its multitenant environment. For developers, these limits are both a challenge and a guide to writing efficient, resource-conscious code.

By understanding the different types of limits and implementing best practices like bulkification, SOQL optimization, and asynchronous processing, you can create applications that run smoothly within these constraints. Mastering governor limits not only prevents runtime exceptions but also lays the foundation for robust, scalable Salesforce solutions.


Explore