How to delete a Rails (ActiveRecord) session at the end of a request

683 Views Asked by At

We use Rails with the devise and cancancan gems. Our user sessions are stored using ActiveRecord SessionStore.

In our front end (JavaScript) code we have recently started to use web workers to do Ajax requests to our backend. This means that these requests no longer fall within the same session as requests from the 'main' thread.

This, in turn, means that our database table of sessions quickly grows with 'temporary' sessions from the web worker requests that do not need to be kept. The rate of growth of these temporary records is much higher than the rate of growth we had before so we want to get rid of these unnecessary records.

We can identify the requests from the web workers when they are received on the back end.

One way to remove the unwanted records would be to

  1. create our own SessionStore class and add an attribute to indicate the temporary nature of specific sessions
  2. have a scheduled task remove these records.

We would consider this a 'plan B'.

We would prefer to delete the temporary session at the end of the request handling. We added code to destroy the session in an after_action of the application controller;

# application_controller.rb
after_action :clean_temporary_session

def clean_temporary_session
  session.destroy if is_temporary_session?
end

this does result in the deletion of the session record, however, a new record is created straight away after the record has been deleted, so the number of records still keeps growing.

How do we delete the temporary session record at the end of the request?

0

There are 0 best solutions below