Running garbage collection manually in node

后端 未结 3 550
感情败类
感情败类 2020-12-15 08:33

I am using node and am considering manually running garbage collection in node. Is there any drawbacks on this? The reason I am doing this is that it looks like node is not

3条回答
  •  半阙折子戏
    2020-12-15 09:28

    I actually had the same problem running node on heroku with 1GB instances.

    When running the node server on production traffic, the memory would grow constantly until it exceeded the memory limit, which caused it to run slowly.

    This is probably caused by the app generating a lot of garbage, it mostly serves JSON API responses. But it wasn't a memory leak, just uncollected garbage.

    It seems that node doesn't prioritize doing enough garbage collections on old object space for my app, so memory would constantly grow.

    Running global.gc() manually (enabled with node --expose_gc) would reduce memory usage by 50MB every time and would pause the app for about 400ms.

    What I ended up doing is running gc manually on a randomized schedule (so that heroku instances wouldn't do GC all at once). This decreased the memory usage and stopped the memory quota exceeded errors.

    A simplified version would be something like this:

    function scheduleGc() {
      if (!global.gc) {
        console.log('Garbage collection is not exposed');
        return;
      }
    
      // schedule next gc within a random interval (e.g. 15-45 minutes)
      // tweak this based on your app's memory usage
      var nextMinutes = Math.random() * 30 + 15;
    
      setTimeout(function(){
        global.gc();
        console.log('Manual gc', process.memoryUsage());
        scheduleGc();
      }, nextMinutes * 60 * 1000);
    }
    
    // call this in the startup script of your app (once per process)
    scheduleGc();
    

    You need to run your app with garbage collection exposed:

    node --expose_gc app.js
    

提交回复
热议问题