Rails: clear old sessions stored in database

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



One thought on “Rails: clear old sessions stored in database”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>