Improving Session Performance in Rails

Ruby on Rails includes some options for handling sessions (see overview by Stefan Kaes (PDF)). Unfortunately the default ActiveRecord session handler is relatively slow which may have a big impact on your application (sessions tend to accumulate quickly). Fortunately for all of us, Stefan has created an alternative MySQL session handler whith hard coded SQL statements. His version is much quicker.

If your application uses the standard session handler there is really no reason not to implement Stefan’s solution. However, to make it work with the default session table created by Rails 1.1.2 you have to do some minor modifications (at least in version 0.2):

  1. Download and install Stefan’s session handler files into your application’s lib directory.
  2. If you haven’t created the session table for your application, run “rake create_sessions_table”. The will add a new migration file in the db/migrate folder.
  3. Update the migration file to make sure the created_at column is included. You can append it by adding “t.column :created_at, :datetime”.
  4. Open lib/sql_session_store.rb and modify the SQL statements containing a reference to the sessid column. In Rails 1.1.2 this should be called “session_id”.
  5. Update your config/environment.rb by appending the following lines at the end of the file:
cmVxdWlyZSAnc3FsX3Nlc3Npb25fc3RvcmUnDQpyZXF1aXJlICdteXNxbF9zZXNzaW9uJw0KQWN0aW9uQ29udHJvbGxlcjo6Q2dpUmVxdWVzdDo6REVGQVVMVF9TRVNTSU9OX09QVElPTlMudXBkYXRlKDpkYXRhYmFzZV9tYW5hZ2VyID0+IFNRTFNlc3Npb25TdG9yZSkNClNRTFNlc3Npb25TdG9yZS5zZXNzaW9uX2NsYXNzID0gTXlzcWxTZXNzaW9u

Restart your web server and you have improved session performance a lot. For more details see:

Related Posts:

  • No Related Posts
  • Don Barlow

    In addition to the sql_session_store.rb file, I also had to modify statements referring to the sessid column in the mysql_session.rb file. I am somewhat of a newbie and I got stuck on this one for a while.