Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the advantage of using non-connect default session store?

For express applications, I've seen that there's a connect-mongodb and connect-redis middleware for storing sessions, but I don't understand why that's necessary - what's wrong with the default in-memory session storage? Is it for large scale applications that need to sync sessions across multiple machines?

Also, can anyone offer any benchmarks/tips for the fastest session store? My guess is Redis due to its simpler key/value store.

like image 917
badunk Avatar asked May 06 '12 01:05

badunk


1 Answers

The only reason to store session data in a database (MongoDB, Redis, etc) is so that it is available across Node processes and is durable across failures. In scale out architectures, it is highly desirable to have stateless servers so that everything works regardless of which server a particular user connects to and servers can go up and down without losing any state.

In other words, imagine you have 10 servers behind a load balancer handling incoming requests. User 1 makes a request that Server A handles and logs in. You need to store the fact that they've logged in so you store this in a session. The next request ends up getting routed to Server C since Server A is busy with another request. In order for Server C to know that the user has already logged in, it needs the session data. So how does it get access to the session data that was stored by Server A?

One way is by storing the data in a cookie on the client side which is submitted with each request, but this isn't very secure. Another way is to try and sync state across Node servers which can be done but tends to be costly and error prone. The easiest way is to store a session ID in a cookie and then store the actual session data in a database. Each node server then has access to the same database so they can look up the session data. This way you can easily scale in and out your Node servers and load balance them when servers fail without losing any data.

In terms of performance, the in memory store will be the fastest (but has the drawbacks above). Redis will be the next fastest and MongoDB will be the slowest (generally about 4x slower than Redis). Keep in mind that either will be plenty fast enough for the vast majority of web sites.

like image 200
Bill Avatar answered Nov 09 '22 04:11

Bill