This site is dedicated to further knowledge about creating Ruby on Rails applications professionaly. We discuss Ruby on Rails features from a performance angle, discuss Ruby on Rails performance analysis methods, provide information on Ruby on Rails scaling and benchmark Ruby on Rails performance for each release. We discuss best practices for selecting Ruby on Rails session containers, fragment and page caching and optimizing database queries.

Roll your own SQL session store

Posted 19 Dec 2005

The alert reader may have noticed that I'm using my own SQL session store, which provides much better performance than the default ActiveRecordStore shipping with Rails.

I have decided to publish the source code here. If you are using Mysql, simply unpack the files into your lib directory and make SQLSessionStore your session storage.

require 'sql_session_store'
require 'mysql_session'
    update(:database_manager => SQLSessionStore)
SQLSessionStore.session_class = MysqlSession
If you're using components, which you probably shouldn't, you'll need to activate eager session saving:
MysqlSession.eager_session_creation = true

The improved performance is due to a number of factors:

  • fixed number of known DB columns
  • retrieve only fields into the session that are actually used to create the session for a controller
  • offloading most of the work to the DB, including updating the created_at and updated_at fields
  • hard coded Mysql statements

As a consequence, if you want another DB, other DB column names, don't want created_at or updated_at fields, you'll have to change the code.

I have uploaded HTML representations of the call trees for ActiveRecordStore and SQLSessionStore. If you inspect them closely, you'll see how much time ActiveRecordStore spends in just creating the SQL statements and how much simpler the call tree is for SQLSessionStore.

If you adapt the provided code for other database systems, I'd be happy if you sent me the code, and I'll add it to the download after reviewing. The required changes are probably pretty small, but I currently don't have the time to test other DB systems.


Posted in performance | Tags sessions


blog comments powered by Disqus