Troubleshooting Apex heap size

Salesforce enforces an Apex Heap Size Limit of 6MB for synchronous transactions and 12MB for asynchronous transactions and this is a governor limit which means it is a hard limit and cannot be modified or relaxed.

The “Apex heap size too large” error occurs when too much data is being stored in memory during processing. The limit depends on the type of execution (E.g., synchronous vs asynchronous calls) and current value. 

Best practices for running within the Apex heap size,

  • Don’t use class level variables to store a large amount of data.
  • Utilize SOQL For Loops to iterate and process data from large queries.
  • Construct methods and loops that allow variables to go out of scope as soon as they are no longer needed.


In order to resolve Heap size error issue, you need to revamp the code following the above best practices so that you don’t hit these limits.

Please refer to the following link which discusses different strategies to manage the heap size.

Troubleshooting approach to fix heap size error,

1) Add the following debug method to the affected class:

void checkHeapSize(String tag) {
system.debug(tag + ': Heap size is ' + limits.getHeapSize() + ' enforced is ' + limits.getLimitHeapSize());

2a) Call the method at various points in the code using a “tag” parameter so that you know where it’s called in the code. For example: checkHeapSize(‘constructor1’);

2b) In order to check the heap limit, put the check in the loop and then run the check every 1000th iteration. This is done by adding a local variable called “i” (i.e. “integer i;”), increment it for each iteration, and then running the following code:

if (math.mod(i, 1000) == 0) } { call the method }.

3) Review the debug logs to find the heap size to see if it’s exceeding the limit. For issues with scheduled batches, testing in the Developer Console will run code synchronously and show the limit as 6 MB but the heap size limit for scheduled batches is the asynchronous limit of 12MB.

4) If heap size doesn’t exceed the limit, repeat steps 1-3. If the limit is exceeded, the debug logs should point out the problematic section of code that will need to be fixed.

Credit: Sweta (Her profile is not available anymore – 404 error)

Leave a Comment