HTTP Caching: ETags And Last-Modified
Learn how ETags, Last-Modified, and conditional GET requests work, and use Rails stale? and fresh_when to return 304 responses.
By Jean Emmanuel Cadet • 24 min read
Every time a browser downloads a page, a JSON payload, or an image it already has a perfectly good copy of, someone pays for it. The user waits on the network, your server spends CPU and database time building the response, and your hosting bill quietly grows. For content that changes rarely compared to how often it is requested, most of that work is wasted.
HTTP has a built-in answer to this problem: validators. A validator is a small piece of metadata, such as an ETag or a Last-Modified timestamp, that identifies a specific version of a resource. When a client holds a stored copy and is unsure whether it is still current, it asks the server a cheap question: "Has this changed since the version I have?" If not, the server replies with a tiny 304 Not Modified response that carries no body, and the client reuses what it already has.
In this guide you will learn how ETags and Last-Modified work, how conditional requests use them, and how Rails exposes all of it through stale?, fresh_when, and expires_in. We will build a realistic controller, test it, and cover the mistakes that cause most real-world caching bugs. The goal is a reference you can return to when something behaves strangely in the browser's network tab.
What Is HTTP Caching?
HTTP caching is the practice of storing a response so it can be reused for later requests instead of fetching it again from the origin server. The protocol defines the rules that decide when a stored response may be reused, and those rules are expressed almost entirely through response headers.
Caches exist at several layers:
- Browser cache (private cache): Stores responses for a single user. It can safely hold personalized content.
- Shared caches: CDNs, reverse proxies, and corporate proxies sit between many users and your server. They may store responses only when the headers allow it, and they should never serve one user's private data to another.
- Server-side caches: Rails fragment caching,
Rails.cache, and Redis or Solid Cache stores live inside your application. They are not HTTP caches, but they often work alongside them.
Two ideas drive everything else in this article:
- Freshness: How long a stored response may be reused without asking the server anything. During this window, the client does not make a network request at all.
- Validation: What a cache does once a response is no longer fresh. Instead of blindly downloading the whole thing again, it sends a conditional request to check whether the stored copy is still valid.
When caching works well, repeat visits skip the network entirely while the response is fresh. After it goes stale, a short validation round trip replaces a full download. Both reduce traffic and server work, though as we will see, to different degrees.
Fresh vs. Stale Responses
A cached response is fresh while its age is below its freshness lifetime. The most common way to set that lifetime is the Cache-Control header with the max-age directive, expressed in seconds:
HTTP/1.1 200 OK
Date: Mon, 23 Nov 2026 14:30:00 GMT
Cache-Control: max-age=300
Content-Type: text/html; charset=utf-8
This tells any cache that the response can be reused for 300 seconds after it was generated. During those five minutes, the browser answers from its own cache without contacting your server.
Once the age exceeds max-age, the response becomes stale. A stale response is not necessarily wrong or deleted. It simply cannot be reused without checking with the origin server first. If the stored response carries a validator (ETag or Last-Modified), the cache can send a conditional request to revalidate it. If the response has no validator, the cache has nothing to ask about and must download the full resource again.
Here are the Cache-Control directives you will meet most often:
Directive | Meaning |
|---|---|
| The response is fresh for N seconds. |
| Shared caches (CDNs, proxies) may store the response. |
| Only the end user's own cache may store it. |
| The response may be stored, but it must be revalidated before every reuse. |
| Do not store the response at all. |
| Once stale, the response must not be reused without successful validation. |
The names no-cache and no-store are famously confusing. no-cache does not mean "do not cache." It means "cache it, but always validate first." That is exactly the behavior you want when you rely on ETags for content that must always be checked.
The key distinction to remember: max-age controls freshness, while ETag and Last-Modified enable validation of a stale response. They solve different halves of the problem and work best together.
What Are ETags?
An ETag (entity tag) is an opaque identifier that a server assigns to a particular representation of a resource. When the representation changes, the ETag should change too.
ETag: "6f1c2a9e4b7d83055ae2c19d7b40f8e3"
The word opaque matters. Clients must not try to interpret an ETag. They store it and send it back unchanged, nothing more. The server is free to generate it however it likes:
- A digest of the response body.
- A digest of a database record's identity and
updated_attimestamp. - A version number or revision counter.
- A combination of file size and modification time.
Because the format is up to the server, you should never assume an ETag is a plain hash of the content, and you should never treat it as a safe place to leak anything. A well-designed ETag reveals nothing about the underlying data. Generation also varies by framework, resource, representation, and configuration. The same record could produce different ETags in two applications, or even for two formats (HTML and JSON) within one application.
An ETag identifies a representation, not just a resource. The HTML version of an article, the JSON version, and a gzip-compressed variant are different representations, and in principle each deserves its own ETag.
Strong and Weak ETags
ETags come in two flavors, distinguished by syntax:
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
ETag: W/"0815"
- A strong ETag (plain quoted string) promises that the representation is byte-for-byte identical whenever the tag matches.
- A weak ETag (prefixed with
W/) promises only that two representations are semantically equivalent. Small byte differences, such as a rebuilt timestamp in a footer, may exist.
Servers compare ETags using two different rules:
- Strong comparison: Both tags must be strong and have identical opaque values.
- Weak comparison: The opaque values must match, and the
W/prefix is ignored.
If-None-Match, the header used for cache validation, uses weak comparison. That is why weak ETags work perfectly well for ordinary page caching. But If-Match and If-Range require strong comparison, so weak ETags are not suitable for byte-range requests or safe-update preconditions. Weak ETags are a good fit for many cache validation scenarios, not for every use case.
What Is the Last-Modified Header?
Last-Modified is the older and simpler validator. The server tells the client when it believes the resource last changed:
Last-Modified: Fri, 20 Nov 2026 09:15:42 GMT
The value uses the HTTP date format, which is always expressed in GMT and has one-second precision. When the client later revalidates, it sends that timestamp back in an If-Modified-Since header:
If-Modified-Since: Fri, 20 Nov 2026 09:15:42 GMT
The server compares the timestamp with the resource's current modification time. If the resource has not been modified after that moment, the server can answer 304 Not Modified.
In Rails, updated_at is the natural source for this value, since it already tracks when a record last changed. Static files served from disk traditionally use the file's modification time.
One side effect is worth knowing early. If a response has Last-Modified but no explicit freshness information, caches are allowed to calculate a heuristic freshness lifetime, often a fraction of the time since the last modification. Your resource may then be served from cache without any validation for a while. Setting an explicit Cache-Control header removes that guesswork.
ETags vs. Last-Modified
Both validators answer the same question, but they differ in useful ways.
Aspect | ETag | Last-Modified |
|---|---|---|
Precision | Any change can produce a new tag | One second (HTTP date format) |
Format | Opaque string | Date |
Implementation | Needs a version, digest, or cache key | Needs a reliable modification time |
Representation awareness | Can differ per format or encoding | Usually tied to the underlying data |
Failure mode | Unstable tags cause needless misses | Wrong or reset timestamps cause stale or missed hits |
Precision. If a resource can change twice within the same second, Last-Modified cannot tell the two versions apart, and a client could keep a stale copy. ETags have no such limit. They are the better choice for frequently changing resources.
Implementation. Last-Modified is trivial when you already have a trustworthy timestamp. ETags require you to decide what identifies a version, which is more flexible but also easier to get wrong.
Reliability. Timestamps break in surprising ways: a restored backup, a touch that changes nothing meaningful, a deploy that resets file times, or clock drift between servers. Version-based ETags avoid most of these problems.
Representation changes. A timestamp says when the data changed, not whether the rendered output did. If a template changes, or the response differs by format, Last-Modified alone will not notice. Rails handles this by including a template digest in its generated ETags.
Using both. Servers commonly send both validators, which lets clients and intermediaries use whichever they understand. When a request carries both If-None-Match and If-Modified-Since, the ETag takes precedence. We will look at the exact rule in the next section.
Conditional HTTP Requests
A conditional request is a normal request with extra headers that make the server's behavior depend on the current state of the resource. For caching, two headers matter:
If-None-Match: "Send the full response only if the current ETag does not match any of these."If-Modified-Since: "Send the full response only if the resource changed after this date."
Here is a complete exchange. First, the original request and response:
GET /articles/http-caching HTTP/1.1
Host: example.com
Accept: text/html
HTTP/1.1 200 OK
Date: Mon, 23 Nov 2026 14:30:00 GMT
Cache-Control: max-age=300, public
ETag: W/"6f1c2a9e4b7d83055ae2c19d7b40f8e3"
Last-Modified: Fri, 20 Nov 2026 09:15:42 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 18452
<!DOCTYPE html>...
Six minutes later, the stored copy is stale. The browser revalidates by echoing both validators:
GET /articles/http-caching HTTP/1.1
Host: example.com
Accept: text/html
If-None-Match: W/"6f1c2a9e4b7d83055ae2c19d7b40f8e3"
If-Modified-Since: Fri, 20 Nov 2026 09:15:42 GMT
If nothing changed, the server answers:
HTTP/1.1 304 Not Modified
Date: Mon, 23 Nov 2026 14:36:10 GMT
Cache-Control: max-age=300, public
ETag: W/"6f1c2a9e4b7d83055ae2c19d7b40f8e3"
Last-Modified: Fri, 20 Nov 2026 09:15:42 GMT
No body, no Content-Length of 18 KB, just headers. The browser reuses its stored copy and resets its freshness clock.
How Servers Evaluate the Conditions
Under the HTTP specification, the logic for GET and HEAD requests is:
- If
If-None-Matchis present, compare its ETags with the current one using weak comparison. A match means "not modified." TheIf-Modified-Sinceheader is ignored in this case. - Only if
If-None-Matchis absent does the server look atIf-Modified-Since. If the resource has not been modified after that date, the answer is "not modified." - If the condition fails (the resource did change), the server sends a normal
200 OKwith the full body and fresh validators.
If-None-Match can also carry several ETags or the wildcard *, which matches any current representation.
One note about Rails specifically: the framework's own conditional GET check (ActionDispatch::Http::Cache::Request#fresh?) has historically treated the response as fresh only when every validator the client sent matches, rather than skipping If-Modified-Since entirely. Browsers send both validators from the same stored response, so both approaches give the same answer in normal use. If you depend on edge cases, read that method in your installed version.
A 304 is appropriate only for GET and HEAD requests. For other methods, a failed If-None-Match precondition produces 412 Precondition Failed.
Understanding HTTP 304 Responses
A 304 Not Modified response means: "The condition you sent was evaluated, and your stored representation is still valid. Reuse it."
Why there is no body. The whole purpose of a 304 is to skip retransmitting the representation. The client already has it. Sending the body again would defeat the point.
What the response does carry. A 304 should include the headers that would have appeared in a 200 and that matter to caches: ETag, Cache-Control, Date, Expires, and Vary. The browser merges these into the stored response. That is how a 304 can extend freshness: the cache gets a new Date and Cache-Control, so the stored copy is considered fresh again.
How it differs from a 200.
|
| |
|---|---|---|
Body | Full representation | None |
Client action | Replace stored copy | Reuse stored copy, update headers |
Bandwidth | Full size | Headers only |
Server work | Depends on app | Depends on app (see below) |
That last row deserves an honest warning. A 304 saves transfer, but it does not automatically save server processing. A server that generates an ETag by rendering the full page and hashing the result still did all the rendering work, then threw the body away. Real savings come when your application decides "not modified" before doing expensive work, which is exactly what Rails' stale? and fresh_when enable. We will return to this point in the Rails sections.
Other Conditional Request Headers
Three more conditional headers appear in HTTP. They are not about cache validation, but you will see them in the same documentation and in network traces.
If-Match: The request should proceed only if the current ETag matches one of the listed values, using strong comparison. It is mainly used onPUT,PATCH, andDELETEfor optimistic concurrency: "update this resource only if nobody changed it since I read it." A failed precondition returns412 Precondition Failed.If-Unmodified-Since: The timestamp version ofIf-Match. The request proceeds only if the resource has not changed after the given date.If-Range: Used with aRangerequest. It says: "If my stored copy is still current, send me just the missing bytes (206 Partial Content). Otherwise, send the whole resource." It requires a strong validator, which is one reason weak ETags are unsuitable here.
You can build a Rails application without touching any of these three, but knowing they exist helps when you read traces from download managers, media players, and API clients.
How HTTP Caching Works in Rails
Rails supports conditional GET at two levels.
The middleware stack. Rails applications include Rack::ETag and Rack::ConditionalGet by default. If your action does not set any validators, Rack::ETag computes a weak ETag from the rendered response body, and Rack::ConditionalGet turns a matching request into a 304. This works with zero code changes, but note the cost: your action runs, the view renders, and only then does Rails discover that the body is unchanged. You save bandwidth but not server work. For more on where these middleware sit around your controller, see our guide to how the Rails request lifecycle works.
The controller helpers. stale? and fresh_when (from ActionController::ConditionalGet) let you declare the validators up front, before rendering. Rails sets the ETag and Last-Modified headers, compares them against the request, and sends head :not_modified immediately when they match. That is where genuine server savings come from.
When validators are present and you have not set Cache-Control, Rails applies a conservative default of max-age=0, private, must-revalidate. In plain terms: the browser may store the response, must revalidate it every time, and shared caches must not store it.
One more detail that surprises people: config.action_controller.perform_caching controls fragment and server-side caching. It does not switch off conditional GET handling.
With that background, let's look at the three helpers.
Using stale? in Rails Controllers
stale? sets validators, checks the request against them, and returns false when the client's copy is still valid (after sending a 304). It returns true when you need to render. The method accepts an object, plus options such as etag:, weak_etag:, strong_etag:, last_modified:, public:, cache_control:, and template:.
# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def show
@article = Article.published.find_by!(slug: params[:slug])
if stale?(@article)
@comments = @article.comments.order(:created_at)
# Implicit render of show.html.erb happens here.
end
end
end
When you pass a record, Rails does two things:
- Uses the record as the source of a weak ETag (derived from its cache key and version, plus a digest of the action's template).
- Sets
Last-Modifiedfrom the record'supdated_at.
If the request's If-None-Match or If-Modified-Since indicates the client is current, Rails responds with 304 and the block never runs. Notice that the comments query lives inside the if. That is deliberate: work you skip on a 304 is work you save. Only the cheap article lookup always runs.
You can also pass validators explicitly:
stale?(etag: @article, last_modified: @article.updated_at, public: true)
Using fresh_when
fresh_when does the same job but without a return value. It is ideal when the only thing the action does is render, since Rails skips the implicit render automatically after a 304.
class ArticlesController < ApplicationController
def show
@article = Article.published.find_by!(slug: params[:slug])
fresh_when @article
end
end
That one line produces a weak ETag and a Last-Modified header derived from updated_at. To control the validators yourself, pass keywords:
# Explicit weak ETag and Last-Modified
fresh_when etag: @article, last_modified: @article.updated_at
# Strong ETag
fresh_when strong_etag: @article, last_modified: @article.updated_at
Rails defaults to weak ETags for good reason. The rendered HTML may contain values that vary slightly between requests, so promising byte-for-byte identity would be dishonest. Use strong_etag: only when your representation is truly byte-identical for a given version.
Collections. You can pass a relation:
def index
@articles = Article.published.order(published_at: :desc)
fresh_when @articles, public: true
end
For a relation, Rails derives Last-Modified from maximum(:updated_at), and the ETag from the relation's cache key (which accounts for the number of records and the latest updated_at). The records themselves are not loaded unless the request turns out to be stale. If you add limit or pagination, check the SQL in your development log to confirm the validators behave the way you expect.
Controlling the template digest. By default, Rails folds a digest of the action's template into the ETag, so a deploy that changes the view invalidates old validators. If your action renders a different template, pass template: with that name. If it renders none (for example, a JSON-only action), pass template: false.
Using expires_in
expires_in sets freshness, not validators. It writes the Cache-Control header:
def show
@article = Article.published.find_by!(slug: params[:slug])
expires_in 10.minutes, public: true
end
This produces Cache-Control: max-age=600, public. For the next ten minutes, browsers and shared caches may reuse the response without contacting your server at all.
Pay attention to what expires_in does not do:
- It does not generate an
ETagorLast-Modified. - It does not evaluate
If-None-Matchor return a 304. - It does not make Rails check anything on later requests. The cache decides.
It also accepts options such as public:, must_revalidate:, stale_while_revalidate:, and stale_if_error:. By default, expires_in produces a private response unless you pass public: true.
expires_in and stale? or fresh_when are not interchangeable. One tells caches how long to reuse a response blindly. The others let caches check whether a stale response is still good. Most production setups use them together.
Combining Cache-Control with Conditional Requests
Freshness and validation complement each other:
- While fresh: the cache answers on its own. No request reaches your server.
- After going stale: the cache sends a conditional request. Your app answers with a cheap 304 or a full 200.
- After a 304: the stored response is fresh again, and the cycle restarts.
In Rails, combining them looks like this:
def show
@article = Article.published.find_by!(slug: params[:slug])
expires_in 5.minutes, public: true
fresh_when @article, public: true
end
The order of expires_in and fresh_when does not matter. Both modify the same response headers. The result is:
Cache-Control: max-age=300, public
ETag: W/"6f1c2a9e4b7d83055ae2c19d7b40f8e3"
Last-Modified: Fri, 20 Nov 2026 09:15:42 GMT
Public vs. Private Caching
Choosing between public and private is a correctness and privacy decision, not a performance tweak.
public: Safe for content identical for every visitor, such as a published blog post. CDNs and proxies may store and serve it to anyone.private: The default in Rails. Only the visitor's own browser may store it. Use it for anything that depends on who is logged in.
Never mark a response public if the layout, a navigation bar, a flash message, or a CSRF token varies per user. A shared cache could serve one person's page to another.
For user-specific pages where you still want validators, include the user in the ETag with the etag class macro:
class DashboardsController < ApplicationController
etag { current_user&.id }
def show
fresh_when current_user.dashboard
end
end
Everything that goes into the block is mixed into every ETag that controller generates, so two users never share a validator.
Files and Attachments
The same ideas apply to uploaded files. Rails itself uses these helpers internally. For example, Active Storage's proxy controllers have relied on http_cache_forever for blob responses. If you serve user files through your application, our practical guide to Rails Active Storage covers the delivery options that determine which cache headers are even in play.
Practical Rails Example
Let's build a realistic example: a public blog article page that readers and CDNs request frequently, but that changes rarely.
The models (app/models/article.rb and app/models/comment.rb):
class Article < ApplicationRecord
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where(published_at: ..Time.current) }
def to_param
slug
end
end
class Comment < ApplicationRecord
belongs_to :article, touch: true
end
The touch: true option is the important line. It updates the parent article's updated_at whenever a comment is created, updated, or destroyed. Because the article page displays its comments, a change to a comment should invalidate the article's validators. With touch: true, using the article's own updated_at and cache key is enough. The touch happens inside the same database transaction as the comment save, so both changes commit together (more on transaction behavior in our Rails transactions guide).
The route (config/routes.rb):
resources :articles, only: %i[index show], param: :slug
The controller (app/controllers/articles_controller.rb):
class ArticlesController < ApplicationController
def show
@article = Article.published.find_by!(slug: params[:slug])
expires_in 5.minutes, public: true
if stale?(@article, public: true)
@comments = @article.comments.includes(:author).order(:created_at)
end
end
end
The request and response flow:
- First visit. The browser has nothing stored. Rails loads the article,
stale?finds no conditional headers, so it returns true. The comments load, the view renders, and the server sends200 OKwithCache-Control: max-age=300, public, anETag, andLast-Modified. - Within five minutes. The browser reuses its stored copy. No request is sent.
- After five minutes, article unchanged. The browser sends
If-None-MatchandIf-Modified-Since. Rails loads the article (one cheap query),stale?sees that the validators match, and Rails sends304 Not Modified. The comments query and the render are skipped entirely. This is real server savings, not just bandwidth savings. - After an edit. Someone updates the article or posts a comment.
updated_atchanges, so the ETag andLast-Modifiedchange. The conditional request fails, and Rails answers200 OKwith the new body and new validators.
Working Alongside Fragment Caching
HTTP caching and fragment caching are complementary, not competing. Fragment caching, covered in our guide on how fragment caching works in Ruby on Rails, speeds up the rendering of a response when your server has to produce one. HTTP caching decides whether your server has to produce one at all, and whether the bytes need to cross the network. A common production setup uses conditional GET to short-circuit unchanged requests and fragment caching to make the unavoidable renders cheaper.
Testing HTTP Caching
Rails integration tests make it easy to verify headers and conditional behavior. Put these in test/integration/article_caching_test.rb. The example uses Minitest, the Rails default.
require "test_helper"
class ArticleCachingTest < ActionDispatch::IntegrationTest
setup do
@article = Article.create!(
title: "HTTP Caching",
slug: "http-caching",
body: "Validators explained.",
published_at: 1.day.ago
)
end
test "sends validators and cache headers" do
get article_path(@article)
assert_response :success
assert response.headers["ETag"].present?
assert response.headers["Last-Modified"].present?
assert_includes response.headers["Cache-Control"], "max-age=300"
assert_includes response.headers["Cache-Control"], "public"
end
test "returns 304 when If-None-Match matches" do
get article_path(@article)
etag = response.headers["ETag"]
get article_path(@article), headers: { "If-None-Match" => etag }
assert_response :not_modified
assert_empty response.body
end
test "returns 304 when If-Modified-Since matches" do
get article_path(@article)
last_modified = response.headers["Last-Modified"]
get article_path(@article), headers: { "If-Modified-Since" => last_modified }
assert_response :not_modified
end
test "returns 200 with new validators after the article changes" do
get article_path(@article)
old_etag = response.headers["ETag"]
travel 1.minute do
@article.touch
end
get article_path(@article), headers: { "If-None-Match" => old_etag }
assert_response :success
assert_not_equal old_etag, response.headers["ETag"]
end
test "a new comment invalidates the article" do
get article_path(@article)
old_etag = response.headers["ETag"]
travel 1.minute do
@article.comments.create!(body: "Great post", author: users(:one))
end
get article_path(@article), headers: { "If-None-Match" => old_etag }
assert_response :success
end
end
A few notes on this test file:
- Read the validators from the first response and replay them. That mirrors what a real browser does and avoids hard-coding ETag values.
travelcomes fromActiveSupport::Testing::TimeHelpers, which Rails includes in test cases. It makes sureupdated_atactually moves, which matters becauseLast-Modifiedhas one-second precision.- The last test assumes a
users(:one)fixture and anauthorassociation on comments. Adjust it to your own schema. - For
HEADrequests, usehead article_path(@article)with the same headers.
Common Mistakes
Incorrect timestamps. Last-Modified is only as trustworthy as the data behind it. Restored backups, bulk updates that skip callbacks, update_column calls that do not change updated_at, and clock drift between servers can all produce timestamps that do not reflect real changes. Remember also that a deleted record does not move maximum(:updated_at), so a collection's Last-Modified may not change after a deletion even though the page did. The collection's ETag accounts for the record count, which is one reason to prefer ETag-driven validation for collections.
Misunderstanding weak vs. strong ETags. Rails generates weak ETags by default, which is correct for page caching but wrong for byte-range requests and If-Match preconditions. Also be careful when a proxy or web server compresses responses. Many servers weaken or rewrite strong ETags when they change the encoding, which can make validation behave differently from what your app intended.
Forgetting Cache-Control. Validators without an explicit freshness policy leave caches to guess. A Last-Modified header with no Cache-Control can trigger heuristic freshness, and your users may see older content than you expect. Rails' default max-age=0, private, must-revalidate protects you when you use its helpers, but custom header code or an intermediary can change that.
Assuming a 304 means no server work. A 304 saves transfer, not computation. If you let Rack::ETag generate the ETag from a rendered body, your server did all the work. To avoid the work, compute validators from cheap data (a record's updated_at) and check them before querying the rest of the page. In your logs, a 304 that still shows the full set of SQL queries is a hint that you are validating too late.
Confusing expiration with validation. Setting expires_in 1.hour does not make Rails check anything. It tells caches not to ask for an hour. If content changes during that hour, visitors may keep the old version. If you need changes to appear quickly, use a short max-age (or no-cache) and rely on validators.
Caching pages with per-session content. Pages that embed CSRF tokens in forms, flash messages, or user menus must not be public, and a reused cached copy can carry stale session-specific values. Keep those pages private, add the user to the ETag, or restructure the page so personalized parts load separately.
Forgetting associated records. If an article page shows comments, tags, or an author name, a change to any of them must change the article's validators. Use touch: true on associations, or pass the associated records into the ETag, for example etag: [@article, @comments].
Best Practices
Use this checklist when adding HTTP caching validators to a production application:
- Choose validators from cheap data. Derive them from
updated_ator a cache key, not from rendering the page. - Check before you work. Call
stale?orfresh_whenas early as possible, and keep expensive queries inside thestale?block. - Set
Cache-Controlexplicitly. Do not rely on heuristic freshness. Pickmax-age,public, orprivatedeliberately. - Default to
private. Usepubliconly for content that is identical for every visitor, layout included. - Keep ETags and
Last-Modifiedconsistent. If one changes, the other should reflect the same state of the world. - Propagate child changes. Use
touch: trueor include associated records in the ETag. - Prefer weak ETags for rendered pages. Reserve strong ETags for byte-identical representations, ranges, and
If-Matchuse cases. - Remember
template:. Let Rails include the template digest so deploys invalidate stale validators, and settemplate: falsefor actions that render no template. - Test conditional behavior. Cover 200, 304, and changed-resource cases in integration tests.
- Verify in the network tab and logs. Look for
304status codes,If-None-Matchheaders, and skipped SQL queries. - Measure before celebrating. HTTP caching helps most when resources are requested repeatedly and change infrequently. For constantly changing or highly personalized responses, the benefit shrinks and the complexity may not be worth it.
Conclusion
HTTP caching is a conversation between client and server. Freshness, set with Cache-Control: max-age and Rails' expires_in, tells caches how long they may reuse a response without asking. Validation, built on ETag and Last-Modified, lets a stale response be checked cheaply with If-None-Match and If-Modified-Since, and answered with a bodyless 304 Not Modified when nothing has changed.
Rails makes this approachable. stale? and fresh_when generate and evaluate validators for you, expires_in handles freshness, and touch: true keeps parent records honest about child changes. Used together and tested properly, they cut unnecessary response transfers and, when you check validators early, real server work as well. Start with one high-traffic, rarely changing page, verify the headers in your browser's network tab, and expand from there.