Session Overload!

A quick Rake task to purge old session records from your database

Daniel O'Shea • Jan. 31, 2008 6:39 PM

 

You've deployed your application to production and are starting to monitor performance and you realize that old session records are starting to accumulate and slow your app down.  Don't be alarmed just whip up a little rake task to toss those stale sessions into the bit bucket.  Create a file: lib/tasks/your_tasks.rake with something like the following and you'll be golden. 

  desc "Remove session records that have NOT been updated in over a week."
task(:session_sweep => :environment) do
one_week_ago = (Time.today - 1.week).to_s(:db)
ActiveRecord::Base.connection.execute( "delete from sessions where updated_at < '#{one_week_ago}';" )
end

You can call this task like so:

rake session_sweep. 

You can also pass an environment like so (defaults to development):

rake RAILS_ENV='production' session_sweep

 If you forget the name of your task you can use 'rake --tasks' to get the full list.


Categories: Development