Search code examples
node.jsexpresssessionconcurrencysession-store

Express-session - Concurrent modifications on session


I'm implementing a session-based services using expressjs and express-session with the redis-connect store in nodejs and I have a problem with the concurrent modifications on session storage. Find following an example of the problem:

  • Two routes published: /api/op1 and /api/op2
  • /api/op1: Increment the value of request.session.op1Calls and performs calls to external services (3 seconds)
  • /api/op2: Increment the value of request.session.op2Calls and just do nothing (0.1 ms to be executed)

The problem here is: If I execute the op2 several times during the execution of op1, the request.session.op2Calls value is just lost. How should I implement the session store to never lose the values?

Thanks!


Solution

  • Express session ( request.session ) is being read from the store ( in your case redis store ) at the moment the request was made.

    Having the request doing the task and then modify the session and save it back to the store will actually save the already read session enriched with the updated properties.

    What you can do to mitigate this is to have the session reloaded before save :

    app.get( "/op2", function( req, res, next ) {
       someReallyLongAsyncTask( function() {
           req.session.reload(function(err) {    
               if ( !req.session.op2Call ) { req.session.op2Call = 0; }
               req.session.op2Call++;
               req.session.save( function() { 
                   res.json( { success: true } )
               } );
           } );
       } );    
    } );
    

    This way you will make sure that the session is re-read before being saved.