Rails Asynchronous Cache Expiration

My application uses the usual caching utility (a subclass of ActionController :: Caching :: Sweeper) to expire the cache (essentially fragments).

Now, cache expiration blocks the application for several seconds, which negatively affects performance, as perceived by the client.

It would be great if I asynchronously terminated the cache, for example, using delayed_job (the application is currently hosted on the hero).

Unfortunately, just adding handle_synchronously to the cache expiration function in the sweeper does not work.

Is it possible that cache fragments expired asynchronously with delayed_job? If so, what are the best methods for doing this?

+5
source share
1 answer

You will need to manually expire the cache. Since you are using memcached, you only need the data needed to generate the cache keys.

Then you can write a delayed task for direct access to the cache and delete the required keys.

Here's an example sweeper for Resque:

class UserMemcachedSweeper < ActionController::Caching::Sweeper
  observe User

  def after_save(user)
    Resque.enqueue UserCacheExpiry, user.id
  end
end

class UserCacheExpiry
  @queue = :cache_expiry

  def self.perform(user_id)
    Rails.cache.delete("/users/#{user_id}")
  end
end
+3
source

All Articles