How do you prevent heap size limit exceptions when processing large payloads in Batch Apex execute chunks?
Answer
Basics: Heap is the memory your Apex variables occupy in one transaction. Async transactions get 12 MB (sync 6 MB). Large JSON payloads, big lists of sObjects with long text fields, and bloated Stateful state are the typical causes of "Apex heap size too large".
How it works:
- Reduce scope size so each chunk holds fewer records.
- Query only the required fields (avoid long text and blobs unless needed).
- Process records, then clear or reassign large variables.
- Log
Limits.getHeapSize()to find the peak.
Advanced / deep dive: For callout responses, request pages of manageable size instead of one giant payload; deserialize into a lean typed class rather than Map<String,Object>, which keeps much more overhead; handle one page per job or per execute() and chain. Use SOQL for loops (for (List<Account> chunk : [SELECT ...])) so records are retrieved in batches of 200 instead of loading the whole result at once. Avoid holding both the original list and transformed copies; update in place. Strings and collections count by their content size, so building one huge concatenated string or JSON is risky; stream into chunks or Blob/ContentVersion pieces. Heap exceptions are uncatchable and fail the entire chunk, so prevention matters. If a record legitimately needs heavy processing, use a scope of 1 to 10.
Code / config example:
public void execute(Database.BatchableContext bc, List<Document__c> scope) {
for (Document__c d : scope) {
processOne(d);
d.Body__c = ;
(Limits.getHeapSize() > Limits.getLimitHeapSize() * ) {
System.debug(LoggingLevel.WARN, );
}
}
update scope;
}