skip to content

Response & Data Caching

Rails caches at four layers: view fragments with Russian-doll nesting, Rails.cache values, the store behind them such as Solid Cache, and conditional GET. Interviewers probe how each one invalidates.

part ofRuby on Railsread it →
on this pageshow

explore

questions

24

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 a Rails controller, what does fresh_when(@article) put on the response, and what does Rails skip when the request is already fresh?

level: juniorimportance: must knowfreq 48%

basics

~20 s

fresh_when(@article) sets a weak ETag built from the record's cache key and version and a Last-Modified header from updated_at; if the request's If-None-Match or If-Modified-Since matches, Rails answers 304 Not Modified with no body and never renders the template.

open as a page

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?

level: juniorimportance: must knowfreq 65%

basics

~20 s

Rails.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.

open as a page

In a new Rails 8.1 app, which store does config.cache_store select in development, test and production, and why does each environment differ?

level: juniorimportance: must knowfreq 62%

basics

~20 s

A new Rails 8.1 app sets config.cache_store to :memory_store in development, :null_store in test and :solid_cache_store in production; Rails builds Rails.cache from that value at boot, and an app that sets nothing falls back to :file_store in tmp/cache/.

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

A mobile reader app polls a Rails 8.1 API endpoint for one article each minute; why use stale? over fresh_when, and what goes into the ETag?

level: middleimportance: must knowfreq 45%

basics

~20 s

stale? sets fresh_when's validators and returns false on a fresh request, so it can guard render json:, while fresh_when plus render raises DoubleRenderError. In ActionController::API the ETag covers the record and class-level etag blocks, not a template digest.

open as a page

A Rails 8.1 citizen-petition site runs on two app servers; after Rails.cache.delete, one server still shows an old signature count from :memory_store. Why, and which store would you pick?

level: seniorimportance: must knowfreq 48%

basics

~20 s

:memory_store lives inside each Ruby process, so every Puma worker on each server keeps its own copy and Rails.cache.delete clears only the process that ran it; a shared store such as Solid Cache on a networked database, Redis or Memcached fixes it.

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

In a Rails controller, what Cache-Control headers do expires_in, expires_now, no_store and http_cache_forever produce, and when would you use each?

level: middleimportance: should knowfreq 35%

basics

~20 s

expires_in 10.minutes gives max-age=600, private (public with public: true); expires_now gives no-cache; no_store gives no-store; http_cache_forever gives a 100-year max-age with immutable and yields its block only when stale. Without them, Rails sends max-age=0, private, must-revalidate.

open as a page

In Rails 8.1, how does the ETag Rack::ETag adds to an ordinary response differ from one set by fresh_when, and which one saves server work?

level: middleimportance: should knowfreq 32%

basics

~20 s

Rack::ETag hashes the already-rendered body into a weak ETag and Rack::ConditionalGet swaps a matching 200 for a 304, which saves bandwidth only; fresh_when derives the ETag from the record before rendering, so a match skips the view work too.

open as a page

With Rails.cache.fetch, what do the force:, skip_nil: and version: options change, and when would you reach for each?

level: middleimportance: should knowfreq 35%

basics

~20 s

force: 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.

open as a page

In Rails, when would you use Rails.cache.read_multi or fetch_multi instead of fetch in a loop, and what does each return?

level: middleimportance: should knowfreq 30%

basics

~20 s

Use 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.

open as a page

In Rails, what is Active Record's SQL query cache, when is it switched on, and why is it no substitute for Rails.cache?

level: middleimportance: should knowfreq 45%

basics

~20 s

Active Record's query cache remembers result sets of identical SELECTs for one request or job, clears them on any write, and discards them at the end. Rails.cache persists values across requests and processes, so the two solve different problems.

open as a page

In Rails 8.1 development, what does bin/rails dev:cache actually switch, and why does Rails.cache.fetch keep caching when it is off?

level: middleimportance: should knowfreq 40%

basics

~10 s

bin/rails dev:cache creates or deletes tmp/caching-dev.txt, and development.rb sets config.action_controller.perform_caching from that file, which gates Action Controller caching such as view fragments; config.cache_store stays :memory_store, so Rails.cache.fetch caches either way.

open as a page

How does Solid Cache decide which cache entries to delete, and what do max_age and max_size in config/cache.yml control?

level: middleimportance: should knowfreq 38%

basics

~20 s

Solid Cache evicts first-in first-out by row id, not least-recently-used: writes trigger background expiry that deletes the oldest rows when max_size or max_entries is exceeded, and otherwise deletes only rows older than max_age, which defaults to two weeks.

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

A Rails invoice page shows the signed-in user's name and uses fresh_when @invoice; how can a stale or wrong page be served, and how does a class-level etag fix it?

level: seniorimportance: should knowfreq 28%

basics

~20 s

fresh_when @invoice builds its ETag from the invoice, template digest and flash only, so a browser that cached one user's page gets a 304 after another user signs in; a class-level etag { Current.user&.id } adds the viewer to every ETag.

open as a page

When a hot Rails.cache.fetch entry with expires_in: expires under load, what does race_condition_ttl: do, and where does it not help?

level: seniorimportance: should knowfreq 40%

basics

~20 s

With race_condition_ttl:, the first fetch to find a recently expired entry writes it back with a short extension and regenerates, while concurrent callers keep the old value. Missing, evicted or version-mismatched entries get no help.

open as a page

In Rails 8.1, when the database behind Solid Cache or the Redis server behind :redis_cache_store becomes unreachable, what does Rails.cache.fetch do?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Both stores fail safe: a read error is treated as a miss so Rails.cache.fetch runs its block, the write is dropped, and the error goes to the store's error_handler and Rails' error reporter instead of raising, so the app stays up but every request recomputes.

open as a page

With Rails.cache.increment, what happens when the key is missing or expired, and why use it rather than read-then-write for a counter?

level: middleimportance: nice to knowfreq 20%

basics

~20 s

Rails.cache.increment adds to an integer in the store and returns the new value; a missing or expired key starts at the amount. It is atomic in the store, whereas reading, adding and writing back loses updates when processes race.

open as a page

What does config.action_dispatch.strict_freshness change in Rails 8.x when a request sends both If-None-Match and If-Modified-Since, and when would an upgraded app notice?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

With strict_freshness true, which load_defaults 8.0 sets, Rails judges a request carrying If-None-Match by the ETag alone and ignores If-Modified-Since; with false, the old default, both validators must match before fresh_when or stale? answers 304.

open as a page

In Rails 8.1, what is the per-request local cache that stores such as :solid_cache_store and :redis_cache_store wrap around themselves, and when does it surprise you?

level: seniorimportance: nice to knowfreq 16%

basics

~20 s

Stores that include ActiveSupport::Cache::Strategy::LocalCache keep a per-request, per-thread hash in front of the backend: the first read of a key hits the store, later reads in the same request come from memory, including recorded misses, and writes update both.

open as a page