Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MemoryStore in production

Tags:

node.js

Ok, after talking to Connect developers, I got more information. There are two things considered memory leaks here:

  1. problem with JSON parsing which is already fixed in recent versions
  2. the fact that there is no cleanup of expired sessions if the users never access them (i.e. the only cleanup is on-access)

The solution seems to be rather simple, at least this is what I plan to do: use setInterval to periodically clean up the expired sessions. MemoryStore provides all() to get the list, and we can use get() to force reading and thus expire them. Pseudo-code:

function sessionCleanup() {
    sessionStore.all(function(err, sessions) {
        for (var i = 0; i < sessions.length; i++) {
            sessionStore.get(sessions[i], function() {} );
        }
    });
}

Now just call sessionCleanup periodically via setInterval() and you have automatic garbage collection for expired sessions. No more memory leaks.


So the accepted answer to this is [edit: was] pretty much a hack, and the others are just recommending using a database which I think is overkill.

I had the same problem and just replaced express-session with cookie-session.

To do this simply install cookie-session:

npm install cookie-session

Then in your app.js, find where express-session is being used and replace with cookie-session.

app.use(require('cookie-session')({
    // Cookie config, take a look at the docs...
}));

You may need to change some other things, for me is was a simple swap-out-bobs-your-uncle-no-harm-done.


MemoryStore is just for (rapid) development mode, because if your app restarts (process dies) you will lose all the session data (that resided in the memory of that process).

If you don't want to use a database, use encrypted cookie storage instead.

http://www.senchalabs.org/connect/cookieSession.html


This module was designed to deal with the memory leak issue. https://www.npmjs.com/package/session-memory-store

The accepted answer may be fine. However, since this question shows up high in the list of search results I figured I would include this in case it helps anyone else.