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?
answer
- explicit render json: needs a guard
- stale? returns a boolean
- DoubleRenderError after head
- API controllers skip the template digest
- add a class-level etag for format changes
basics
~20 sstale? 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.
solid answer
~40 s`fresh_when` relies on the implicit render: on a fresh request it calls `head :not_modified`, and if the action then calls `render json: ...` Rails raises `AbstractController::DoubleRenderError`. `stale?` calls `fresh_when` and returns `!request.fresh?(response)`, so `if stale?(article) then render json: ... end` renders only when the app's copy is out of date and otherwise leaves the 304 in place. In `ActionController::API`, `ConditionalGet` is included but `EtagWithTemplateDigest` and `EtagWithFlash` are not, so the ETag is a digest of the article's `cache_key_with_version` plus whatever controller-level `etag` blocks add. Because a deploy that changes the JSON shape does not change the record, add a version to the ETag, for example `etag { "articles-v2" }`, or polling clients keep receiving 304 for the old format.
code
ruby · 6 lines# Raises AbstractController::DoubleRenderError on a fresh request
def show
article = Article.find(params[:id])
fresh_when article
render json: article
endgo deeper
Remember the pattern: if stale?(record) then render json:. On a fresh request stale? returns false and Rails sends 304 for you.
Explain why fresh_when plus an explicit render raises DoubleRenderError, and that ActionController::API includes ConditionalGet but not the template-digest or flash ETag modules.
Design the ETag for a polled API: record version, a class-level format version for deploys, per-user data where relevant, and associated data that must invalidate the response.
Weigh polling with conditional GET against pushing changes, and set expectations for how stale a client may be versus the request volume the API must absorb.
## The scenario A mobile reader app shows an article and refreshes it every minute with `GET /api/articles/:id`. Most of the time nothing has changed, and sending the full JSON again wastes the server's rendering time and the phone's data. The app stores the `ETag` it received and sends it back as `If-None-Match`; the server should answer `304 Not Modified` when the article is unchanged. ## Why `fresh_when` is the wrong fit here `fresh_when` is designed for actions that end with Rails' **implicit render**: 1. it sets the validators; 2. if the request is fresh, it calls `head :not_modified`, which sets the response body and marks it performed; 3. it returns, and the action carries on. An API action does not use implicit rendering; it calls `render json:` itself. On a fresh request that second render meets a response that already has a body, and Rails raises **`AbstractController::DoubleRenderError`**. You could add `return if performed?`, but Rails already has the method for this shape of action. ## `stale?` as the guard `stale?` takes the same arguments as `fresh_when` (a record or relation, or `etag:`, `weak_etag:`, `strong_etag:`, `last_modified:`, `public:`, `cache_control:`, `template:`), calls `fresh_when` with them, and returns `true` when the request is **not** fresh. The pattern is: ```ruby class Api::ArticlesController < ActionController::API etag { "articles-v2" } def show article = Article.find(params[:id]) if stale?(article) render json: article.as_json(only: %i[id title body updated_at]) end end end ``` | Request | `stale?` returns | Response | |---|---|---| | no `If-None-Match` | `true` | 200 with JSON and a weak ETag | | matching `If-None-Match` | `false` | 304 set by `fresh_when`, no body | | ETag from before an edit | `true` | 200 with new JSON and a new ETag | ## What goes into the ETag in an API controller `ActionController::Base` includes three modules that feed the ETag: `ConditionalGet`, `EtagWithTemplateDigest` and `EtagWithFlash`. **`ActionController::API` includes only `ConditionalGet`.** So for `stale?(article)` the ETag is a digest of: - the article's `cache_key_with_version`, which changes when `updated_at` changes; - the result of every controller-level **`etag { ... }`** block, if you declared any. There is no template digest because there is no template. That has a consequence for deploys: if a release adds a field to the JSON, the record's version is unchanged, the ETag is unchanged, and every polling client keeps receiving `304` and showing the old shape. A class-level `etag` block holding a format version, which you bump when the representation changes, fixes it. If the response depends on the caller, for example personalised reading progress, put that in an `etag` block too. ## Practical details for a polling client - `Last-Modified` comes from `updated_at` as well. Under Rails 8.x defaults (`strict_freshness` on), a request that carries `If-None-Match` is judged by the ETag alone. - The default `Cache-Control` for this response is `max-age=0, private, must-revalidate`, which suits a polling client: it always asks, but most answers are a small 304. - `expires_in 30.seconds` would let the app skip some requests entirely, at the cost of showing edits up to 30 seconds late. - A 304 still costs one request and the `Article.find` query; the saving is serialisation and the response body. ## What the interviewer is checking That you know `stale?` is the guard for explicit renders, that `fresh_when` plus `render` raises, and that an API controller's ETag does not include a template digest, so representation changes need an explicit ETag version.
- The article shows a comment count. Why might the app keep getting 304 after a new comment?The ETag is built from the article's `cache_key_with_version`, which only changes when the article's `updated_at` does. A new comment does not change it unless the comment association touches the article, or you pass something like `[article, article.comments.maximum(:updated_at)]` as the ETag.
- How would you test that the endpoint returns 304?In an integration test, make one request, read `response.headers["ETag"]`, then repeat the request with `headers: { "If-None-Match" => etag }` and assert `:not_modified` with an empty body. Then update the article and assert the next request returns 200.
- fresh_when followed by render json: works fine for API actions.
- stale? returns true when the client's copy is still valid.
- An API controller's ETag changes automatically when the JSON format changes.
- ActionController::API cannot do conditional GET at all.
- stale? skips the Article.find query on a fresh request.