Apex heap limit differences between synchronous and asynchronous transactions
20.5K reputation · 19 Mar 2022, 16:45 UTC
Heap sizing for bulk Apex
A design is being evaluated for bulk processing that keeps data in memory during an Apex transaction. The documented capability is the Apex heap size governor limit, which caps in-memory data per transaction and is enforced separately for synchronous and asynchronous contexts. Heap usage is measured per transaction and includes variables, collections and deserialized sObjects, with memory reclaimed only at transaction end and no developer-exposed compaction or garbage collection control.
There is uncertainty about exact current limits and how heap is accounted for with large collections and JSON deserialization. Platform Cache and external data access do not directly increase Apex heap, but data retrieved into Apex variables does count toward the limit. Static variables are scoped per transaction and do not persist heap across invocations.
What is the documented heap size limit for synchronous Apex versus asynchronous Apex such as Queueable and Batch execute in the current release? How is heap accounted for when a large JSON payload is deserialized into a List of sObjects held for the duration of the transaction? Does retrieving data from Platform Cache increase Apex heap only when the data is copied into Apex variables?