skip to content

Conditional GET & ETags

fresh_when and stale? compare a record's ETag and updated_at with the request so Rails answers 304 Not Modified without rendering. Interviewers ask about weak ETags and the Cache-Control helpers.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

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%

answer

  1. validators from the record
  2. weak ETag plus Last-Modified
  3. updated_at becomes Last-Modified
  4. head :not_modified on a match
  5. the template never renders

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.

solid answer

~40 s

`fresh_when` is an Action Controller method from `ActionController::ConditionalGet`. Given a record, it uses the record itself as the ETag validator, which Rails turns into a weak `W/"..."` digest of its `cache_key_with_version` (plus the template digest in a full controller), and sets `Last-Modified` from `updated_at`; given a relation, it uses `maximum(:updated_at)`. It then calls `request.fresh?(response)`. If the client's `If-None-Match` or `If-Modified-Since` matches, it calls `head :not_modified`, so the implicit render is skipped: no view, no partials, no queries made only by the view, and an empty body. If not, the action falls through to its normal template. The action code before `fresh_when`, such as `Article.find`, still runs, so the saving is rendering, not the lookup.

code

http · 8 lines
http
GET /articles/42 HTTP/1.1
If-None-Match: W/"3f2b0c9a51d4e6f78a90b1c2d3e4f5a6"
If-Modified-Since: Tue, 06 Oct 2026 08:15:00 GMT

HTTP/1.1 304 Not Modified
ETag: W/"3f2b0c9a51d4e6f78a90b1c2d3e4f5a6"
Last-Modified: Tue, 06 Oct 2026 08:15:00 GMT
Cache-Control: max-age=0, private, must-revalidate

go deeper

for a junior

Remember that fresh_when sets an ETag and Last-Modified from the record and answers 304 with an empty body when the browser's copy still matches.

for a middle

Explain the flow: validators are computed after the lookup, request.fresh? compares them, head :not_modified marks the response performed, and the implicit render is skipped.

for a senior

Point out what the ETag does and does not cover: the record version, the template digest and flash, but not associated data unless you touch or include it.

for a principal

Judge where conditional GET pays off: pages that are expensive to render but cheap to version, and the cost of keeping validators honest as pages gather more data.

## Conditional GET in one line A browser that already has a page can ask the server "has it changed?" by sending back the validators it received, in the `If-None-Match` and `If-Modified-Since` request headers. If nothing changed, the server answers `304 Not Modified` with an empty body and the browser reuses its copy. In Rails, **`fresh_when`** is the controller method that sets those validators and answers the 304 for you. ## What `fresh_when(@article)` sets ```ruby class ArticlesController < ApplicationController def show @article = Article.find(params[:id]) fresh_when @article end end ``` With a single record as the argument: - **ETag**: the record becomes the weak ETag validator. Rails expands it with the same cache-key logic the cache uses (`cache_key_with_version` for an Active Record model), adds the outputs of any controller-level `etag` blocks, and hashes the result into a 32-character hex digest written as `W/"..."`. In a controller inheriting from `ActionController::Base` two blocks are built in: the **template digest** of the action's view and the **flash** when it is not empty. - **Last-Modified**: taken from `@article.updated_at`. For a relation such as `Article.where(published: true)`, `fresh_when` uses `maximum(:updated_at)`. - **Cache-Control**: unless you set it, Rails sends `max-age=0, private, must-revalidate`, so the browser keeps the copy but asks again every time. ## What happens on the second request 1. The browser sends `If-None-Match: W/"..."` (and `If-Modified-Since` with the date). 2. The action runs up to `fresh_when`: the `Article.find` query still happens. 3. `fresh_when` computes the validators again and calls `request.fresh?(response)`. 4. If they match, it calls **`head :not_modified`**. The response is marked as performed, so Rails' implicit render does nothing. 5. If they do not match, `fresh_when` returns and the action ends normally; the implicit render produces `show.html.erb` with the new ETag. | Request | Work on the server | Response | |---|---|---| | first visit, no validators | lookup, render | 200 with body, ETag, Last-Modified | | revisit, article unchanged | lookup only | 304, empty body | | revisit, article updated | lookup, render | 200 with body and a new ETag | ## What it saves and what it does not The saving is everything rendering would cost: templates, partials, helper calls and any queries that only the view triggers, such as loading comments. It also saves bandwidth. It does **not** save the queries that run before `fresh_when`; the record has to be loaded to know its version. The validators come from the record, so any change that bumps `updated_at` produces a new ETag. A change that does not touch the record, such as an edited comment on the page, will not, unless the record is touched or the comments are part of the ETag; deciding that is the caching sibling topic of keys and touching. ## Options you meet early - `fresh_when etag: @article, last_modified: @article.published_at` picks the validators explicitly. - `fresh_when @article, public: true` allows shared caches to store the page, for content that is the same for everyone. - `fresh_when @article, template: "articles/summary"` names a different template whose digest belongs in the ETag, and `template: false` skips the digest. ## Why interviewers ask it Junior candidates often describe HTTP caching only in the abstract. Naming `fresh_when`, the record-derived validators, and the fact that the 304 skips rendering but not the lookup shows they have used it in a Rails app.

  • Does `fresh_when` stop the rest of the action from running?
    No. It is an ordinary method call. On a fresh request it calls `head :not_modified`, which marks the response as performed so the implicit render is skipped, but code after it still runs. That is why side effects or an explicit `render` after `fresh_when` are a problem, and why `stale?` exists.
  • What does `fresh_when Article.where(published: true)` use for its validators?
    The relation itself becomes the ETag validator, expanded through its collection cache key and version, and `Last-Modified` comes from `maximum(:updated_at)` on the relation. Computing those runs a query, but it is cheaper than loading and rendering every article.

  • fresh_when skips the database lookup that loads the record.
  • fresh_when sets a strong ETag by default.
  • A 304 from fresh_when still sends the rendered body.
  • fresh_when stores the rendered page in Rails.cache.
  • fresh_when halts the action like a return statement.
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

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

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

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