Rails: clear old sessions stored in database

December 14, 2013 · Posted in Development 

Sessions in Rails application can be stored in a database (as well as in cookies). I used to store session data in a table in database.

Sessions table may grow very large because Rails doesn’t have a built-in mechanism to clear old session data.

So you need to remove old sessions rows from database manually.

Rails has rake task

rake db:sessions:clear

But it will delete ALL sessions and some users may lose their sessions.

It is much better to delete only old expired sessions.

One of the way of automatic clearing of old sessions data is using a rake task and cron to run this task every day.

Create rake task in file ‘lib/tasks/session.rake’ that will remove rows older than 3 days:


After that we can use cron to run this task every day at 5 A.M. when our site is not busy:

0 5 * * * cd /path/to/app/dir/ && rake RAILS_ENV=production sessions:cleanup > /dev/null 2>&1

 

Note: in order to store sessions in a database instead of cookies you need to have this config (for Rails 3):

file "config/initializers/session_store.rb":
 
Rails.application.config.session_store :active_record_store

 

 

Comments

  • http://abhishek77in.ruhoh.com/ Abhishek Srivastava

    I would suggest using – `ActiveRecord::SessionStore::Session.delete_all(["updated_at < ?", 3.days.ago])` so that the code is not database dependent.