Governor Limits & Performance Tuning

Share

Apex Governor Limits (Why They Exist)

What Are Governor Limits?

Governor limits are Salesforce-enforced rules that restrict how much system resources Apex code can use in a single transaction.

Simple Explanation

Governor limits are like speed limits on a highway—they keep everyone safe and ensure one driver doesn’t block others.

Salesforce is multi-tenant, so limits protect:

  • Platform performance

  • Data integrity

  • All customers using Salesforce


Common Governor Limits (High Level)

  • Number of SOQL queries

  • Number of DML statements

  • CPU time

  • Heap size (memory)


Real-Life Example

If one company runs a huge report without limits, it could slow down Salesforce for everyone. Governor limits prevent that.


Gist (Quick Revision)

Governor limits protect Salesforce performance and force developers to write efficient code.


CPU Time, Heap Size & Query Limits

CPU Time Limit

CPU time is the amount of processing time Apex can use.

  • Sync Apex → ~10 seconds

  • Async Apex → higher limit

Bad Example (Inefficient Logic)

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

Heap Size Limit

Heap size is the memory Apex uses to store variables and objects.

Bad Practice

  • Storing large objects unnecessarily

  • Holding data longer than needed

List<Account> accounts = [SELECT * FROM Account]; // bad

SOQL Query Limit

You can run only a limited number of SOQL queries per transaction.

❌ Bad (SOQL inside loop)

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

✅ Good (Single query)

Map<Id, Contact> contactMap = new Map<Id, Contact>(
    [SELECT Id, AccountId FROM Contact WHERE AccountId IN :accountIds]
);

Easy Memory Rule

CPU = Time, Heap = Memory, SOQL = Queries


Gist (Quick Revision)

Avoid heavy logic, large memory usage, and repeated queries to stay within limits.


Bulk Data Processing Strategies

What Is Bulk Processing?

Bulk processing means handling many records at once safely and efficiently.

Why It Matters

Salesforce often processes up to 200 records in a single transaction.


Strategy 1: Always Assume Multiple Records

for(Account acc : Trigger.new){
    // logic must support many records
}

Strategy 2: Use Collections

  • List → store records

  • Set → collect unique IDs

  • Map → fast lookup

Set<Id> accountIds = new Set<Id>();

Strategy 3: One SOQL, One DML

  • Query all data at once

  • Perform DML outside loops

insert accountList;

Strategy 4: Use Async Apex for Heavy Work

  • Queueable

  • Batch

  • Future methods


Real-Life Example

Instead of processing each invoice separately, process all invoices together.


Gist (Quick Revision)

Bulk-safe code uses collections, avoids loops with SOQL/DML, and scales efficiently.

  • January 6, 2026