CommonThread - Our Blog

Removing Stale Sessions in Heroku

Written By: Ben Wyrosdick

May 11th, 2009

Removing stale session in any app is necessary to keep a clean and happy DB. With Heroku apps it is even more important since you don’t want to pay more for a bloated DB with stale data. Heroku makes it easy to run cron tasks by calling ‘rake cron’ against your app every hour. for more info on Heroku cron support see their docs page.

To setup your cron job on Heroku create the file lib/tasks/cron.rake and place the following code in your file:

task :cron => :environment do
  puts "Removing stale sessions ..." 
  session_count = CGI::Session::ActiveRecordStore::Session.delete_all(['updated_at < ?', 1.hour.ago])
  puts "#{session_count} sessions removed" 
  puts "done." 
end

2 Responses to “Removing Stale Sessions in Heroku”

  1. barry Says:
    Question: won't this possibly kill some 'active' sessions; like if the user loaded the page an hour and a half ago but still has the browser window open?
  2. Ben Says:
    @barry yes it will but we are ok with making people log back in if they have been inactive for more than an hour. We have that limit set to 24 hours on one app though and you can conceivably make it any length of time.

Leave a Reply