How can I recreate a 'heap limit Allocation failed' error?

Viewed 34

Background

I was getting FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory

It was happening around 512 mb

Scavenge (reduce) 507.8 (518.9) -> 507.2 (518.9) MB, 2.4 / 0.0 ms

I believe a heap out of memory error should happen at 1024mb, not 512mb, because I'm running my program on a heroku dyno with 1gb (1024mb).

I made some changes to my app to try to fix this.

Question

I want recreate a situation where over 512mb of ram are used up. This way I can see if my changes fixed the problem. Or if my app still crashes.

How would one go about this?

I Tried

I tried creating a route that adds 1000mb buffers to a global array. But this took the heap used down by about 1mb. I would think it would take 3000mb out of the heap on each request. But maybe those buffers aren't store in the heap?

const crashArray =[];
  someRoute.get('/', async (req, res, next) => {

    console.log(process.memoryUsage().heapUsed);
    // returns> 52848344    

    const a = Buffer.alloc(1000000000);
    const b = Buffer.alloc(1000000000);
    const c = Buffer.alloc(1000000000);
    crashArray.push(a);

    console.log('after adding buffer to arrays' + process.memoryUsage().heapUsed);
    // returns> 51684512    
 
    res.send(200);
  });

1 Answers
  1. create a route like this
  const arr = [];
  app.get('/1', (req, res, next) => {
    arr.push(...Array(0.12e6).fill('some string'));


    // logs memory info
    const used = process.memoryUsage();
    console.log('');
    console.log('request');
    for (const key in used) {
      console.log(`${key} ${Math.round((used[key] / 1024 / 1024) * 100) / 100} MB`);
    }
    console.log('');



    res.send(200);
  });

Note: If you get Maximum call stack size exceeded error, lower the number 1.2e6.

  1. Open a browser to the the url, domain.com/1 or whatever your domain is. Then go to this url a bunch of times. Just keep refreshing like 200 times really fast. Eventually it gives you the error

This only worked in production on my heroku dyno. Maybe because the local machine high a really has memory limit?

Related