skip to content

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%

answer

  1. middleware hashes the finished body
  2. only 200 or 201, buffered bodies
  3. Rack::ConditionalGet turns 200 into 304
  4. fresh_when decides before rendering
  5. strong_etag: for byte-exact needs

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.

solid answer

~40 s

Rails' default middleware stack includes `Rack::ConditionalGet` and `Rack::ETag` (with `"no-cache"` as its fallback). After the action has rendered, `Rack::ETag` computes a digest of a buffered 200 or 201 body and sets `ETag: W/"..."`, unless the response already has an `ETag` or `Last-Modified`. `Rack::ConditionalGet`, wrapped around it, compares that value with `If-None-Match` and replaces the 200 with an empty 304. The client saves the download, but the server has already done all the work. `fresh_when` and `stale?` compute the validators from the record before rendering, so a match answers 304 without rendering at all. Both are weak by default; `fresh_when strong_etag:` produces a strong ETag when byte-exact matching is needed, for example `Range` requests or a CDN that ignores weak ones.

code

ruby · 7 lines
ruby
class ReportsController < ApplicationController
  def show
    @report = Report.find(params[:id])
    # Strong ETag: some CDNs and Range requests need byte-exact validators
    fresh_when strong_etag: @report, last_modified: @report.updated_at
  end
end

go deeper

for a junior

Know that Rails adds an ETag to normal responses automatically, and that fresh_when is the explicit way to set one from a record.

for a middle

Explain that Rack::ETag hashes the body after rendering and Rack::ConditionalGet turns a matching 200 into a 304, so only bandwidth is saved, while fresh_when skips rendering.

for a senior

Choose per action: leave cheap pages to the middleware, add fresh_when or stale? to expensive ones, and use strong_etag: where a CDN or Range requests require byte-exact validators.

for a principal

Decide where validation should live across the stack, in Rails, a CDN or both, and how to keep validators consistent when pages are assembled from many sources.

## Two places an ETag can come from A Rails 8.1 app can answer `304 Not Modified` in two quite different ways, and the difference is where the decision is made. 1. **In the controller**, before rendering, with `fresh_when` or `stale?`. 2. **In Rack middleware**, after rendering, with `Rack::ETag` and `Rack::ConditionalGet`. ## The middleware path Rails' default middleware stack contains, in this order, `Rack::Head`, `Rack::ConditionalGet` and `Rack::ETag, "no-cache"`. A response passes through `Rack::ETag` first on its way out: - it acts only on status **200 or 201**; - it needs a body that can be buffered (`to_ary`); a streamed response, such as one written by `ActionController::Live`, is left alone; - it **skips** any response that already has an `ETag` or `Last-Modified` header, so anything `fresh_when` set wins; - otherwise it hashes the body (SHA-256 in Rack 3.2), keeps the first 32 hex characters and sets `ETag: W/"..."`; - if no `Cache-Control` is present it sets `max-age=0, private, must-revalidate` when it produced a digest, and `no-cache` when it did not. Then `Rack::ConditionalGet` sees the response. For a `GET` or `HEAD` with status 200 it compares `If-None-Match` with the `ETag` (or, without `If-None-Match`, `If-Modified-Since` with `Last-Modified`). On a match it changes the status to 304, removes `Content-Type` and `Content-Length`, closes the body and sends nothing. The important point: by the time `Rack::ETag` runs, the controller has run every query and rendered every template. **The server's work is spent; only the transfer is saved.** ## The controller path `fresh_when(@article)` builds the ETag from what the page is made of rather than from its bytes: the record's `cache_key_with_version`, the template digest and any `etag` blocks. That can be known **before** rendering, so a fresh request ends at `head :not_modified` and the view never runs. | | `Rack::ETag` + `Rack::ConditionalGet` | `fresh_when` / `stale?` | |---|---|---| | When the ETag is computed | after rendering | before rendering | | Computed from | the response body bytes | record versions, template digest, `etag` blocks | | Code needed | none, it is in the default stack | one call per action | | Saves | bandwidth | rendering, view queries and bandwidth | | Weak or strong | always weak | weak by default, strong with `strong_etag:` | ## Weak and strong in Rails terms The protocol meaning of weak and strong validators belongs to HTTP; what matters in Rails is which options produce which: - `fresh_when etag: x` and `fresh_when weak_etag: x` both set `W/"digest"`; - `fresh_when strong_etag: x` sets `"digest"` without the prefix; - `response.strong_etag = ...` and `response.weak_etag = ...` set them directly, and `response.weak_etag?` / `response.strong_etag?` tell you which you have. Rails' own documentation recommends weak ETags for HTML pages and strong ones for responses that must be byte-identical, such as `Range` requests within a large PDF or video, and for CDNs that do not support weak ETags. ## When the middleware alone is enough For cheap pages the automatic ETag is a reasonable default: it costs a hash of the body and saves the download for clients that revalidate. For expensive pages it only hides the cost from the network, and the right fix is `fresh_when`/`stale?`, or fragment caching for parts that change independently. ## Why interviewers ask it Candidates often say "Rails already does ETags" and stop. The follow-up is whether they know that the default only saves bytes, and that controller-level conditional GET is what saves CPU.

  • Why does a page rendered with `ActionController::Live` get no automatic ETag?
    `Rack::ETag` only digests bodies it can buffer with `to_ary`. A live stream is written while the response is being sent, so there is nothing to hash in advance; the middleware leaves it untouched and, if no `Cache-Control` was set, marks it `no-cache`.
  • If an action calls `fresh_when`, does `Rack::ETag` still hash the body on a stale request?
    No. `Rack::ETag` skips any response that already carries an `ETag` or `Last-Modified` header, so the controller's validators are the ones the client sees and no body digest is computed.

Rack::ETag is a courier who drives the parcel to your door, sees you already have one exactly like it and drives it back; fresh_when checks the order number before anyone packs the box.

  • The automatic Rack::ETag means Rails skips rendering for unchanged pages.
  • Rack::ETag produces strong ETags because it hashes the exact body bytes.
  • Rack::ETag overwrites the ETag that fresh_when already set.
  • Rails needs a gem to send ETags on ordinary responses.
  • fresh_when hashes the rendered HTML to build its ETag.