skip to content

Fetch, Expiry & Keys

Rails.cache.fetch returns a cached value or runs its block and stores it, with expires_in:, race_condition_ttl: and skip_nil: shaping it. Interviewers ask what to cache and how to stop stampedes.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In Rails, what does Rails.cache.fetch do on a hit and on a miss, and how do expires_in: and expires_at: bound the entry?

level: juniorimportance: must knowfreq 65%

answer

  1. block runs only on a miss
  2. block result written, then returned
  3. nil results are cached too
  4. relative duration vs absolute time
  5. both together raise ArgumentError

basics

~20 s

Rails.cache.fetch returns the stored value on a hit; on a miss it runs the block, writes the result under the key and returns it. expires_in: sets a duration from the write, expires_at: an absolute time; passing both raises ArgumentError.

solid answer

~40 s

`Rails.cache.fetch(["fx", "EUR", "USD"], expires_in: 10.minutes) { FxProvider.quote("EUR", "USD") }` reads the key; if a live entry with a matching version is there it returns that value and the block never runs. On a miss (no entry, expired, version mismatch) it yields, writes whatever the block returns, `nil` included, and returns it. If the block raises, nothing is written and the exception propagates. `expires_in:` is a duration counted from the write; `expires_at:` is an absolute `Time`, which Active Support turns into a duration at write time. Passing both, or a `Time` as `expires_in:`, raises `ArgumentError`, and since the 7.1 defaults a negative `expires_in:` raises too. Inside the block you can also set expiry from the result, through the `WriteOptions` passed as the second block argument.

code

ruby · 10 lines
ruby
rate = Rails.cache.fetch(["fx", "EUR", "USD"], expires_in: 10.minutes) do
  FxProvider.quote("EUR", "USD") # runs only on a miss
end

Rails.cache.fetch("fx/rates-board", expires_at: Time.current.end_of_hour) do
  FxProvider.board
end

# Raises ArgumentError: both options at once
Rails.cache.fetch("fx/x", expires_in: 5.minutes, expires_at: 1.hour.from_now) { 1 }

go deeper

for a junior

Recall that fetch returns the stored value on a hit and runs the block, stores and returns its result on a miss.

for a middle

Explain what counts as a miss, that nil is cached, the difference between expires_in and expires_at, and the ArgumentError cases.

for a senior

Show judgment on what to cache, plain values not records, and on deriving expiry from the data itself through the block's options.

for a principal

Weigh which slow dependencies deserve a cache at all and what freshness each consumer can tolerate.

## What `fetch` does `Rails.cache` is the application's cache store, an instance of an `ActiveSupport::Cache::Store` subclass chosen by `config.cache_store`. Its `fetch` method is the everyday read-through call. In a travel-booking app that prices trips in the traveller's currency, the exchange rate comes from a slow external service, so it is cached: ```ruby class ExchangeRates def self.rate(from, to) Rails.cache.fetch(["fx", from, to], expires_in: 10.minutes) do FxProvider.quote(from, to) # slow HTTP call, returns a BigDecimal end end end ``` With a block, `fetch` does the following: 1. Builds the key: an array becomes `"fx/EUR/USD"`, a record contributes its `cache_key`, and the store's namespace, if any, is prefixed. 2. Reads the entry. If it exists, is not expired and its version matches, `fetch` **returns the stored value** and the block never runs. 3. Otherwise it **yields**, writes the block's return value under the key with the given options, and **returns that value**. Without a block, `fetch` behaves like `read` and returns `nil` on a miss. ## What counts as a miss | Situation | Result | |---|---| | No entry under the key | miss, block runs | | Entry past its expiry | miss; the expired entry is deleted, unless `race_condition_ttl:` applies | | Entry written with a different `version` | miss, the same key is overwritten | | Stored value cannot be deserialized | miss | | `force: true` passed | treated as a miss without reading | A **cached `nil` is a hit**. If the provider times out and the block returns `nil`, that `nil` is stored and served until the entry expires, which is what `skip_nil: true` prevents. An exception raised inside the block is not cached at all; it propagates to the caller and the next call tries again. ## Bounding the entry: `expires_in:` vs `expires_at:` | Option | Meaning | Example | |---|---|---| | `expires_in:` | duration counted from the write | `expires_in: 10.minutes` | | `expires_at:` | absolute time | `expires_at: Time.current.end_of_hour` | Rules Active Support enforces when it merges the options: - Passing **both** raises `ArgumentError` ("Either :expires_in or :expires_at can be supplied, but not both"). - Passing a **`Time` as `expires_in:`** raises `ArgumentError` and suggests `expires_at`. - A **negative** `expires_in:` raises under `load_defaults 7.1` and later, through `config.active_support.raise_on_invalid_cache_expiration_time`; on older defaults it is reported and logged instead. - `expires_at:` is converted to a duration at write time, so it behaves like `expires_in:` from then on. - With neither option, the entry has no expiry of its own and lives until the store evicts it or a store-wide default applies. When the right expiry depends on the value itself, set it from inside the block. The block receives the key and an `ActiveSupport::Cache::WriteOptions` object: ```ruby Rails.cache.fetch(["fx", from, to]) do |_key, options| quote = FxProvider.quote(from, to) options.expires_at = quote.valid_until # the provider says how long the rate holds quote.rate end ``` Setting `expires_at` there clears any `expires_in`, and the other way round, so the two never conflict. ## What to cache - **Plain values**: numbers, strings, hashes, arrays of ids. They serialize cheaply and do not go stale in surprising ways. - **Not live objects**: an Active Record instance captured in the cache keeps the attribute values it had when cached, and a `Proc` cannot be serialized at all. Cache ids or plain attributes and load records fresh when you need them. - **Not per-user secrets in shared keys**: anything the key does not distinguish is shared by every caller. ## How keys are built - A **string** or **symbol** is used as is: `"fx/EUR/USD"` and `:fx` both work. - An **array** is joined with slashes, so `["fx", "EUR", "USD"]` becomes `"fx/EUR/USD"`. - A **hash** is turned into sorted `key=value` pairs, so argument order does not matter. - An object that responds to `cache_key`, such as an Active Record record, contributes that key, and its version is checked on read. - The store's **namespace**, when configured, is prefixed to every key. - A key longer than the store's limit is truncated and suffixed with a digest, so very long keys still work but become unreadable in tooling. ## Where `fetch` runs `fetch` is callable anywhere: models, service objects, jobs and controllers. It is independent of the view's `perform_caching` flag, which only gates fragment caching. In the generated test environment the store is `:null_store`, so a block runs on every call there; tests that need real caching swap in a memory store.

  • Why is caching an Active Record object with fetch discouraged?
    The cached copy freezes the record's attributes at caching time, so later reads get stale data, and it ties the cache entry to the class's serialized shape, which can break across deploys. Cache ids or plain values instead, then load the records you need.
  • What does fetch return when the store write fails?
    It still returns the block's value. `fetch` writes the result and then returns it regardless of whether the write succeeded, so the caller gets correct data; only the next call pays for another miss.

  • fetch caches nothing when the block returns nil.
  • fetch writes the value even when the block raises an exception.
  • expires_in: and expires_at: can be combined to pick the earlier one.
  • fetch only caches when perform_caching is enabled for the controller.
  • Without a block, fetch raises on a miss.

Assumes Rails 8.1 with load_defaults 8.1; raise_on_invalid_cache_expiration_time, which makes a negative expires_in: raise ArgumentError instead of logging, has been on since the 7.1 defaults.

open as a page

With Rails.cache.fetch, what do the force:, skip_nil: and version: options change, and when would you reach for each?

level: middleimportance: should knowfreq 35%

basics

~20 s

force: true skips the read, runs the block and writes; skip_nil: true stops a nil result being stored; version: stores a version with the entry, so a different version on read is a miss that overwrites the same key.

open as a page

In Rails, when would you use Rails.cache.read_multi or fetch_multi instead of fetch in a loop, and what does each return?

level: middleimportance: should knowfreq 30%

basics

~20 s

Use them when one page needs many keys: read_multi returns a hash of only the names it found, and fetch_multi returns every name's value in input order, running its block per missing name and storing those with one write_multi.

open as a page

In Rails, what is Active Record's SQL query cache, when is it switched on, and why is it no substitute for Rails.cache?

level: middleimportance: should knowfreq 45%

basics

~20 s

Active Record's query cache remembers result sets of identical SELECTs for one request or job, clears them on any write, and discards them at the end. Rails.cache persists values across requests and processes, so the two solve different problems.

open as a page

When a hot Rails.cache.fetch entry with expires_in: expires under load, what does race_condition_ttl: do, and where does it not help?

level: seniorimportance: should knowfreq 40%

basics

~20 s

With race_condition_ttl:, the first fetch to find a recently expired entry writes it back with a short extension and regenerates, while concurrent callers keep the old value. Missing, evicted or version-mismatched entries get no help.

open as a page

With Rails.cache.increment, what happens when the key is missing or expired, and why use it rather than read-then-write for a counter?

level: middleimportance: nice to knowfreq 20%

basics

~20 s

Rails.cache.increment adds to an integer in the store and returns the new value; a missing or expired key starts at the amount. It is atomic in the store, whereas reading, adding and writing back loses updates when processes race.

open as a page