Search code examples
redissession-storage

Redis for session storage


I am building a security service as part of a suite of services that make up an application. I am considering using Redis to store sessions. A session is a data structure that looks like this:

{
   string   : sessionToken
   DateTime : expiryUtc
   string[] : permissionKeys
}

All I need to do is create, read and remove sessions. If I can have Redis remove expired sessions then great but not essential. As a noob to Redis I have some reading to do but can someone with Redis experience give me any guidance on the correct way to achieve this, assuming Redis is a good choice. BTW I'm on the Mono platform and have so far selected StackExchange.Redis client as at some stage I will want to cluster Redis. I am open to changing this selection.


Solution

  • You can go with Redis hashes, they will match your structure pretty well: http://redis.io/topics/data-types-intro#redis-hashes
    The session token can be the key of the whole hash. The StackExchange Redis client has a KeyExpire method which can take a DateTime parameter, so you can have Redis expire your keys.
    Inside Redis hashes you can't have nested structures so your permissionKeys and any other values that will go inside must be stored as simple values - you can serialize them as json.
    And one more thing with hashes is that they allow for some memory optimization: http://redis.io/topics/memory-optimization#use-hashes-when-possible which can be pretty usefull if you will have many sessions to create (because Redis will store all these in ram).