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?
answer
- block runs only on a miss
- block result written, then returned
- nil results are cached too
- relative duration vs absolute time
- both together raise ArgumentError
basics
~20 sRails.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 linesrate = 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
Recall that fetch returns the stored value on a hit and runs the block, stores and returns its result on a miss.
Explain what counts as a miss, that nil is cached, the difference between expires_in and expires_at, and the ArgumentError cases.
Show judgment on what to cache, plain values not records, and on deriving expiry from the data itself through the block's options.
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.