skip to content

Fragment & Russian-Doll

The cache view helper stores rendered fragments under keys built from records, their cache_version and a template digest. Interviewers probe how nested fragments stay fresh when a child changes.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In a Rails view, what does <% cache product do %> store, under which key, and what makes that fragment stop being served?

level: juniorimportance: must knowfreq 70%

answer

  1. rendered HTML, not records
  2. views/ prefix plus template path
  3. digest of the template tree
  4. cache_version stored beside the key
  5. perform_caching gates the helper

basics

~20 s

The cache helper stores the HTML its block renders, keyed by the template path, a digest of the template and its partials, and the record's cache_key. A new cache_version (from updated_at) or a template edit makes Rails render it again.

solid answer

~40 s

`cache product do ... end` captures the HTML the block renders and writes it to the store behind `Rails.cache`. The key looks like `views/products/index:<digest>/products/42`: the template's path, a digest of that template and the partials it renders, then `product.cache_key`. The record's `cache_version` (its `updated_at` to the microsecond) is stored inside the entry; on read a different version counts as a miss, so saving the product re-renders the block and overwrites the same key. Editing the template changes the digest and therefore the key. On a hit the block never runs. The helper only caches when the controller's `perform_caching` is true; otherwise it just yields, which is why a fresh development app seems to ignore it until `bin/rails dev:cache` is run.

code

erb · 9 lines
erb
<%# app/views/products/index.html.erb %>
<% @products.each do |product| %>
  <% cache product do %>
    <article class="gear-card">
      <h2><%= product.name %></h2>
      <%= render product.reviews %>
    </article>
  <% end %>
<% end %>

go deeper

for a junior

Recall that the helper caches the HTML of its block, that a record argument supplies the key, and that saving the record makes the fragment re-render.

for a middle

Explain the key parts: views prefix, template path with digest, record cache_key, plus the cache_version kept inside the entry and checked on read.

for a senior

Show you know what does not retire a fragment: other records, helper changes, per-user content. Name how you would make each one visible to the cache.

for a principal

Weigh where fragment caching pays off against the invalidation work it creates, and how to keep a team's cache keys honest as templates grow.

## What the `cache` helper stores In an ERB template, `cache` wraps a block of markup. The first time the block runs, Action View captures the HTML it produces and writes that string to the application's cache store, the one behind `Rails.cache` and configured by `config.cache_store`. On the next render with the same key and a matching version, the helper reads the string back and inserts it into the page **without executing the block**. Nothing about the record itself is cached: the helper stores **rendered markup**, not Active Record objects and not query results. ```erb <%# app/views/products/index.html.erb in an outdoor-gear shop %> <% @products.each do |product| %> <% cache product do %> <article class="gear-card"> <h2><%= product.name %></h2> <p><%= number_to_currency(product.price) %></p> <%= render product.reviews %> </article> <% end %> <% end %> ``` ## How the key is built A fragment written by `cache product` lives under a key assembled from several parts: | Part | Example | Where it comes from | |---|---|---| | Prefix | `views` | added to every fragment key by `combined_fragment_cache_key` | | Template and digest | `products/index:4f1c...` | the template's virtual path plus a digest of the template and the partials it renders | | Record key | `products/42` | `product.cache_key` | | Version (stored in the entry, not in the key) | `20261006093015123456` | `product.cache_version`, built from `updated_at` | Optional parts slot in as well: `ENV["RAILS_CACHE_ID"]` or `ENV["RAILS_APP_VERSION"]` when either is set, and any controller-wide prefix declared with the `fragment_cache_key` class method. The version is the subtle part. With cache versioning on (the default since `load_defaults 5.2`), the record's timestamp is **not** part of the key string. The store keeps the version inside the entry and, on every read, compares it with the version the current record reports. A mismatch is treated exactly like a miss. ## What retires a fragment 1. **The record changes.** `product.update(price: 189)` moves `updated_at`, so `cache_version` changes; the next render misses, re-runs the block and overwrites the entry under the **same** key. 2. **The template changes.** Editing `index.html.erb`, or a partial the digest knows it renders, changes the digest and so produces a different key; the old entry is never read again and ages out of the store. 3. **The store drops it.** An `expires_in:` passed to the helper (`cache product, expires_in: 12.hours do`), the store's own size or age limits, or a cache clear removes entries. What does **not** retire it on its own: - a change to a *different* record the block displays, such as a review or the product's category; - a change to a helper method the block calls; - a different signed-in user viewing the same card. Those must be expressed through the key, a touch on the parent, or the template digest, which is what Russian-doll caching and template dependencies are about. ## When the helper does nothing The helper checks the controller's `perform_caching` flag first. When it is false, `cache` simply yields and renders the block every time. In a newly generated Rails 8.1 app: - **development** sets `perform_caching` to false unless `tmp/caching-dev.txt` exists, a file `bin/rails dev:cache` toggles; - **test** uses `:null_store`, which keeps nothing, so every render misses; - **production** sets `perform_caching` to true and, after the Solid Cache installer runs, uses `:solid_cache_store`. So "fragment caching does nothing on my machine" is almost always the development toggle, not a broken key. ## Choosing what to wrap - Wrap markup that is **expensive** to render and **shared** by many viewers: product cards, review lists, navigation trees. - Keep per-user details, such as an edit link or a "you bought this" badge, outside the block, or put the user in the key. - Pass a record, a relation or an array of them rather than a bare string. A string key such as `cache "gear-sidebar"` has no version, so only a template edit, an `expires_in:` or eviction ever refreshes it. - Remember that the controller action still runs: `cache` saves view rendering, not the queries the action issued before rendering. Associations loaded lazily inside the block, however, are skipped entirely on a hit. The helper returns `nil` and writes the fragment straight into the template's output buffer, which is why it is written with `<% %>` rather than `<%= %>`.

  • What happens if you wrap an unsaved record, as in cache Product.new?
    An unsaved record's `cache_key` is `products/new` and its `cache_version` is `nil`, so every unsaved product shares one versionless entry. The first rendering is served to everyone afterwards, so a cached block around a new-record form shows stale or foreign content. Keep unsaved records out of fragment keys.
  • Does a cache hit skip the queries behind the page?
    Only the ones the block would have run. The controller action executes before rendering, so `@products = Product.order(:name)` still loads. Associations touched only inside the block, such as `product.reviews`, are skipped on a hit because the block never executes. That is why fragment caching pairs well with lazy loading inside the cached block.

  • The cache helper stores the product row so later requests skip the database.
  • You must call expire_fragment after every product update.
  • Editing the ERB inside the block requires clearing the cache by hand.
  • Each product save writes a new key and strands the old entry.
  • Fragment caching is active in development as soon as you add the helper.
open as a page

In Rails Russian-doll caching, why can editing a review leave the outer product fragment stale, and what keeps the nested fragments fresh?

level: middleimportance: must knowfreq 60%

basics

~20 s

The outer fragment is versioned by the product's updated_at alone, so a review change leaves it valid and its block never reaches the fresh review fragment. Declaring belongs_to :product, touch: true on Review moves the outer version.

open as a page

In Active Record, how do cache_key, cache_version and cache_key_with_version differ for a record and for a relation, and why are they split?

level: middleimportance: should knowfreq 45%

basics

~20 s

cache_key is a stable name (products/42), cache_version is the changing part (updated_at, or count plus newest updated_at for a relation), and cache_key_with_version joins them. Splitting them lets one entry be overwritten instead of piling up dead keys.

open as a page

In a Rails view, how do array keys and cache_if or cache_unless keep per-user markup out of a fragment that every visitor shares?

level: middleimportance: should knowfreq 40%

basics

~20 s

Everyone whose render produces the same key shares the fragment, so per-user markup must enter the key, as in cache [product, current_user.role], or bypass caching: cache_if and cache_unless just render the block when their condition disables caching.

open as a page

In Rails fragment caching, how does the template digest expire fragments when views change, and when must you add a Template Dependency comment?

level: middleimportance: should knowfreq 35%

basics

~20 s

The fragment key embeds a digest of the template and every partial its render calls name, so editing any of them yields a new key. Rails cannot see partials rendered from helpers, so those need a Template Dependency comment.

open as a page

On a Rails product grid, what does render partial: "products/product", collection: @products, cached: true do differently from a cache block inside each, and what can go wrong?

level: seniorimportance: should knowfreq 38%

basics

~20 s

cached: true builds every item's fragment key first, fetches them all with one read_multi, renders only the misses and writes them back with write_multi. A cache block inside an each loop does one store round trip per item.

open as a page