Tuesday, October 02, 2007

Session less rails application

Sessions are used to store user login information on the server because http is a stateless protocol and need either sessions or cookies to know pass data between user's subsequent page requests. However there has been a lot of talk and benchmarks which show that sessions are one of the things that slow down rails applications rather dramatically. It is also one of the key bottlenecks which with many other factors turns itself into a scalability nightmare.
File session stores are slow and when no. of servers are more than one you cannot easily make use of them without using something like NFS or load balancer hack. DB session store though are easily scalable when more than one servers are used are still quiet slow and moreover it would just become as unscable as no. of users and applications increase as the number of inserts and selects from DB will grow tremendously. Drb sessions store ...well nobody seems to use them :)

I decided to completely do away with sessions and use only cookies in my rails application. My application cookie is made up of various user params which are stored in a pipe seperated string and then Rijndael encryption encrypted using a key. Aes is quiet fast and there is a library for ruby which is a actually a wrapper on top of a C lib so it is quiet fast(feels fast enough...haven't done any benchmarks on it).
Now everytime my application needs to check for authentication it reads the cookie, decrypts it (after base decoding and url unescaping) and makes a user object of a user class using this decrypted info and thats it. Bye bye sessions :)

p.s. As for error/flash messages ...well thats a different story. If you want to disobey rails and do things your way, a lot of magic powers are rendered useless but it's not as if there are no ways to get around the problem.

p.p.s. This system was conceptualized by Saurabh Nanda who based it on Standford's WebAuth and JA-SIG CAS