As Salesforce applications grow in complexity and handle larger datasets, Apex Heap Size Limit errors become one of the most common governor limit exceptions developers encounter.
Apex heap size issues occur when a single transaction consumes more memory than Salesforce allocates. These errors are rarely caused by incorrect code. Instead, they typically arise when otherwise valid logic processes large production datasets, broad SOQL queries, complex object structures, or inefficient memory management patterns.
As record volumes increase and production data becomes richer than sandbox data, even minor inefficiencies in querying, storing, or serializing data can quickly accumulate and exceed Salesforce’s strict heap limits, resulting in immediate runtime failures.
Salesforce Apex Heap Size Limits
Salesforce enforces the following heap size limits:
- 6 MB for Synchronous Apex
- 12 MB for Asynchronous Apex
When these limits are exceeded, the transaction fails immediately.
Heap size issues generally occur when too much data is stored in memory during a single transaction.
Common Causes of Apex Heap Size Errors
- Querying unnecessary fields
- Large SObject collections
- Heavy wrapper classes
- JSON serialization of full objects
- Passing large datasets into asynchronous jobs
- Static variables holding unnecessary data
Let’s look at some common scenarios and their solutions.
1. SOQL Query Design Problem
Querying unnecessary fields significantly increases heap usage.
apex id="q1"
SELECT Id, Subject, Description, Internal_Notes_c
FROM Case
Even if only the Subject field is required, querying every field loads the complete record into memory.
Solution
Query only the fields your logic actually uses.
apex id="q2"
SELECT Id, Subject
FROM Case
2. Large Collections Problem
Storing complete SObjects inside Maps or Collections consumes a large amount of memory.
apex id="q3"
Map<id, Account> accountMap = new Map<Id, Account>(accounts);
This stores every field of the Account object, increasing heap usage unnecessarily.
Solution
Store only the values you actually need.
apex id="q4"
Map<Id, String> accountNameMap = new Map<Id, String>();
for(Account acc : accounts){
accountNameMap.put(acc.Id, acc.Name);
}
3. Wrapper Classes Problem
Wrapper classes that contain full SObjects can quickly consume heap space, especially when processing thousands of records.
apex id="q5"
public class OppWrapper {
public Opportunity opp;
public Account acc;
public List<Task> tasks;
}
This approach becomes expensive with large datasets.
Solution
Use lightweight wrapper structures and load additional data only when necessary.
apx id="q6"
public class OppWrapper{
public Id oppId;
public String oppName;
public String accountName;
}
4. Async Apex Serialization Problem
Passing complete SObjects into Queueable Apex increases serialization overhead.
System.enqueueJob(new JobProcessor(opportunityList);
Solution
Pass only record IDs to asynchronous jobs.
Set<Id> oppIds = new Set<Id>();
for(Opportunity opp : opportunityList){
oppIds.add(opp.Id):
}
System.enqueueJob(new JobProcessor(oppIds);
Re-query the required records inside the Queueable class instead of serializing the entire object.
5. JSON Serialization Problem
Serializing full SObjects duplicates memory.
String payload = JSON.serialize(leadRecord);
This keeps both:
- SObject in memory
- Serialized JSON string
Solution
Use lightweight DTO (Data Transfer Object) classes instead of serializing full SObjects.
public class LeadDTO {
public String firstName;
public String lastName;
public String email;
public String company;
}
Lead l = [SELECT FirstName, LastName, Email, Company FROM Lead WHERE Id = :leadId];
LeadDTO dto = new LeadDTO();
dto.firstName = l.FirstName;
dto.lastName = l.LastName;
dto.email = l.Email;
dto.company = l.Company;
String payload = JSON.serialize(dto);
6. Static Variables Problem
Large static variables remain in memory throughout the transaction and can significantly increase heap consumption.
public static List<Account> processedAccounts = new List<Account>();
Solution
Use static variables only for flags or small utility values, and clear them whenever possible after use.
processedAccounts.clear();
processedAccounts = null;
Best Practices for Managing Apex Heap Size
To build scalable and memory-efficient Apex applications, follow these best practices:
- Query only the required fields in SOQL.
- Avoid storing unnecessary SObjects in collections.
- Use lightweight wrapper classes or DTOs.
- Pass record IDs instead of entire objects to asynchronous Apex.
- Avoid serializing complete SObjects when not required.
- Keep static variables minimal and clear them after use.
- Process large datasets using Batch Apex where appropriate.
- Monitor heap usage during development using debug logs.
Conclusion
Apex heap size errors are not random failures – they occur when a transaction consumes more memory than Salesforce allows.
By designing your Apex code to retrieve only the required data, using lightweight data structures, minimizing serialization, and carefully managing memory throughout each transaction, you can build applications that are scalable, efficient, and production-ready.
Effective heap size management is a fundamental Salesforce best practice that not only helps avoid governor limit exceptions but also improves application performance, maintainability, and reliability as your data continues to grow.
By following the above blog instructions, you will be able to learn “How to Manage Apex Heap Size in Salesforce and Avoid Heap Size Limit Errors“. If you still have queries or any related problems, don’t hesitate to contact us at salesforce@greytrix.com. More details about our integration product are available on our website and Salesforce AppExchange.
We hope you may find this blog resourceful and helpful. However, if you still have concerns and need more help, please contact us at salesforce@greytrix.com.
About Us
Greytrix – a globally recognized and one of the oldest Sage Development Partner and a Salesforce Product development partner offers a wide variety of integration products and services to the end users as well as to the Partners and Sage PSG across the globe. We offer Consultation, Configuration, Training and support services in out-of-the-box functionality as well as customizations to incorporate custom business rules and functionalities that require apex code incorporation into the Salesforce platform.
Greytrix has some unique solutions for Cloud CRM such as Salesforce Sage integration for Sage X3, Sage 100 and Sage 300 (Sage Accpac). We also offer best-in-class Cloud CRM Salesforce customization and development services along with services such as Salesforce Data Migration, Integrated App development, Custom App development and Technical Support business partners and end users. Salesforce Cloud CRM integration offered by Greytrix works with Lightning web components and supports standard opportunity workflow. Greytrix GUMU™ integration for Sage ERP – Salesforce is a 5-star rated app listed on Salesforce AppExchange.
The GUMU™ Cloud framework by Greytrix forms the backbone of cloud integrations that are managed in real-time for processing and execution of application programs at the click of a button.
For more information on our Salesforce products and services, contact us at salesforce@greytrix.com. We will be glad to assist you.