skip to content

In Rails 8.1, when the database behind Solid Cache or the Redis server behind :redis_cache_store becomes unreachable, what does Rails.cache.fetch do?

level: seniorimportance: should knowfreq 28%

answer

  1. the store swallows the outage
  2. a read error becomes a miss
  3. writes are dropped, not raised
  4. error_handler: lambda and error reporter
  5. Solid Cache rescues transient errors only

basics

~20 s

Both stores fail safe: a read error is treated as a miss so Rails.cache.fetch runs its block, the write is dropped, and the error goes to the store's error_handler and Rails' error reporter instead of raising, so the app stays up but every request recomputes.

solid answer

~40 s

Both stores wrap backend calls in a private `failsafe` method. When Redis raises `Redis::BaseError`, a `RedisClient::Error` or a connection-pool error, `RedisCacheStore` returns a neutral value: `nil` for a read, so `fetch` treats it as a miss and runs the block, and nothing for the write, which is dropped. Solid Cache does the same for transient Active Record errors such as `ActiveRecord::ConnectionNotEstablished`, `StatementTimeout` or `Deadlocked`; any other database error still raises. Each store calls its `error_handler:` lambda with `method:`, `returning:` and `exception:` (the default logs it) and reports the exception through `ActiveSupport.error_reporter` with `:warning` severity. The production effect is that the site stays up but every request does the uncached work, so the database behind it takes the full load; Redis' one-second default timeouts add up to that much per call.

code

ruby · 8 lines
ruby
# config/environments/production.rb
config.cache_store = :redis_cache_store, {
  url: ENV["REDIS_CACHE_URL"],
  error_handler: ->(method:, returning:, exception:) {
    Rails.logger.warn("cache #{method} failed: #{exception.class}")
    ActiveSupport::Notifications.instrument("cache_error.app", method: method)
  }
}

go deeper

for a junior

Remember that Rails' Redis and Solid Cache stores treat an unreachable backend as a cache miss, so pages still render but without the benefit of caching.

for a middle

Explain the failsafe wrapper: reads return nil and become misses, writes are dropped, and the error goes to error_handler and the Rails error reporter rather than up to the controller.

for a senior

Plan for the load shift: an outage sends every request to the database, so add metrics in error_handler, keep timeouts tight, give Solid Cache its own database, and know which errors still raise.

for a principal

Decide what the cache is allowed to be relied on for. If correctness depends on a write landing, such as a lock or quota, a fail-safe cache is the wrong tool and the design should change.

## The design: a cache outage should not be a site outage A cache is an optimisation. If losing it took the whole application down, the cache would make the site less reliable. Rails' networked stores therefore **fail safe**: they catch the backend's errors, return the value a miss or a failed write would return, report the problem, and let the request continue. ## `RedisCacheStore` The store's own documentation lists it as fault tolerant: if the Redis server is unavailable, no exceptions are raised, cache fetches are all misses and writes are dropped. In the code: - every Redis call runs inside `failsafe`, which rescues `Redis::BaseError`, `ConnectionPool::Error`, `ConnectionPool::TimeoutError` and, when the `redis-client` gem is loaded, `RedisClient::Error`; - the rescue calls the **`error_handler`** given to the store with keyword arguments `method:`, `returning:` and `exception:`, then returns `returning`, such as `nil` for a read; - the default handler logs `RedisCacheStore: <method> failed, returned ...` and calls `ActiveSupport.error_reporter` with `severity: :warning`. The default connection settings are `connect_timeout`, `read_timeout` and `write_timeout` of **1 second** each. While Redis is unreachable rather than refusing connections, each cache call can wait up to that long before failing over to a miss, which turns into visible latency on pages that make several cache calls. ## Solid Cache Solid Cache's `Failsafe` module follows the same shape with a narrower net. It rescues only **transient** Active Record errors: | Rescued | Typical cause | |---|---| | `ActiveRecord::ConnectionNotEstablished` | database down or unreachable | | `ActiveRecord::AdapterTimeout` | adapter-level timeout | | `ActiveRecord::StatementTimeout`, `ActiveRecord::QueryCanceled` | slow query cancelled | | `ActiveRecord::Deadlocked`, `ActiveRecord::LockWaitTimeout` | lock contention | When one occurs, Solid Cache reports it through `ActiveSupport.error_reporter` as handled with `:warning` severity, calls its `error_handler` (default: log `SolidCacheStore: <method> failed ...`), and returns the fallback. Anything else, such as a missing `solid_cache_entries` table because the cache schema was never loaded, **raises** like any other database error. That difference matters in a deploy checklist: a forgotten cache database fails loudly, a flaky one fails quietly. ## `MemCacheStore`, for comparison `MemCacheStore` rescues `Dalli::DalliError` and connection-pool errors in a private `rescue_error_with`, logs them and reports them through the error reporter, returning `nil`, `false` or `{}` depending on the call. It has no `error_handler:` option. ## What happens to the application 1. `Rails.cache.fetch(key) { expensive }` reads, gets the fallback `nil`, treats it as a miss, runs `expensive`, then tries to write and the write is dropped. 2. The page renders correctly but slowly, and **every** request repeats the expensive work, because nothing ever gets stored. 3. The load the cache was absorbing lands on the primary database or the external API behind it, which is often the real incident. ## Operating it well - Give the store an `error_handler:` that increments a metric, so a cache outage shows up as a rising error rate and not only as slower pages. - Watch the error reporter for the `:warning` reports these stores emit. - Keep Solid Cache in its **own database** (`database: cache` in `config/cache.yml`). Without a `database`, `databases` or `connects_to` setting, it shares `ActiveRecord::Base`'s connection pool, so cache reads and writes join any surrounding transaction, and a primary-database incident takes the cache with it. - Before trusting a cache for something that is not an optimisation, such as a lock or a rate counter, remember that the store may silently drop the write.

  • The Solid Cache table was never created in production. Does `Rails.cache.fetch` still fail safe?
    No. Solid Cache's failsafe rescues only transient errors such as `ConnectionNotEstablished`, timeouts and deadlocks. A missing table raises `ActiveRecord::StatementInvalid`, which propagates, so pages that read the cache error out until the cache schema is loaded.
  • Why can a Redis cache outage make pages slower rather than just uncached?
    `RedisCacheStore` defaults to one-second connect, read and write timeouts. If Redis does not answer, each cache call waits until a timeout before failing over to a miss, so a page with several cache reads can gain seconds of latency on top of recomputing the values.

  • A Redis outage makes Rails.cache.fetch raise a Redis::BaseError up to the controller.
  • Solid Cache swallows every database error, including a missing table.
  • When the cache is down, Rails serves the last cached value it remembers.
  • MemCacheStore accepts the same error_handler: option as RedisCacheStore.
  • A cache outage cannot affect the primary database's load.