# How do developers optimize integration payload structures to prevent heap size exhaustion and serialization errors?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Payload Optimization, Heap Size Limits

Read it on the site: https://www.forcechallenges.com/interview-questions/how-do-developers-optimize-integration-payload-structures-to-prevent-heap-size-exhaustion-and-serialization

## Answer

**Basics:** Heap is the memory your Apex transaction uses. A callout request and response body, plus the parsed objects built from them, all count. A big JSON array parsed into maps and lists can use many times its raw size, which is where "Apex heap size too large" errors come from.

**How it works:**
1. Query narrowly: only the fields the target uses, with filters on `SystemModstamp` or a flag to send only changed records.
2. Serialize efficiently: `JSON.serialize(obj, true)` suppresses null Apex object fields; use compact wrapper classes instead of full sObjects.
3. Chunk: send 200 to 1000 records per call, via Batch Apex or paged callouts.
4. Compress: `req.setCompressed(true)` gzips the request body.
5. Free memory: set large variables to `null` once done; check `Limits.getHeapSize()`.

**Advanced / deep dive:** On the inbound side prefer `JSON.deserialize` into typed classes over `deserializeUntyped` (maps of objects cost more). For very large responses use `JSONParser` (streaming tokens) or request paging (`limit`/`offset`, cursor tokens, REST `nextRecordsUrl` with default 2,000-row batches). Asynchronous contexts double heap to 12 MB, so move heavy parsing into Queueable or Batch. For genuinely large data movement skip Apex altogether: use Bulk API 2.0, Change Data Capture with middleware, or Salesforce Connect. Delta design: use CDC events (which carry only changed fields) rather than re-sending entire records. Beware serialization errors: sObjects with relationship subqueries nest deeply, circular references fail, and some types (for example `Blob`) are large when Base64-encoded. Add a payload-size guard: if `Blob.valueOf(body).size()` crosses a threshold, split the batch.

**Code / config example:**
```apex
List<Slim> slim = new List<Slim>();
for (Account a : [SELECT Id, Name FROM Account WHERE SystemModstamp > :lastSync LIMIT 500]) {
    slim.add(new Slim(a.Id, a.Name));               // only what the target needs
}
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Target/accounts');
req.setMethod('POST');
req.setCompressed(true);                             // gzip request body
req.setBody(JSON.serialize(slim, true));             // suppress null fields
slim = null;                                         // release heap
```

**Hidden gotchas & must-remember points:**
- Heap counts the raw string and each parsed structure at once.
- Sync heap 6 MB, async 12 MB; the limit is per transaction, not per variable.
- Not all servers accept gzip requests; compression of responses depends on the server.
- Deltas need a reliable watermark; `LastModifiedDate` ties can lose rows, so prefer `SystemModstamp` plus an Id tiebreak.
- Pagination loops in one transaction still accumulate heap.

**Best practice:** Design payloads as small, versioned contracts and move volume to Bulk API or async chunks.

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