Session store, active record store saving too many rows to heroku database Session store, active record store saving too many rows to heroku database heroku heroku

Session store, active record store saving too many rows to heroku database


I ran into a very similar issue about a year ago, and the solution I had was to write a rake task which ran every so often using the Heroku scheduler free add-on. Here's the rake task:

namespace :maintenance do  desc "Cleanup stale sessions (optional ENV[\"BEFORE_DATE\"] = yyyy/mm/dd)"  task :clear_stale_sessions => :environment do    before_date = ENV["BEFORE_DATE"] || 1.week.ago    start_timestamp = Time.now    if Rails.env.production?      puts "#{start_timestamp} -- Beginning deleting of stale sessions before #{before_date}..."    else      Rails.logger.info "#{start_timestamp} -- Beginning deleting of stale sessions before #{before_date}..."    end    deleted_session_count = ActiveRecord::SessionStore::Session.delete_all(["updated_at <= ?", before_date])    finished_timestamp = Time.now    current_session_count = ActiveRecord::SessionStore::Session.count    if Rails.env.production?      puts "#{Time.now} -- Finished deleting of stale sessions before #{before_date} -- Deleted Sessions: #{deleted_session_count} - Current Sessions: #{current_session_count} -- Time: #{(finished_timestamp - start_timestamp)} seconds."    else      Rails.logger.info "#{Time.now} -- Finished deleting of stale sessions before #{before_date} -- Deleted Sessions: #{deleted_session_count} - Current Sessions: #{current_session_count} -- Time: #{(finished_timestamp - start_timestamp)} seconds."    end  endend

The basic idea is to delete any session information older than a week, but you can use the BEFORE_DATE environment variable in Heroku to change this to any value you wish. Note that on the first run, this may take quite some time depending on how many stale sessions you have, but subsequent runs should be faster.

I run this daily sometime early in the morning (again, using the Scheduler add-on) and it's kept my database size down significantly. I also added some logging to this rake task so I could quickly see how it is doing without having to watch it regularly. You can remove this, if you'd like.

It's important to note that, if you're using all of your Heroku dyno hours for your application, the scheduler will result in some dyno hours being charged to your credit card. In other words, the add-on is free, but use of it may not be.