With Rails.cache.fetch, what do the force:, skip_nil: and version: options change, and when would you reach for each?
answer
- force skips the read
- force without a block raises
- skip_nil keeps failures out
- version mismatch counts as a miss
- WriteOptions in the block
basics
~20 sforce: 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.
solid answer
~50 s`force: true` makes `fetch` behave as if the key were missing: it does not read, runs the block and writes the result, which suits a refresh job that rewrites hot keys before they expire; it needs a block or raises `ArgumentError`, and when the refresh is unconditional `write` says the same thing more plainly. `skip_nil: true` keeps a `nil` result out of the store, so a provider timeout that returns `nil` is retried on the next call instead of being served for the whole expiry. `version:` is compared with the version stored in the entry; a mismatch counts as a miss and the new value overwrites the same key, which is how you retire entries when the cached shape changes without inventing new keys. Records and relations used as keys supply a version automatically. Inside the block, the `WriteOptions` argument lets you set `version`, `expires_in` or `expires_at` from the result.
code
ruby · 8 linesRails.cache.fetch(["fx", "EUR", "USD"],
expires_in: 10.minutes,
skip_nil: true) do
FxProvider.quote("EUR", "USD") # nil on timeout: returned, not stored
end
Rails.cache.fetch("fx/EUR/USD", force: true)
# => ArgumentError: Missing block: Calling `Cache#fetch` with `force: true` requires a block.go deeper
Recall that force recomputes, skip_nil avoids storing nil, and version makes old entries count as misses.
Explain each option's effect on the read and the write, the ArgumentError for force without a block, and how version overwrites the same key.
Show where each fits in production: refresh jobs, failure handling that does not cache errors or storm the provider, format changes during deploys.
Set conventions for how a team signals failures to the cache and versions cached formats across deploys.
## Three options that change `fetch`'s decision `Rails.cache.fetch(key, options) { ... }` normally reads, and runs its block only on a miss. Three options change when the block runs and what gets stored. In the travel-booking app they cover a refresh job, a flaky rates provider and a change to the cached format. | Option | Effect on the read | Effect on the write | Typical use | |---|---|---|---| | `force: true` | skipped | always writes the block's result | refresh jobs, admin "recompute" actions | | `skip_nil: true` | unchanged | skipped when the block returns `nil` | sources that return `nil` on failure | | `version: v` | entry with another version is a miss | stores `v` with the entry | retiring entries when the cached shape changes | ## `force: true` `force: true` makes `fetch` behave as if the entry were absent. It does not read the store, runs the block and writes the result with the other options you passed. - It **requires a block**; `fetch(key, force: true)` without one raises `ArgumentError`. - It is most useful when the decision is computed, as in `force: params[:refresh].present?`, or in a job that rewrites hot keys before they expire so web requests rarely miss. - When you always want to overwrite, `Rails.cache.write(key, value, expires_in: ...)` expresses the intent more plainly; Active Support's own documentation says the same. ```ruby class RefreshRatesJob < ApplicationJob def perform(pair) from, to = pair.split("/") Rails.cache.fetch(["fx", from, to], force: true, expires_in: 10.minutes) do FxProvider.quote(from, to) end end end ``` ## `skip_nil: true` By default `fetch` stores whatever the block returns, and **`nil` is a valid cached value**. If `FxProvider.quote` swallows a timeout and returns `nil`, every traveller sees no rate for the next ten minutes. With `skip_nil: true`: 1. The block's `nil` is returned to the caller. 2. Nothing is written. 3. The next call misses and tries the provider again. Points worth stating: - Only `nil` is skipped; `false`, `0` and empty collections are stored normally. - An **exception** raised in the block is never cached, with or without the option, so raising on failure and rescuing at the call site is the other clean design. - Skipping `nil` means a dead provider is called on every request; pair it with a timeout or a circuit breaker so the retry storm stays bounded. ## `version:` A **cache version** is a value stored inside the entry and compared on every read. When the requested version differs from the stored one, the read is a **miss**, and the fresh value is written to the **same key**, replacing the old entry rather than leaving it behind. ```ruby FX_FORMAT = "2" # bumped when the cached hash gained :bid and :ask Rails.cache.fetch(["fx", from, to], version: FX_FORMAT, expires_in: 10.minutes) do quote = FxProvider.quote(from, to) { mid: quote.mid, bid: quote.bid, ask: quote.ask } end ``` - Use it when the **shape** or **meaning** of the cached value changes, or when the source exposes a revision number you can compare. - When the key is an Active Record object or relation, the store asks it for a version itself, so you rarely pass `version:` alongside a record. - An explicit `version:` takes precedence over a version derived from the key. ## Setting options from the result The block receives the key and an `ActiveSupport::Cache::WriteOptions` object. Assigning `options.version`, `options.expires_in` or `options.expires_at` there applies to the write that follows, and setting one expiry clears the other: ```ruby Rails.cache.fetch(["fx", from, to]) do |_key, options| quote = FxProvider.quote(from, to) options.expires_at = quote.valid_until quote.mid end ``` ## How the options combine - **`force: true` with `skip_nil: true`** is a useful refresh pattern: the job always recomputes, but if the provider fails and returns `nil`, nothing is written and the **previous value stays in place** for readers until it expires. - **`version:` with `race_condition_ttl:`**: a version mismatch is a plain miss, so no stale value is served while the new format is computed; expect a burst of regeneration after a deploy that bumps the version. - **`version:` with `force: true`**: the read is skipped, so the version only affects what is stored for later readers. ## Choosing between them - A value must be **recomputed now**: `force: true` in the code path that knows it, or `write`. - A **failure** must not be remembered: `skip_nil: true`, or raise instead of returning `nil`. - **Old entries** must stop being served after a format change: `version:`, or a new key segment if old entries should simply be abandoned.
- How does version: differ from adding the version to the key string?A version in the key creates a new key per version and leaves old entries until eviction. `version:` keeps one key, stores the version inside the entry, treats a mismatch as a miss and overwrites in place, so a size-capped store does not fill with dead entries.
- Does skip_nil: true help when the block raises?It is not needed for that: an exception propagates out of `fetch` before any write, so nothing is cached either way. `skip_nil` matters only when failures are signalled by returning `nil`.
- force: true with no block simply reads the current value.
- skip_nil: true also skips caching false and empty arrays.
- A version mismatch raises an error on read.
- version: creates a new key for each version value.
- fetch caches an exception raised inside the block.