Purging Old ActiveRecord Sessions.

Using ActiveRecord::SessionStore has many benefits but the darwback is that sessions’ data can build up in the table resulting in 10,000+ entries if the application is moderately used, the easiest way to delete old stale sessions is by using the following code snippet.

class SessionCleaner
  def self.remove_stale_sessions
    ActiveRecord::SessionStore::Session.destroy_all( ['updated_at <?', 3.hour.ago] )
  end
end

Stick this code in a file called sessions_cleaner.rb in your /lib folder and execute is using the runner script, you can also schedule it using crontab, make sure you give it the full path though

script/runner -e production "SessionCleaner.remove_stale_sessions"

Tags:

Leave a comment