We have a batchable Apex where we read two CSV attachments on a custom object and we perform various operations on Accounts and Addresses that the CSV contain. The problem is when the files are a bit large (1,61 MB and 872 KB so total approximately 2MB) we get error related to Heap Size Exceeded. The problem is that the only thing that is being performed synchronously is the reading of content. All the other processes are being performed asynchronously.

I have not understood this error and how i could overcome it. Any ideas?

  • 2
    I suggest you post the piece of code where you read the attachments. You should definitely only read one per transaction. But even if you read a single attachment and then split it up into individual lines, you are already consuming 2x the size - 1x for the attachment text and 1x for the text broken up into lines. And the limit for synchrnonous requests is 6M.
    – Keith C
    Dec 1 '19 at 9:47
  • Without seeing your code, best generic advice would be to use the transient keyword on the variables used to parse your CSV files. Those variables can't be saved and presumably would reduce the heap used. That's the general technique one would use in a VisualForce page. If that doesn't help, you'll need to post code.
    – crmprogdev
    Dec 1 '19 at 17:09

If you are in a batch asynchronous context when parsing the CSV files then you total heap size of 12 MB applies.

That should be more than enough to load in the approximately 2.5 MB of raw CSV data and then process it. You would be looking at about 5 MB of Heap usage all up, not including the Account and Address records you wanted to process.

You mentioned that the CSV files are stored against a custom object.

Is your batch job iterating over a collection of these custom objects? If so, that could easily cause issues with the Heap size as each batch iteration would contain multiple custom objects and their associated CSVs. If this is the case, try reducing the batch scope to 1 - See executeBatch(batchClassObject, scope).

You could also actively investigate the Heap usage in your Apex classes. Try debugging out Limits.getHeapSize() in your Apex code. The developer console will also show up heap usage details in the Log Inspector.

Not the answer you're looking for? Browse other questions tagged or ask your own question.