Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails cache expire

I have a rails application, in that I am using simple rails cache. My testing is as follows:

Rails.cache.write('temp',Date.today,:expires_in => 60.seconds)

I can read it through Rails.cache.read('temp') and Rails.cache.fetch('temp').

The problem is it doesn't expire. It will still be alive after 60 seconds. Can any one tell me what is missing here.

FYI: I have declared in my development.rb as follows :

config.action_controller.perform_caching = true

config.cache_store = :memory_store

Is there anything I missed out? I want to expires my cache.

like image 388
palani Avatar asked Jan 13 '12 05:01

palani


People also ask

Does Rails cache use Redis?

Rails 5.2 introduced built-in Redis cache store, which allows you to store cache entries in Redis.

Is Rails cache thread safe?

Keep it in memory thread_mattr_accessor method which makes it easy to build a trivial thread-safe cache service. Rails' implementation ensures every thread has its own storage location for cached_value ; therefore this should be thread-safe (assuming #compute_value can safely run both concurrently and in parallel).

What does Rails cache do?

Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the web server (i.e. Apache or NGINX) without having to go through the entire Rails stack. While this is super fast it can't be applied to every situation (such as pages that need authentication).

What are view caches?

View caching in Ruby on Rails is taking the HTML that a view generates and storing it for later.


1 Answers

After some search, I have found one possible reason why the cache is not cleaned after 60 seconds.

  1. You call Rails.cache.write which is documented here.
  2. It calls write_entry(namespaced_key(name, options), entry, options), where your option :expires_in is one part of the options argument.
  3. The implementation of write_entry has the following condition:

    if expires_in > 0 && !options[:raw]
        # Set the memcache expire a few minutes in the future to support race condition ttls on read
        expires_in += 5.minutes
    end
    

So there are 5 minutes added to your 60 seconds. 2 possible solutions:

  • Just live with it :-)
  • Try to include the option :raw => true, perhaps this will skip the condition, so that your expiry works as suspected.
like image 91
mliebelt Avatar answered Oct 13 '22 15:10

mliebelt