Search code examples
ruby-on-railsrackrack-middleware

What is ActiveSupport::Cache::Strategy::LocalCache used for?


In my production middleware stack in all environments I see this one-off instance:

use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x7f38095d>

I've experimented by removing everything I can think of related to caching, but I'm unable to figure out where it comes from.

What is it?


Solution

  • In the abstract, it wraps another cache with an in-memory cache for the duration of a block, and then is cleared after the block.

    In practice I believe it is used in Rails/Rack to wrap whatever cache you have configured (memcached, disk) with an in-memory cache which is cleared at the end of the request. The idea is that if you fetch the same cache key twice in one request, it will be cached in the wrapping LocalCache on the first request and will loaded from memory on the second request (instead of reaching out to the memcached server/disk again).

    From the docs:

    Caches that implement LocalCache will be backed by an in-memory cache for the duration of a block. Repeated calls to the cache for the same key will hit the in-memory cache for faster access.

    Git History: https://github.com/rails/rails/commits/master/activesupport/lib/active_support/cache/strategy/local_cache.rb

    RDoc: http://api.rubyonrails.org/classes/ActiveSupport/Cache/Strategy/LocalCache.html