Skip to Content Skip to Search

Redis Cache Store

Deployment note: Take care to use a dedicated Redis cache rather than pointing this at a persistent Redis server (for example, one used as an Active Job queue). Redis won’t cope well with mixed usage patterns and it won’t expire cache entries by default.

Redis cache server setup guide: redis.io/topics/lru-cache

  • Supports vanilla Redis, hiredis, and Redis::Distributed.

  • Supports Memcached-like sharding across Redises with Redis::Distributed.

  • Fault tolerant. If the Redis server is unavailable, no exceptions are raised. Cache fetches are all misses and writes are dropped.

  • Local cache. Hot in-memory primary cache within block/middleware scope.

  • read_multi and write_multi support for Redis mget/mset. Use Redis::Distributed 4.0.1+ for distributed mget support.

  • delete_matched support for Redis KEYS globs.

  • read supports delete: true to atomically read and delete a cache entry using the Redis GETDEL command.

    cache.write("greeting", "hello")
    cache.read("greeting", delete: true)  # => "hello"
    cache.read("greeting")                 # => nil
    
Methods
C
D
I
N
R
S

Constants

DEFAULT_ERROR_HANDLER = -> (method:, returning:, exception:) do if logger logger.error { "RedisCacheStore: #{method} failed, returned #{returning.inspect}: #{exception.class}: #{exception.message}" } end ActiveSupport.error_reporter&.report( exception, severity: :warning, source: "redis_cache_store.active_support", ) end
 
DEFAULT_REDIS_OPTIONS = { connect_timeout: 1, read_timeout: 1, write_timeout: 1, }.freeze
 

Attributes

[R] redis

Class Public methods

new(**options)

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 70
      def self.new(**options)
        if options[:redis]
          ActiveSupport.deprecator.warn(<<~MSG.squish)
            Passing a Redis or ConnectionPool instance via the `:redis` configuration to ActiveSupport::Cache::RedisCacheStore
            is deprecated and will be removed in Rails 8.3.

            RedisCacheStore no longer depends on the `redis` gem, but use the simpler `redis-client`.

            Prefer passing a raw `:url` option instead, of if you need more advanced configuration, pass a configured `RedisClient`
            via the `:client` option.
          MSG
          return DeprecatedRedisCacheStore.new(**options)
        end

        super
      end

new(error_handler: DEFAULT_ERROR_HANDLER, **redis_options)

Creates a new Redis cache store.

The :url param can be:

 - A string used to create a RedisClient::Pooled instance.
 - An array of strings used to create a +RedisClient::HashRing+ instance.

Option  Class       Result
:url    String  ->  RedisClient.config(url: …).new_pool
:url    Array   ->  RedisClient::HashRing.new([RedisClient.config(url: …).new_pool, ...])

If you need some advanced configuration for the client, or want to use an alternative implementation like ‘redis-cluster-client`, you can pass an already configued client via the :client option:

config.cache_store = :redis_cache_store, client: RedisClient.config(...)
config.cache_store = :redis_cache_store, client: [RedisClient.config(...), RedisClient.config(...)]
config.cache_store = :redis_cache_store, client: -> { RedisClient.config(...) }

No namespace is set by default. Provide one if the Redis cache server is shared with other apps: namespace: 'myapp-cache'.

Compression is enabled by default with a 1kB threshold, so cached values larger than 1kB are automatically compressed. Disable by passing compress: false or change the threshold by passing compress_threshold: 4.kilobytes.

No expiry is set on cache entries by default. Redis is expected to be configured with an eviction policy that automatically deletes least-recently or -frequently used keys when it reaches max memory. See redis.io/topics/lru-cache for cache server setup.

Race condition TTL is not set by default. This can be used to avoid “thundering herd” cache writes when hot cache entries are expired. See ActiveSupport::Cache::Store#fetch for more.

Setting skip_nil: true will not cache nil results:

cache.fetch('foo') { nil }
cache.fetch('bar', skip_nil: true) { nil }
cache.exist?('foo') # => true
cache.exist?('bar') # => false
# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 131
def initialize(error_handler: DEFAULT_ERROR_HANDLER, **redis_options)
  universal_options = redis_options.extract!(*UNIVERSAL_OPTIONS)
  pool_options = self.class.send(:retrieve_pool_options, redis_options)

  if redis_options.key?(:client)
    client = redis_options.delete(:client)
    clients = Array.wrap(client.respond_to?(:call) ? client.call : client)
  else
    urls = Array.wrap(redis_options.delete(:url))
    urls << nil if urls.empty?
    clients = urls.map do |url|
      RedisClient.config(url: url, protocol: 2, **redis_options)
    end
  end

  clients.map! do |c|
    if c.respond_to?(:new_pool)
      c.new_pool(**(pool_options || {}))
    else
      c
    end
  end

  @redis = if clients.size > 1
    RedisClient.ring(clients)
  else
    clients.first
  end

  @error_handler = error_handler

  super(universal_options)
end

supports_cache_versioning?()

Advertise cache versioning support.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 66
def self.supports_cache_versioning?
  true
end

Instance Public methods

cleanup(options = nil)

Cache Store API implementation.

Removes expired entries. Handled natively by Redis least-recently-/ least-frequently-used expiry, so manual cleanup is not supported.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 290
def cleanup(options = nil)
  super
end

clear(options = nil)

Clear the entire cache on all Redis servers. Safe to use on shared servers if the cache is namespaced.

Failsafe: Raises errors.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 298
def clear(options = nil)
  failsafe :clear do
    if namespace = merged_options(options)[:namespace]
      delete_matched "*", namespace: namespace
    else
      redis.then { |c| c.flushdb }
    end
  end
end

decrement(name, amount = 1, options = nil)

Decrement a cached integer value using the Redis decrby atomic operator. Returns the updated value.

If the key is unset or has expired, it will be set to -amount:

cache.decrement("foo") # => -1

To set a specific value, call write passing raw: true:

cache.write("baz", 5, raw: true)
cache.decrement("baz") # => 4

Decrementing a non-numeric value, or a value written without raw: true, will fail and return nil.

To read the value later, call read_counter:

cache.decrement("baz") # => 3
cache.read_counter("baz") # 3

Failsafe: Raises errors.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 275
def decrement(name, amount = 1, options = nil)
  options = merged_options(options)
  key = normalize_key(name, options)

  instrument :decrement, key, amount: amount do
    failsafe :decrement do
      change_counter(key, -amount, options)
    end
  end
end

delete_matched(matcher, options = nil)

Cache Store API implementation.

Supports Redis KEYS glob patterns:

h?llo matches hello, hallo and hxllo
h*llo matches hllo and heeeello
h[ae]llo matches hello and hallo, but not hillo
h[^e]llo matches hallo, hbllo, ... but not hello
h[a-b]llo matches hallo and hbllo

Use \ to escape special characters if you want to match them verbatim.

See redis.io/commands/KEYS for more.

Failsafe: Raises errors.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 204
def delete_matched(matcher, options = nil)
  unless String === matcher
    raise ArgumentError, "Only Redis glob strings are supported: #{matcher.inspect}"
  end
  pattern = namespace_key(matcher, options)

  instrument :delete_matched, pattern do
    redis.nodes.each do |node|
      node.with do |conn|
        conn.scan(match: pattern, count: SCAN_BATCH_SIZE).each_slice(SCAN_BATCH_SIZE).each do |keys|
          conn.call("unlink", *keys)
        end
      end
    end
  end
end

increment(name, amount = 1, options = nil)

Increment a cached integer value using the Redis incrby atomic operator. Returns the updated value.

If the key is unset or has expired, it will be set to amount:

cache.increment("foo") # => 1
cache.increment("bar", 100) # => 100

To set a specific value, call write passing raw: true:

cache.write("baz", 5, raw: true)
cache.increment("baz") # => 6

Incrementing a non-numeric value, or a value written without raw: true, will fail and return nil.

To read the value later, call read_counter:

cache.increment("baz") # => 7
cache.read_counter("baz") # 7

Failsafe: Raises errors.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 243
def increment(name, amount = 1, options = nil)
  options = merged_options(options)
  key = normalize_key(name, options)

  instrument :increment, key, amount: amount do
    failsafe :increment do
      change_counter(key, amount, options)
    end
  end
end

read_multi(*names)

Cache Store API implementation.

Read multiple values at once. Returns a hash of requested keys -> fetched values.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 171
def read_multi(*names)
  return {} if names.empty?

  options = names.extract_options!
  options = merged_options(options)
  keys    = names.map { |name| normalize_key(name, options) }

  instrument_multi(:read_multi, keys, options) do |payload|
    read_multi_entries(names, **options).tap do |results|
      payload[:hits] = results.keys.map { |name| normalize_key(name, options) }
    end
  end
end

stats()

Get info from redis servers.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 309
def stats
  redis.then { |c| c.info }
end