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`:
# config/initializers/session_store.rb
ActionController::Base.session_store = :active_record_store
ActiveRecord::SessionStore.session_class = ActiveRecord::SessionStore::SqlBypass
.. then in `session_controller.rb`
# app/controllers/session_controller.rb
class SessionController session[:user_id], :status => :ok
end
def write
render :text => session[:user_id] = 23, :status => :ok
end
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.