How do developers optimize integration payload structures to prevent heap size exhaustion and serialization errors?
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:
- Query narrowly: only the fields the target uses, with filters on
SystemModstampor a flag to send only changed records. - Serialize efficiently:
JSON.serialize(obj, true)suppresses null Apex object fields; use compact wrapper classes instead of full sObjects. - Chunk: send 200 to 1000 records per call, via Batch Apex or paged callouts.
- Compress:
req.setCompressed(true)gzips the request body. - Free memory: set large variables to
nullonce done; checkLimits.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 crosses a threshold, split the batch.