Site icon Trailhead Titans

⚡Understanding Governor Limits in Salesforce (Complete Guide for Developers)

Salesforce is a multi-tenant cloud platform, which means multiple organizations share the same computing resources such as CPU, memory, and database infrastructure.

To ensure that no single organization consumes excessive resources, Salesforce introduced a mechanism called Governor Limits.

For every Salesforce developer, understanding Governor Limits is not optional — it is critical. Poorly designed code can quickly hit these limits and cause runtime exceptions.

In this guide, we will explore:

• What Governor Limits are
• Why Salesforce enforces them
• Types of Governor Limits
• Important limits every developer should know
• Examples and best practices to avoid hitting limits
• Real-world interview scenarios


What Are Governor Limits?

Governor Limits are runtime limits enforced by the Salesforce platform to control how much resources Apex code can consume during execution.

If your code exceeds these limits, Salesforce throws a runtime exception and stops the execution.

Example error:

System.LimitException: Too many SOQL queries: 101

This means your code executed more SOQL queries than the allowed limit.

Governor Limits help ensure:

• Fair resource usage across all tenants
• System stability and performance
• Protection against poorly written code


Why Salesforce Uses Governor Limits

Salesforce follows a multi-tenant architecture.

In a multi-tenant environment:

• Multiple customers share the same infrastructure
• Database and compute resources are shared
• One inefficient application can affect others

Governor Limits ensure:

✔ Fair resource allocation
✔ Platform stability
✔ Efficient code design
✔ Scalable applications

Without Governor Limits, a poorly designed trigger or Apex class could consume all system resources.


Types of Governor Limits

Governor Limits can be categorized into several types.

1. Per-Transaction Apex Limits

These limits apply per Apex transaction.

A transaction could be triggered by:

• Trigger execution
• Apex class execution
• API call
• Batch job execution

Common Per-Transaction Limits include:

LimitSynchronous ApexAsynchronous Apex
SOQL Queries100200
DML Statements150150
Records Retrieved by SOQL50,00050,000
Heap Size6 MB12 MB
CPU Time10 seconds60 seconds
Callouts100100

Most Important Governor Limits Developers Must Remember

These are the limits most commonly tested in Salesforce interviews.

1. SOQL Query Limit

Maximum SOQL queries per transaction:

100 for synchronous Apex
200 for asynchronous Apex

Bad Example (SOQL inside loop)

for(Account acc : Trigger.new){
Contact con = [SELECT Id FROM Contact WHERE AccountId = :acc.Id LIMIT 1];
}

If 200 records trigger this logic, the SOQL query executes 200 times, exceeding the limit.

Correct Approach (Bulkified)

Set<Id> accountIds = new Set<Id>();for(Account acc : Trigger.new){
accountIds.add(acc.Id);
}List<Contact> contacts = [
SELECT Id, AccountId
FROM Contact
WHERE AccountId IN :accountIds
];

2. DML Statement Limit

Maximum 150 DML operations per transaction.

Bad Example

for(Account acc : accounts){
insert acc;
}

Correct Approach

insert accounts;

Bulk operations help prevent hitting the DML limit.


3. CPU Time Limit

Maximum CPU time allowed:

10 seconds for synchronous Apex
60 seconds for asynchronous Apex

CPU time includes:

• Apex code execution
• Database operations
• Complex loops

Bad Example

for(Integer i = 0; i < 1000000; i++){
// heavy processing
}

To reduce CPU usage:

✔ Optimize loops
✔ Use Maps and Sets
✔ Avoid nested loops when possible


4. Heap Size Limit

Heap size represents the amount of memory used during Apex execution.

Limits:

6 MB for synchronous
12 MB for asynchronous

Example problem:

Large collections or large JSON responses may exceed heap limits.

Solution:

• Process data in batches
• Avoid storing unnecessary data


5. Maximum Records Retrieved

Maximum 50,000 records can be retrieved using SOQL in a transaction.

If more records are needed:

Use Batch Apex.

Example:

Database.getQueryLocator()

Batch Apex can process millions of records.


Governor Limits for Batch Apex

Batch Apex has different limits because it processes records in smaller chunks.

Each batch execution gets fresh limits.

Example:

global class AccountBatch implements Database.Batchable<SObject>{    global Database.QueryLocator start(Database.BatchableContext bc){
return Database.getQueryLocator('SELECT Id FROM Account');
} global void execute(Database.BatchableContext bc, List<Account> scope){
// process records
} global void finish(Database.BatchableContext bc){ }
}

If batch size = 200, each execution processes 200 records with fresh limits.


Static vs Non-Static Limits

Static Limits

These cannot be increased.

Examples:

• Maximum SOQL queries
• Maximum DML statements
• CPU time

Size-Specific Limits

These depend on the edition of Salesforce.

Examples:

• Data storage
• API requests


How to Check Governor Limits in Apex

Salesforce provides the Limits class.

Example:

System.debug(Limits.getQueries());
System.debug(Limits.getLimitQueries());

Example output:

Number of SOQL queries used: 10
Maximum allowed queries: 100

Other useful methods:

Limits.getDmlStatements()
Limits.getCpuTime()
Limits.getHeapSize()

This helps monitor resource consumption.


Best Practices to Avoid Governor Limits

1. Avoid SOQL Inside Loops

Wrong:

for(Account acc : accounts){
[SELECT Id FROM Contact WHERE AccountId = :acc.Id];
}

Correct:

Use single SOQL query with IN clause.


2. Avoid DML Inside Loops

Wrong:

for(Contact c : contacts){
update c;
}

Correct:

update contacts;

3. Write Bulkified Code

Always design code to handle multiple records at once.

Triggers should never assume only one record.


4. Use Collections (Map, Set)

Collections improve performance.

Example:

Map<Id, Account> accountMap = new Map<Id, Account>(accounts);

5. Use Asynchronous Processing

For heavy operations use:

• Future Methods
• Queueable Apex
• Batch Apex
• Scheduled Apex

This helps distribute resource consumption.


Real Interview Scenario

Interview Question:

What happens if your Apex code exceeds Governor Limits?

Answer:

If an Apex transaction exceeds Governor Limits, Salesforce throws a System.LimitException, and the transaction stops immediately. The entire transaction is rolled back, meaning no data changes are committed to the database.

Example error:

System.LimitException: Too many DML statements: 151

Real Production Example

Imagine a trigger that runs on Account updates.

If 200 accounts are updated and the trigger performs:

• SOQL inside loops
• DML inside loops

The code will hit limits quickly.

This can break:

• Data integrations
• User updates
• Automated processes

Proper bulkification and optimized queries prevent these issues.


Final Thoughts

Governor Limits are one of the most important concepts in Salesforce development.

A developer who understands Governor Limits can:

✔ Write scalable Apex code
✔ Avoid runtime exceptions
✔ Build enterprise-level applications
✔ Pass Salesforce developer interviews confidently

Remember:

Good Salesforce developers don’t just write code — they write limit-aware code.


If you master Governor Limits, you move one step closer to becoming a strong Salesforce developer.

Top 25 Governor Limits Interview Questions

1. What are Governor Limits in Salesforce?

Governor Limits are runtime limits enforced by Salesforce on Apex code execution to control how much system resources a single transaction can consume.

Salesforce uses a multi-tenant architecture, meaning multiple organizations share the same infrastructure (CPU, memory, database). To ensure that one organization’s code does not monopolize system resources, Salesforce imposes these limits.

Examples of resources controlled by Governor Limits include:

If a limit is exceeded, Salesforce throws a System.LimitException, and the entire transaction is rolled back.


2. Why does Salesforce use Governor Limits?

Salesforce enforces Governor Limits mainly because of its multi-tenant architecture.

In this architecture:

Without limits, poorly written code from one organization could consume excessive resources and negatively impact other customers.

Governor Limits help ensure:

These limits encourage developers to write optimized and bulkified code.


3. What is the SOQL query limit in Apex?

The maximum number of SOQL queries allowed in a single Apex transaction depends on whether the code is synchronous or asynchronous.

Synchronous Apex

Asynchronous Apex

Synchronous Apex examples:

Asynchronous Apex examples:

This limit prevents excessive database queries that could degrade performance.

Example error when limit is exceeded:

System.LimitException: Too many SOQL queries: 101

4. What is the DML statement limit?

Salesforce allows a maximum of 150 DML statements per transaction.

DML operations include:

If DML operations are executed inside loops, the limit can be reached quickly.

Bad Example:

for(Account acc : accounts){
insert acc;
}

Correct approach:

insert accounts;

Bulk operations help avoid hitting the DML limit.


5. What is the CPU time limit in Apex?

CPU time represents the amount of processing time used by Apex code and related operations.

Limits are:

Synchronous Apex

Asynchronous Apex

CPU time includes:

Heavy loops, complex logic, and nested loops can increase CPU time.


6. What happens when a Governor Limit is exceeded?

When an Apex transaction exceeds a Governor Limit, Salesforce throws a System.LimitException.

Example:

System.LimitException: Too many DML statements: 151

Important characteristics:

This ensures system integrity and prevents partial updates.


7. What is the heap size limit?

Heap size refers to the memory used by variables during Apex execution.

Heap limits:

Synchronous Apex

Asynchronous Apex

Heap size increases when storing:

Example:

Storing very large datasets in lists may exceed heap limits.

Solutions:


8. What is the maximum number of records retrieved by SOQL?

The maximum number of records that can be retrieved using SOQL in a single transaction is 50,000 records.

Example:

SELECT Id FROM Account

If this query returns more than 50,000 records, Salesforce throws a limit exception.

To process large datasets, developers use:

Batch Apex can process millions of records.


9. What is the maximum number of records processed in Batch Apex?

Batch Apex can process millions of records.

This is possible because Batch Apex processes records in smaller batches.

Example:

If batch size = 200

Each batch processes 200 records and receives fresh Governor Limits.

Structure of Batch Apex:

Each execute() call gets its own limits.


10. What is the maximum number of callouts allowed?

Salesforce allows a maximum of 100 callouts per transaction.

Callouts are requests sent to external systems using:

Example:

HttpRequest req = new HttpRequest();

This limit ensures external integrations do not overload the system.


11. What is the difference between synchronous and asynchronous limits?

Asynchronous Apex receives higher limits because it runs in the background.

FeatureSynchronousAsynchronous
SOQL Queries100200
CPU Time10 sec60 sec
Heap Size6 MB12 MB

Asynchronous processing is used for:


12. How can you check Governor Limits in Apex?

Salesforce provides the Limits class to monitor usage.

Example:

System.debug(Limits.getQueries());
System.debug(Limits.getLimitQueries());

Other useful methods:

Limits.getDmlStatements()
Limits.getCpuTime()
Limits.getHeapSize()
Limits.getCallouts()

This helps developers track resource consumption.


13. What are the common types of Governor Limits?

Governor Limits are categorized into several types:

1. Per Transaction Apex Limits

Apply to each Apex transaction.

Examples:

2. Static Apex Limits

Fixed limits that do not change.

Example:

3. Size-Specific Limits

Based on Salesforce edition.

Example:

4. Platform Limits

General platform restrictions.

Example:


14. Why should we avoid SOQL inside loops?

Executing SOQL inside loops can quickly exceed the 100 query limit.

Example:

If 200 records are processed in a loop and each iteration runs a query, it results in 200 SOQL queries, exceeding the limit.

Correct approach:

Use one query outside the loop and store results in collections.


15. Why should we avoid DML inside loops?

DML operations inside loops can exceed the 150 DML statement limit.

Example:

Updating 200 records individually results in 200 DML operations.

Instead, perform a single bulk update.


16. What is bulkification?

Bulkification means writing code that handles multiple records efficiently in a single execution.

Bulkified code:

Triggers must always be bulkified because they can process up to 200 records at once.


17. Which data structures help reduce limits?

Collections improve performance and reduce resource consumption.

Common collections:

List

Stores ordered data.

Set

Stores unique values and prevents duplicates.

Map

Stores key-value pairs for fast lookup.

Maps are especially useful for avoiding nested loops.


18. What is the maximum number of records processed in a trigger?

Salesforce triggers can process up to 200 records in one execution.

Example:

If 500 records are inserted:

Triggers must always be written to handle multiple records.


19. What is the maximum stack depth for recursive triggers?

The maximum recursion depth allowed in Apex is 16 levels.

Recursive triggers happen when a trigger updates a record that fires the same trigger again.

To avoid recursion:

Developers use static variables to control trigger execution.


20. How can we avoid Governor Limits?

Best practices include:

These practices ensure scalable code.


21. Which Apex features help avoid limits?

Salesforce provides asynchronous processing features:

These features allow heavy processing to run in background with higher limits.


22. Why is Batch Apex useful for Governor Limits?

Batch Apex processes data in smaller chunks.

Each batch execution receives fresh Governor Limits, which allows large datasets to be processed without hitting limits.

This makes Batch Apex ideal for:


23. What is the maximum DML rows limit?

A maximum of 10,000 records can be modified using DML operations in one transaction.

Example:

update accounts;

If accounts contain more than 10,000 records, the transaction fails.


24. What is the maximum number of queueable jobs in a transaction?

Salesforce allows a maximum of 50 queueable jobs per transaction.

Queueable Apex is commonly used for:


25. What is a real-world example of hitting Governor Limits?

Example scenario:

A trigger runs on Account updates.

Inside the trigger:

If 200 records are processed, the code will exceed the SOQL limit.

Error:

System.LimitException: Too many SOQL queries: 101

Solution:


Quick Revision Cheat Sheet

LimitValue
SOQL Queries100
DML Statements150
Query Rows50,000
CPU Time10 sec
Heap Size6 MB
Callouts100
DML Rows10,000

Best of Luck


Trusted by 2000+ learners to crack interviews at TCS, Infosys, Wipro, EY, and more.

Want more Real Salesforce Interview Q&As?

For All Job Seekers – 500+ Questions from Top Tech Companies → https://trailheadtitanshub.com/500-real-interview-questions-answers-from-top-tech-companies-ey-infosys-tcs-dell-salesforce-more/

Mega Interview Packs:

 Career Boosters:

Visit us On www.trailheadtitanshub.com

Exit mobile version