# How do you prevent heap size limit exceptions when processing large payloads in Batch Apex execute chunks?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Batch Apex

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. Reduce scope size so each chunk holds fewer records.
2. Query only the required fields (avoid long text and blobs unless needed).
3. Process records, then clear or reassign large variables.
4. 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:**
```apex
public void execute(Database.BatchableContext bc, List<Document__c> scope) {
    for (Document__c d : scope) {
        processOne(d);
        d.Body__c = null; // release a large field once done
        if (Limits.getHeapSize() > Limits.getLimitHeapSize() * 0.8) {
            System.debug(LoggingLevel.WARN, 'Heap above 80 percent, consider a smaller scope');
        }
    }
    update scope;
}
```

**Hidden gotchas & must-remember points:**
- Async heap is 12 MB; sync is 6 MB.
- Heap errors are uncatchable and roll back the whole chunk.
- `Map<String,Object>` JSON parsing costs more heap than typed classes.
- Stateful collections accumulate across chunks.
- Long text areas and blobs can dominate memory even for small scopes.
- A failing chunk does not stop other chunks, so reduce scope and rerun.

**Best practice:** Treat heap as a budget: lean queries, small scopes, no unbounded Stateful state.

---
Source: ForceChallenges · last updated 2026-11-02
