Boost Rails Sessions
There are many dark corners and hidden features in a big framework like Rails.
Digging inside the code of ActiveRecord I discovered an interesting class: SqlBypass. When you set your session store on ActiveRecord it will use a Base subclass for deal with database store. This configuration adds an useless overhead for your application, because each session read/write will go through the complex callbacks system of ActiveRecord.
For these reason is highly advisable to use SqlBypass. As the name suggest it bypasses all the callbacks and simply performs read/write operations.
Try It By Yourself
In session_store.rb:
1 # config/initializers/session_store.rb 2 ActionController::Base.session_store = :active_record_store 3 ActiveRecord::SessionStore.session_class = ActiveRecord::SessionStore::SqlBypass
.. then in session_controller.rb
1 # app/controllers/session_controller.rb 2 class SessionController < ApplicationController 3 def read 4 render :text => session[:user_id], :status => :ok 5 end 6 7 def write 8 render :text => session[:user_id] = 23, :status => :ok 9 end 10 end
I ran raw benchmarks with one Mongrel instance in production mode:
read:
- Session: 93.05 reqs/sec
- SqlBypass: 132.78 reqs/sec
write:
- Session: 99.89 reqs/sec
- SqlBypass: 128.17 reqs/sec
You can find the whole benchmark results at the dedicated gist.
UPDATE: Unfortunately there is a bug in SqlBypass, just apply this patch for make it working.
advertising





Comments
Respond to this article