In Rails, when would you use Rails.cache.read_multi or fetch_multi instead of fetch in a loop, and what does each return?
answer
- one round trip for many keys
- read_multi: hash of hits only
- fetch_multi needs a block
- block gets each missing name
- misses saved with write_multi
basics
~20 sUse 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.
solid answer
~50 sA results page in the travel app needs twelve exchange rates; `fetch` in a loop costs twelve store round trips. `Rails.cache.read_multi(*keys)` asks once and returns a hash keyed by the names you passed, containing **only** the hits, so missing keys are simply absent. `Rails.cache.fetch_multi(*keys, expires_in: 10.minutes) { |key| ... }` requires a block, reads all keys at once, yields once per missing name, writes those results with a single `write_multi` and returns a hash for every name in the order given. `skip_nil:` and `force:` work there too, but expired entries are just deleted, so `race_condition_ttl` does not apply. The saving depends on the store: Solid Cache, Redis and Memcached read many keys in one call, while stores without that support loop internally. `write_multi` and `delete_multi` cover the other directions; `delete_multi` returns how many entries it removed.
code
ruby · 11 linespairs = [["fx", "EUR", "USD"], ["fx", "EUR", "GBP"], ["fx", "EUR", "JPY"]]
hits = Rails.cache.read_multi(*pairs)
missing = pairs - hits.keys
if missing.any?
fresh = FxProvider.quotes(missing.map { |(_, f, t)| "#{f}/#{t}" }) # one batched HTTP call
computed = missing.zip(fresh).to_h
Rails.cache.write_multi(computed, expires_in: 10.minutes)
hits.merge!(computed)
endgo deeper
Recall that read_multi and fetch_multi read many keys in one call instead of one call per key.
Explain the return shapes: read_multi has hits only, fetch_multi has every name in order, plus the block per missing name and the write_multi.
Show when to batch provider calls with read_multi plus write_multi, and that fetch_multi skips race_condition_ttl handling.
Judge where cache round trips dominate page time and whether batching, coarser keys or a different store setup pays more.
## Why batch at all On the travel-booking app's search results page, each hotel card shows its price in the traveller's currency, so one page can need a dozen exchange rates. Calling `Rails.cache.fetch` once per rate is correct but makes **one store round trip per key**. With a networked store such as Solid Cache, Redis or Memcached, those round trips add up to most of the page's cache time. The multi-key calls ask once. ## The single-key primitives, for reference | Call | Returns | |---|---| | `Rails.cache.read(key)` | the value, or `nil` on a miss (a cached `nil` looks the same) | | `Rails.cache.write(key, value, expires_in: ...)` | `true` on success, `false` on failure, `nil` when the backend could not be reached | | `Rails.cache.delete(key)` | `true` if an entry was deleted, otherwise `false` | | `Rails.cache.exist?(key)` | `true` only for a live entry whose version matches | | `Rails.cache.fetch(key) { ... }` | the cached or newly computed value | `exist?` is the only way to tell a cached `nil` from a miss, but calling it and then `read` is two round trips and racy; prefer `fetch`. ## `read_multi` ```ruby pairs = %w[EUR/USD EUR/GBP EUR/JPY].map { |p| ["fx", *p.split("/")] } found = Rails.cache.read_multi(*pairs) # => { ["fx", "EUR", "USD"] => 1.0842, ["fx", "EUR", "JPY"] => 162.31 } ``` - Returns a hash keyed by the **names you passed**, not the normalized string keys. - Contains **only hits**; a missing, expired or version-mismatched key is absent. A cached `nil` is present with a `nil` value. - Options go in a trailing hash, as in `read_multi(*keys, namespace: "fx")`. - It never computes anything, so it fits cases where a miss is handled elsewhere, for example rendering "rate unavailable". ## `fetch_multi` ```ruby rates = Rails.cache.fetch_multi(*pairs, expires_in: 10.minutes, skip_nil: true) do |(_, from, to)| FxProvider.quote(from, to) end ``` 1. Raises `ArgumentError` without a block. 2. Reads all keys in one call, unless `force: true` is given, in which case nothing is read. 3. Yields **once per missing name**, passing that name. 4. Collects the results and writes them with **one `write_multi`**, dropping `nil` results when `skip_nil: true` is set. 5. Returns a hash with **every name**, in the order you passed them. What it does not do: expired entries found during the bulk read are deleted and treated as misses, so `race_condition_ttl` has no effect here, and the block runs sequentially, so twelve misses still mean twelve provider calls unless your block batches them itself. ## `write_multi` and `delete_multi` - `Rails.cache.write_multi({ key1 => v1, key2 => v2 }, expires_in: 10.minutes)` stores several entries with shared options. Records used as keys contribute their own versions. - `Rails.cache.delete_multi([key1, key2])` removes several entries and returns the **number deleted**. ## Names, keys and versions 1. The values you pass are **names**: strings, arrays or records. Each is normalized into a store key internally, but results come back keyed by the original names, so `hits.keys` can be compared with your input directly. 2. When a name is a record, its version is checked per entry, so a changed record is a miss even if its key is present. 3. Options such as `expires_in:` or `namespace:` apply to every name in the call. 4. Each call emits one notification, `cache_read_multi.active_support`, whose payload lists the hits, which makes hit rates of batched reads visible in logs and metrics; `fetch_multi` reports through the same event. ## How much it saves depends on the store | Store | Multi-key read | |---|---| | Solid Cache | one query per cache database for all keys | | Redis cache store | one multi-get | | Memcached store | one multi-get | | Memory or file store | loops internally; correct, little saving | Choosing a store is a separate decision; the point here is that batching only pays where the store supports it. ## Choosing between the calls - Many keys, fill misses now: `fetch_multi`. - Many keys, misses handled elsewhere or computed in one batch call: `read_multi`, then `write_multi` for what you computed. - One key: `fetch`. - Do not mix in `exist?` checks; they double the round trips and race with writers.
- Why use read_multi and write_multi instead of fetch_multi?`fetch_multi` calls its block once per missing name. If the provider has a batch endpoint, `read_multi` to find the misses, one batched call, then `write_multi` to store the results turns several slow requests into one.
- Does fetch_multi honour race_condition_ttl?No. The bulk read deletes expired entries and treats them as misses, so the stale-while-regenerating behaviour exists only in single-key `fetch` with a block. Protect hot keys read through `fetch_multi` with a refresh job instead.
- read_multi returns nil entries for every key it could not find.
- fetch_multi without a block works like read_multi.
- read_multi returns the store's normalized string keys.
- fetch_multi calls its block once with all missing names.
- Every cache store answers read_multi in a single round trip.