Why This Error Occurs
Salesforce sets limits on how much memory Apex code can use:
- 6 MB for synchronous transactions
- 12 MB for asynchronous transactions (Batch, Queueable, Future)
If your code holds more than this amount of data in memory at any point, Salesforce stops it to protect system performance.
Common causes include:
- Too many records queried without limits
- SOQL inside loops storing large collections
- Deserializing entire JSON responses unnecessarily
- Processing huge file or blob data without streaming
How to Fix the Apex Heap Size Limit Error
Limit Data Returned by SOQL
Only query fields you actually need:
Instead of:
SELECT * FROM Account
Use:
SELECT Id, Name FROM Account
This reduces memory use.
Avoid Storing Unnecessary Records
If you only need record IDs or specific fields:
- Store only those fields in a Set or small list
- Don’t keep full records in memory when not needed
Move Heavy Logic to Asynchronous Processing
When working with large sets of records:
- Use Batch Apex
- Use Queueable Apex
These split processing into smaller transactions with larger limits.
Clear Variables After Use
After processing large lists or maps, set them to null so Salesforce can free up memory.
Example:
largeList = null;
Optimize JSON Handling
If your integration returns large JSON:
- Parse only the keys you need
- Avoid deserializing entire payloads unnecessarily