skip to content

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%

answer

  1. outer hit never runs the block
  2. version comes from product only
  3. belongs_to with touch: true
  4. callback-free writes break the chain
  5. unchanged inner fragments are reused

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.

solid answer

~50 s

With `cache product` wrapping `cache review` blocks, the outer entry's version comes only from `product.cache_version`. Editing a review moves the review's `updated_at` and retires its own fragment, but on the next request the outer read still matches, returns the stored HTML and never runs its block, so the new review fragment is never reached. The fix is to make child writes bump the parent: `belongs_to :product, touch: true` on `Review` touches the product after a review is created, changed or destroyed, and chains upward if `Product` also touches its category. When the outer fragment then re-renders, every unchanged review is a cache hit, which is the point of the nesting. Writes that skip callbacks, such as `update_column`, `update_all`, `touch_all` or `delete_all`, do not touch the parent, so bulk jobs must touch the affected products themselves.

code

ruby · 12 lines
ruby
class Category < ApplicationRecord
  has_many :products
end

class Product < ApplicationRecord
  belongs_to :category, touch: true
  has_many :reviews
end

class Review < ApplicationRecord
  belongs_to :product, touch: true
end

go deeper

for a junior

Recall that nested cache blocks need the parent touched when a child changes, and that belongs_to touch: true is the usual way to do it.

for a middle

Explain why an outer hit never runs its block, how touch propagates up a chain, and why unchanged inner fragments are reused on regeneration.

for a senior

Show where it breaks in production: callback-free bulk writes, hot parent rows, long touch chains, and how you would repair freshness after a bulk job.

for a principal

Weigh touch chains against children-in-the-key and explicit invalidation for a write-heavy model, and decide which freshness contract the team adopts.

## The nesting **Russian-doll caching** is fragment caching with cache blocks inside cache blocks. On the outdoor-gear shop's product grid, each product card is cached, and inside it each review is cached: ```erb <%# app/views/products/_product.html.erb %> <% cache product do %> <h2><%= product.name %></h2> <%= render product.reviews %> <% end %> <%# app/views/reviews/_review.html.erb %> <% cache review do %> <p><%= review.rating %>/5: <%= review.body %></p> <% end %> ``` The payoff comes on regeneration. When the outer fragment misses, Rails re-runs its block, and every inner `cache review` call whose review has not changed is a **hit**. Only the reviews that actually changed are rendered again, so a card with forty reviews is rebuilt by rendering only the one review that changed. ## Why the outer fragment goes stale The outer entry is keyed and versioned by **the product alone**: its `cache_key` and its `cache_version`, which comes from `products.updated_at`. Editing a review moves `reviews.updated_at`, which retires that review's own fragment, but nothing tells the product. On the next request: 1. `cache product` compares the stored version with `product.cache_version`. They still match. 2. The helper returns the stored HTML and **never executes its block**. 3. The inner `cache review` call is never reached, so the fresh review fragment is never read. The page keeps showing the old review text, or omits a new review, for as long as the product row is unchanged. The inner layer being correct does not help, because the outer layer short-circuits it. ## Touching the parent The standard fix is to make every child write bump the parent's `updated_at`: ```ruby class Review < ApplicationRecord belongs_to :product, touch: true end ``` With `touch: true`, the association installs callbacks that touch the product after a review is **created**, **updated** with real changes, **destroyed**, or itself touched. Moving a review to another product touches both the old and the new product. The parent's timestamp update is deferred until just before the transaction commits. Chains work as well: if `Product` declares `belongs_to :category, touch: true`, touching a product touches its category, so a category page's outermost fragment refreshes too. ## Writes that break the chain `touch: true` runs through Active Record callbacks, so any write that skips callbacks leaves the parent alone: | Write | Review side | Product touched? | |---|---|---| | `review.update(body: "Leaks in rain")` | `updated_at` moves | yes | | `review.destroy` | row deleted | yes | | `review.update_column(:body, "...")` | `updated_at` unchanged | no | | `Review.where(spam: true).update_all(hidden: true)` | `updated_at` unchanged | no | | `Review.where(spam: true).touch_all` | `updated_at` moves | no | | `Review.where(spam: true).delete_all` | rows deleted | no | A moderation job that removes spam with `delete_all` therefore leaves the deleted reviews visible inside every cached product card. After a bulk write, touch the parents yourself, for example `Product.where(id: affected_ids).touch_all`, so the outer fragments re-render with the remaining reviews. ## Alternatives and costs - **Children in the outer key.** `cache [product, product.reviews] do` adds the relation's version (row count plus newest `updated_at`) to the outer version, so no touch is needed. The price is one `COUNT`/`MAX` query per card per render, and it still misses callback-free writes that keep both the count and the newest timestamp unchanged. - **Write amplification.** Every review write now also updates the product row. A popular product receiving many reviews at once becomes a hot row, and a long chain turns one child write into several `UPDATE` statements in the same transaction. - **Suppressing touches on purpose.** During a bulk review import, `Product.no_touching { ... }` stops products from being touched once per review; touch the affected products once afterwards. - **Template changes need no touch.** If `_review.html.erb` changes, the outer template's digest changes too, because the digest of a template includes the digests of the partials it renders. ## How to reason about it in an interview Name the chain explicitly: the outer version must change whenever anything rendered inside it changes. `touch: true` is the usual way to propagate that for associated records; the key, the digest or an explicit touch handles everything else. Then say what it costs: an extra `UPDATE` per child write on the parent row and every ancestor, and silent staleness whenever a write path skips callbacks. A strong answer ends with how you would audit those write paths, for example by searching the codebase for `update_all`, `delete_all` and `update_column` on models whose parents are cached.

  • Does touch_all on the products also touch their categories?
    No. `touch_all` is a single `UPDATE` on the products table that runs no callbacks, so the `touch: true` on `Product`'s `belongs_to :category` never fires. If category pages are cached, touch the affected categories as well.
  • What does Product.no_touching do during an import of reviews?
    Inside `Product.no_touching { ... }`, calls that would touch a product, including the ones triggered by reviews' `touch: true`, do nothing. That turns thousands of product updates into none; afterwards you touch each affected product once so their fragments refresh.
  • Why not just call expire_fragment from a review callback?
    `expire_fragment` needs the exact key, including the template digest the view computed, which a model callback does not know, and it couples models to view paths. Moving the parent's version lets every fragment keyed on the product, in any template, notice the change.

Nested gift boxes, each labelled on the lid: swapping the gift in a small box leaves the big box's label unchanged, so anyone trusting the outer label hands over the old contents. touch: true relabels every box around the one you opened, and when the big box is re-wrapped, every small box still sealed goes back in as it is.

  • An inner fragment refreshing is enough because the outer block re-renders it.
  • Rails tracks which records a fragment displayed and expires it automatically.
  • update_all on reviews touches their products when touch: true is declared.
  • touch: true makes every inner fragment re-render when the parent changes.
  • Russian-doll caching requires calling expire_fragment from model callbacks.