Memory leak with nodejs

1.2k views Asked by At

I load my calendar from google. But every time I do it, node uses 2 mb more memory. Even if I delete the module. I need to load it every 5 or 10 min so I can see if there are changes. this is my code.

google-calender.js module

module.exports = {

  loadCalendars: function(acces, res){
    gcal = require('google-calendar');
    google_calendar = new gcal.GoogleCalendar(acces);

    google_calendar.calendarList.list(function(err, calendarList) {

        toLoadCalenders = calendarList.items.length;
        loaded = 0;
        data = [];

        for(var i = 0; i < toLoadCalenders; i++){           
            google_calendar.events.list(calendarList.items[i].id, function(err, calendarList) {
                loaded++;
                data.push(calendarList);
                if (loaded == toLoadCalenders) {
                    res.send(data);
                }
            });

        }

    });
  }
}

main.js

app.get('/google-calender', function (req, res) {
    google = require('./google-calender');
    google.loadCalendars(acces, res);

    setTimeout(function(){
        delete google;
    },500);
});

Does anyone know how I can prevent memory leak here?

1

There are 1 answers

0
Abdullah Shahin On BEST ANSWER

Well, memory leak topic is kind a tough area for any developer, first of all you need to know if you have a memory leak or not, I recommend using node inspector and do the following:

1- run your node app with node-inspector on.

2- take a heap snapshot on fresh start so you can know the initial memory size been used by your app.

3- do some requests, you may use some benchmarking tool, meanwhile take a second snapshot.

4- compare snapshot number one with snapshot number 2, detect where the increasing happening, then note that.

5- stop making requests and wait a little bit so we make sure garbage collector has finished its work then take third snapshot.

6- compare the size of snapshot 3 with snapshot 2, you may see that snapshot 3 has freed size more than snapshot 2.

You may do this test many times, if always the last snapshot has increasing memory allocation than its predecessors snapshots, then you may have a memory leak.

How to fix memory leak ?

well, you need to be familiar with cases in javascript where memory leaks happen, you can read this article and match similar cases in your code. then you can read the details of snapshot tries you had and match the linearly increasing part, and figure out where in your code you have such data types or arrays, objects or even module codes that been repeatedly required and never disposed.

Actually for coincidence, we had such case today and we had to go through this troubleshooting steps to get our hands on the problem.

Good luck my friend.