@brunofuster

www.wesaveapp.com

Archive for the ‘redis’ Category

scaling sessions properly on express

leave a comment »

When using sessions on Express you should be careful. The default behavior with app.use(express.session()) is to save the session on any response even if you don’t need it.

From ExpressJS docs:

Properties on req.session are automatically saved on a response

First of all: Redis

Instead of using the default in-memory implementation from Connect, you should start by using a distributable in-memory storage like Redis.

Redis To Go has a free 5MB plan if you want to get started on the cloud.

$ npm install connect-redis

var RedisStore = require('connect-redis')(express)
  , session_store = new RedisStore({host: 'redistogo.com', port: 6379, pass: 'password', prefix: 'appsess:'});

var session = function() {
  return express.session({ store: session_store, secret: 'salt' });
}


Default but wrong usage

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(session());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

Now use apache bench to stress test your unlogged home page:
$ ab -r -n 5000 -c 50 http://127.0.0.1/

Redis should now have 5000 leaked keys waiting for its expiration, consuming huge amount of unnecessary memory.



Per-request session: the real deal

Just load and save the session object when you really need!

Remove app.use(session()) from app.configure!

//without session
app.get('/', function(req,res) {}); 

//with session
app.get('/admin', session(), function(req, res) {});

Delete all Redis keys.
Run the apache bench command again and check your Redis memory totally unused.

Advertisements

Written by brunofuster

June 21, 2012 at 6:56 pm

Posted in cloud, expressjs, redis