How Browser Caching Improves Web Performance

Learn how browser caching works, how to set Cache-Control, ETag, and 304 responses, and how to configure it in Rails 8.1 apps.


By Jean Emmanuel Cadet • 21 min read

How Browser Caching Improves Web Performance
Share with friends

Open any modern web page and your browser may fire off dozens of requests for HTML, CSS, JavaScript, images, and fonts. On your second visit, most of those files are exactly the same as they were on the first. Downloading them again wastes bandwidth, adds latency, and makes the server do work it has already done.

Browser caching solves this. The browser keeps a copy of a response and reuses it later, or asks the server a quick question ("has this changed?") instead of downloading the whole file again. Done well, this means faster repeat visits, fewer network requests, lower server load, and pages that feel more responsive.

Done badly, it means users see stale pages, or private data ends up in places it should never be stored. This guide explains how HTTP caching works, which headers control it, and how to configure it in Ruby on Rails 8.1 and at the server or CDN level. You will also learn how to test it. The examples use realistic cache durations, but they are starting points, not universal recommendations.


What Is Browser Caching?

Browser caching is the practice of storing copies of HTTP responses on the user's device so they can be reused for later requests. Almost anything a server sends can be cached: HTML documents, CSS stylesheets, JavaScript bundles, images, web fonts, JSON API responses, and other static assets.

The browser's cache is a private cache. It belongs to one user on one browser profile, so it is different from a shared cache, such as a CDN or corporate proxy, which stores responses and serves them to many users. That distinction matters later when we discuss private, public, and s-maxage.

Browser caching is governed primarily by HTTP caching semantics. The server describes how a response may be stored and reused through response headers, and the browser follows those rules. Your code does not call a caching API. You send the right headers, and the browser does the rest.

Browser caching is also not the same as server-side caching, where your application stores computed data (database results, rendered fragments) in something like Redis or Solid Cache to avoid recomputing it. Server-side caching reduces work on the server. Browser caching can avoid the request altogether.


How Browser Caching Works

Here is the lifecycle of a cached resource:

  1. Initial request. The browser has no stored copy, so it sends a request to the server.
  2. Response. The server replies with the resource and headers such as Cache-Control, ETag, and Last-Modified.
  3. Storage. If the headers allow it, the browser stores the response along with its metadata (when it was received, its validators, and so on).
  4. Later request. When the page needs the same URL again, the browser checks its cache first.
  5. Freshness check. If the stored response is still fresh, the browser reuses it with no network request at all.
  6. Revalidation. If the response is stale and has a validator (an ETag or Last-Modified value), the browser sends a conditional request. The server answers 304 Not Modified (reuse your copy) or 200 OK with a new body.
  7. Full fetch. If nothing is stored, or the response cannot be reused, the browser downloads the resource again.

To decide whether a response is fresh, the browser calculates a freshness lifetime. It prefers Cache-Control: max-age, then falls back to the Expires header. If neither is present, browsers may apply a heuristic based on Last-Modified, often a fraction of the time since the file last changed. Relying on heuristics makes behavior hard to predict, so send explicit headers.

Rails requests pass through several layers before reaching your controller. If you want to see where cache headers fit in, read how the Rails request lifecycle works.


Types of Browser Caching

"Browser cache" is a loose term. Several related mechanisms are involved, and browsers do not all implement them identically. The descriptions below are general, and details vary by browser, version, and platform.

HTTP Caching

HTTP caching is the standardized behavior defined by the HTTP caching specification (RFC 9111). It is what your headers control: what can be stored, how long it stays fresh, and how it is revalidated. This is the layer you configure as a developer.

Memory Cache

Many browsers keep recently used resources in memory for very fast access, for example when the same image appears several times on a page or when you navigate back to a page. Memory caches are usually short-lived and may be cleared when a tab closes or memory runs low. Browsers may reuse something already loaded in the current page even when HTTP headers would not otherwise allow it.

Disk Cache

Browsers also persist responses on disk so they survive tab closures and browser restarts. This is the cache most people think of when they say "browser cache." It has a size limit, and browsers evict entries when space is needed, so a cacheable response is not guaranteed to stay stored.

Fresh and Stale Responses

A cached response is fresh while its age is less than its freshness lifetime, and stale afterward. Stale does not mean unusable: a stale response with a validator can be revalidated cheaply. Some directives, such as stale-while-revalidate, even allow a stale response to be served briefly while a refresh happens in the background.

Remember that cache behavior can also be affected by browser settings, extensions, service workers, proxies, and CDN configuration. Treat DevTools as the final authority for what really happens.


Understanding HTTP Cache Headers

Here is a realistic response for a fingerprinted stylesheet:

HTTP/1.1 200 OK
Content-Type: text/css
Cache-Control: public, max-age=31536000, immutable
ETag: "5f2b8c1d9a"
Last-Modified: Tue, 03 Nov 2026 09:12:00 GMT
Vary: Accept-Encoding
Content-Encoding: gzip

Cache-Control

Cache-Control is the primary header. It carries directives that tell caches whether to store a response, who may store it, and how long it stays fresh. Modern caching policy is written here.

Expires

Expires gives an absolute date after which the response is stale. It is the older mechanism. If Cache-Control: max-age is present, browsers prefer it and ignore Expires. Relative lifetimes are less vulnerable to clock differences between server and client, so prefer max-age.

ETag

An ETag (entity tag) is an opaque identifier for a specific version of a resource, often derived from a content hash or a record's version. It is a validator, not a freshness directive. It does not tell the browser how long to cache anything. It lets the browser ask later, "do you still have version 5f2b8c1d9a?" Weak ETags (prefixed with W/) mean the content is semantically equivalent, not byte-for-byte identical.

Last-Modified

Last-Modified reports when the resource last changed. Like ETag, it is a validator. It has one-second granularity, so ETag is generally more precise.

Vary

Vary lists request headers that influenced the response. Caches must treat different values of those headers as different variants. The classic case is Vary: Accept-Encoding: the server may return a gzip, Brotli, or uncompressed body depending on the request, so a cache must not serve a compressed body to a client that did not ask for it. Be deliberate with Vary. Vary: Cookie, for example, can badly fragment shared caches.


Cache-Control Directives

These directives are the ones you will use most often:

  • max-age=<seconds>: how long the response is fresh, counted from when it was generated.
  • s-maxage=<seconds>: like max-age, but only for shared caches such as CDNs. It overrides max-age there. Browsers ignore it.
  • public: the response may be stored by any cache, including shared ones.
  • private: the response is intended for a single user. Shared caches must not store it, but the browser's private cache may.
  • no-cache: the response may be stored, but it must be revalidated with the origin server before every reuse.
  • no-store: caches must not store the response at all.
  • must-revalidate: once stale, the response must not be reused without successful revalidation.
  • immutable: the response will not change during its freshness lifetime, so the browser need not revalidate it, for example on a reload. Support varies by browser, and unsupported browsers simply ignore it.

no-cache vs. no-store

These two are confused constantly, so here is the difference:

Directive

Can the response be stored?

Can it be reused?

no-cache

Yes

Only after successful revalidation

no-store

No

Not applicable

no-cache does not mean caching is disabled. It means "store this if you like, but check with me first." Combined with an ETag, it is excellent for HTML: users get fresh content, and unchanged pages cost only a tiny 304. Use no-store for responses that should not be written to any cache.

public and private Are Not Safety Switches

private keeps a response out of shared caches, but the browser can still store it. If data is sensitive enough that it should not be stored on the device at all, use no-store.

public does not make a response safe to cache. It only widens who may store it. Never add public to a response containing user-specific or sensitive data.


Freshness vs. Validation

These are two separate ideas that work together.

Freshness answers: "Can I reuse this without asking the server?" It is controlled by max-age, Expires, or heuristics.

Validation answers: "My copy is stale, is it still correct?" It uses validators (ETag and Last-Modified) to ask the server without downloading the body again.

Consider a response with Cache-Control: max-age=600 and an ETag:

  • At 5 minutes: the response is fresh. The browser reuses it with no request.
  • At 11 minutes: the response is stale. The browser sends a conditional request with the stored ETag.
  • If unchanged, the server replies 304 Not Modified. The cached copy becomes fresh again.
  • If changed, the server replies 200 OK with the new body and new validators.

Without validators, a stale response forces a full download every time. With them, staleness is cheap.

If you want a deeper look at this mechanism in a Rails context, CodeCurious has a dedicated article on HTTP caching with ETags and Last-Modified.


Conditional Requests and 304 Responses

A conditional request is a request that includes a precondition. For caching, the browser uses two headers:

  • If-None-Match: carries the stored ETag.
  • If-Modified-Since: carries the stored Last-Modified date.

A conditional request looks like this:

GET /articles/browser-caching HTTP/1.1
Host: codecurious.dev
If-None-Match: W/"a91f3c"
If-Modified-Since: Tue, 03 Nov 2026 09:12:00 GMT

If the resource has not changed, the server replies without a body:

HTTP/1.1 304 Not Modified
ETag: W/"a91f3c"
Cache-Control: public, max-age=0, must-revalidate

The browser keeps its stored body, updates the metadata, and renders the page. When both conditional headers are sent, If-None-Match takes precedence.

A 304 avoids retransmitting the body, which is where most bytes live. It does not necessarily eliminate server-side processing. The server (or app) still receives the request, looks up the current validator, and compares it. In a Rails app, that may involve a database query. The saving is bandwidth and rendering time, not necessarily the whole request. Freshness-based reuse (max-age) is cheaper because it avoids the request completely.


Browser Caching vs. CDN Caching


Browser cache

CDN or shared cache

Scope

One user, one browser profile

Many users

Location

User's device

Edge servers or proxies

Controlled by

Response headers

Headers plus CDN configuration

Purge on demand

No

Usually yes (purge APIs)

A CDN (Content Delivery Network) is a shared cache placed geographically close to users. It reduces the distance to your content and shields your origin from repeated requests. A browser cache removes the network trip entirely for repeat visits by the same person. They complement each other.

Policies may differ between the two. s-maxage lets you give the CDN a different lifetime:

Cache-Control: public, max-age=60, s-maxage=600

Here browsers treat the response as fresh for 1 minute, while shared caches may keep it for 10 minutes. Some CDNs also support targeted headers such as CDN-Cache-Control, or their own proprietary equivalents, but support varies, so check your provider's documentation.

The key practical difference is control. You can often purge a CDN. You cannot reach into thousands of browsers and delete their copies. That is why browser-cached content needs versioned URLs or short lifetimes, which leads to the next topic.


Cache Busting and Asset Fingerprinting

If a browser caches /assets/application.css for a year and you deploy a change, returning visitors may keep using the old file. Developers need a way to say "this is a new version."

Cache busting solves this by changing the URL whenever the content changes. The most reliable form is asset fingerprinting: embedding a hash of the file's contents in its filename.

/assets/application-2b1f9d7a.css
/assets/application-8c04e3f1.css (after editing the file)

The HTML references the new URL, so the browser sees an entirely new resource and downloads it. The old URL is never requested again.

This is why fingerprinted URLs are safe for long-lived caching. A given URL always maps to one specific set of bytes. If the bytes change, the URL changes. The old cached copy can stay valid forever, because nothing will ask for it.

Query-string versioning (app.css?v=3) can work, but some intermediaries handle query strings inconsistently, and it is easy to forget to bump the version. Content-hash filenames are more dependable. Fingerprinting only helps if the HTML that references the assets is not itself cached for a long time, since the HTML is what points to the new URLs.


Cache Strategies for Different Resources

No single policy fits every response. Match the policy to how often a resource changes and who may see it.

Versioned CSS and JavaScript

Fingerprinted files never change at a given URL, so cache them aggressively:

Cache-Control: public, max-age=31536000, immutable

One year is the conventional upper bound. Many sites use it for fingerprinted assets.

Images and Fonts

Fingerprinted images and fonts can use the same long-lived policy. For images at stable, unversioned URLs (such as user-uploaded avatars), use a shorter lifetime with validators, for example public, max-age=86400. Fonts loaded cross-origin also need appropriate CORS headers.

HTML Documents

HTML pages reference your fingerprinted assets, so they must update quickly. A common approach is no-cache plus an ETag: browsers always revalidate, and unchanged pages return a cheap 304. A short max-age is also reasonable for content that changes rarely, such as documentation.

API Responses

It depends on the data. Public, slowly changing data can use a short max-age and validators. Per-user data should use private and often no-cache. Always consider what the response contains before deciding.

User-Specific or Sensitive Content

Account pages, invoices, personal dashboards, and anything containing tokens or personal data should use no-store, and must never be marked public.

Applying one long policy to everything would serve stale HTML. Applying no-store to everything would throw away free performance. Choose per resource type.


How Browser Caching Improves Performance

Caching helps in several concrete ways:

  • Repeat visits: fresh cached assets are available instantly, with no network round trip.
  • Bandwidth: fewer bytes cross the network, which matters on metered or slow connections.
  • Latency: every avoided request removes a round trip, which can be significant on high-latency mobile networks.
  • Server workload: fewer requests reach your application, and 304 responses are far cheaper than full renders.
  • Perceived performance: pages render sooner because render-blocking CSS and JavaScript load from local storage.

For web performance metrics, caching can improve Largest Contentful Paint (LCP) and First Contentful Paint (FCP) on repeat visits, because critical resources arrive faster, and it can reduce the time spent waiting on the network overall.

However, the benefit is not automatic or universal. It depends on resource size, cache hit rate, network conditions, and how your application behaves. First-time visitors get no help from the browser cache. A page dominated by uncacheable, personalized HTML will benefit less. Metrics such as Interaction to Next Paint (INP) depend mostly on JavaScript execution, which caching does not directly fix. Measure before and after rather than assuming gains.


Configuring Browser Caching in Rails

Rails can send cache headers from controllers. First, a clarification: HTTP caching tells browsers and CDNs how to reuse a response. Fragment caching (cache in views) and Rails.cache store computed data on the server. They can be combined, but they are different tools. The browser never sees your fragment cache. For the server-side side of the story, see how fragment caching works in Ruby on Rails.

By default, Rails dynamic responses are sent with a conservative policy, typically Cache-Control: max-age=0, private, must-revalidate, and a weak ETag is added by the Rack::ETag middleware. That default is safe. Customize it when a response is safe to share.

Freshness with expires_in

expires_in sets how long a response is fresh. Place it in the controller action (for example, app/controllers/articles_controller.rb):

class ArticlesController < ApplicationController
def show
@article = Article.find_by!(slug: params[:slug])
expires_in 5.minutes, public: true
end
end

This sends Cache-Control: max-age=300, public. For five minutes, browsers and shared caches can reuse the page with no request. Use it only for content that is identical for every visitor, and accept that readers may see up to five-minute-old content.

Validation with fresh_when and stale?

fresh_when and stale? implement conditional GET using ETag and Last-Modified. This is validation, not freshness. They do not make the response fresh for any period. They let Rails return 304 Not Modified when nothing changed.

class ArticlesController < ApplicationController
def show
@article = Article.find_by!(slug: params[:slug])
fresh_when(@article, public: true)
end
end

Rails builds an ETag from the record (and, by default, the template digest), then compares it with If-None-Match. If it matches, Rails sends 304 and skips rendering. If not, the view renders normally.

Use stale? when you need to run code only for the full response:

def index
@articles = Article.published.order(published_at: :desc).limit(20)

if stale?(etag: @articles, public: true)
@featured = Article.featured.first
end
end

stale? returns false when the client's copy is current (Rails has already sent the 304), and true when a full response is needed.

You can combine both ideas. Let browsers reuse the page briefly, then revalidate:

def show
@article = Article.find_by!(slug: params[:slug])
expires_in 5.minutes, public: true
fresh_when(@article, public: true)
end

Protecting Authenticated Responses

Never send public for user-specific pages. Rails defaults to private, and you can go further for sensitive pages:

class DashboardsController < ApplicationController
before_action :require_login

def show
@account = current_user.account
response.headers["Cache-Control"] = "no-store"
end
end

expires_now is another helper, but it sends no-cache, not no-store, so it still allows storage with revalidation. Choose the directive that matches your sensitivity requirements.

Inspecting Headers

Run your app locally and check the real output:

curl -I http://localhost:3000/articles/browser-caching

Do this in production too, since middleware, proxies, and CDNs can change what you intended.


Static Asset Caching in Rails

Rails 8 uses Propshaft as the default asset pipeline. When you precompile, Propshaft gives each asset a fingerprint based on its content, so application.css becomes something like application-2b1f9d7a.css. Helpers such as stylesheet_link_tag, javascript_include_tag, and image_tag generate the fingerprinted URLs for you:

<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag "application" %>

Propshaft also rewrites asset references inside your CSS so they point to fingerprinted files. For the full picture, see Rails asset pipeline with Propshaft explained.

Because the content hash changes whenever the file changes, long cache lifetimes are safe. Configure the static file server in config/environments/production.rb:

config.public_file_server.headers = {
"cache-control" => "public, max-age=#{1.year.to_i}"
}

This applies to files Rails serves from public/, including precompiled assets. Many newly generated Rails apps already include a similar setting, but verify yours.

If a CDN or reverse proxy serves your assets, it may override these headers. Always confirm with curl -I on a real asset URL.


Configuring Cache Headers at the Server or CDN Level

Rails is not the only place to set cache headers. Web servers, reverse proxies, and CDNs can add or override them. This is infrastructure configuration, separate from your Rails code.

Here is an Nginx example for proxied, fingerprinted assets:

location /assets/ {
proxy_pass http://rails_app;
proxy_hide_header Cache-Control;
add_header Cache-Control "public, max-age=31536000, immutable" always;
}

proxy_hide_header removes the upstream header so you do not end up with duplicates. Without it, add_header would append a second Cache-Control header, which causes contradictory policies.

Keep these cautions in mind:

  • Only apply long lifetimes to paths containing fingerprinted files, such as /assets/.
  • Do not use broad rules that set long caching on HTML or API routes.
  • CDNs often have their own "edge TTL" settings that can override or ignore origin headers. Read your provider's documentation and test the actual output.
  • Make Rails the source of truth where practical, so policy lives near the code that understands which responses are public.

Practical Example

Consider a public blog article page at /articles/browser-caching that loads one stylesheet, one script, and one hero image:

Resource

Policy

/articles/browser-caching (HTML)

public, max-age=0, must-revalidate with an ETag

/assets/application-2b1f9d7a.css

public, max-age=31536000, immutable

/assets/application-8c04e3f1.js

public, max-age=31536000, immutable

/assets/hero-9f8e7d6c.webp

public, max-age=31536000, immutable

The HTML policy comes from fresh_when(@article, public: true). The asset policy comes from the static file server settings shown earlier.

First visit. The browser has nothing stored. It requests the HTML (200, with an ETag), then the CSS, JavaScript, and image (all 200). Every response is stored according to its headers.

Second visit, nothing changed. The browser requests the HTML with If-None-Match. Rails sees the ETag matches and returns 304 Not Modified with no body. The three assets are still fresh, so the browser makes no requests for them at all. The page renders from the local cache plus a single tiny request.

After a deploy that changes the CSS. Propshaft produces application-5d3a77b0.css. The HTML changes (it now references the new URL), so its ETag no longer matches and the server returns a full 200. The browser fetches the new CSS, while the JavaScript and image URLs are unchanged and still served from cache. Users get updated styling immediately, without stale files and without re-downloading everything.


Testing Browser Caching

Browser Developer Tools

In Chromium-based browsers, open DevTools and go to the Network panel:

  • The Status column shows 200 for fresh downloads and 304 for successful revalidations.
  • The Size column often shows labels such as "(memory cache)" or "(disk cache)" when a response was served locally. Wording varies by browser.
  • Click a request and open the Headers tab to see the response and request headers, including Cache-Control, ETag, and If-None-Match.
  • Be careful with the Disable cache checkbox. It bypasses caching while DevTools is open, so turn it off when testing real behavior.

Also remember that a hard reload deliberately bypasses the cache, so test by navigating to the page normally instead.

curl

curl -I sends a HEAD request and prints only headers:

curl -I https://codecurious.dev/assets/application-2b1f9d7a.css

Some servers treat HEAD differently from GET. To inspect the headers of a real GET without printing the body:

curl -s -D - -o /dev/null https://codecurious.dev/articles/browser-caching

To test conditional requests, replay the ETag you received:

curl -s -D - -o /dev/null \
-H 'If-None-Match: W/"a91f3c"' \
https://codecurious.dev/articles/browser-caching

A 304 Not Modified status confirms validation works. To check Vary, add -H "Accept-Encoding: gzip" and compare.

Test against production URLs, not only localhost, since proxies and CDNs sit between users and your app.


Common Browser Caching Mistakes

  • Caching personalized content publicly. Adding public to a page that shows account data can cause it to be stored in a shared cache and served to someone else.
  • Long lifetimes on unversioned assets. A one-year max-age on /app.css means users may be stuck on old code for months.
  • Confusing no-cache with no-store. no-cache still stores the response. If data must not be stored, use no-store.
  • Forgetting invalidation. If you cache something for an hour, you cannot recall it from browsers. Plan for how updates will be delivered.
  • Contradictory headers. Combining no-store with max-age=3600, or duplicating Cache-Control from both Rails and Nginx, produces unpredictable behavior.
  • Ignoring Vary. Serving compressed or localized variants without Vary can cause the wrong version to be reused.
  • Caching error responses unintentionally. Check what your server sends with 404 and 500 responses.
  • Trusting only a hard reload. It bypasses the cache, so it does not show what returning users experience.

Best Practices

Use this checklist as a starting point and adapt it to your application:

  • Fingerprint all CSS, JavaScript, images, and fonts, and cache them with long lifetimes.
  • Serve HTML with revalidation (no-cache or max-age=0, must-revalidate) plus an ETag or Last-Modified.
  • Use fresh_when or stale? for public pages whose changes can be detected cheaply.
  • Use expires_in only when brief staleness is acceptable.
  • Mark user-specific responses private, and use no-store for sensitive ones.
  • Never add public to a response without confirming it contains no user-specific data.
  • Send Vary for any request header that changes the response.
  • Avoid duplicate or contradictory Cache-Control headers across Rails, proxies, and CDNs.
  • Give CDNs their own lifetime with s-maxage where it makes sense, and know how to purge.
  • Validate headers in production with DevTools and curl, after every infrastructure change.
  • Measure real repeat-visit performance rather than assuming improvement.

Conclusion

Browser caching reduces unnecessary downloads by letting browsers reuse responses they already have, or confirm cheaply that those responses are still valid. Fresh responses avoid the network entirely, and validated responses use 304 Not Modified to avoid resending the body.

For developers, the recipe is straightforward: fingerprint your assets and cache them for a long time, revalidate HTML with validators, protect personalized responses with private or no-store, and verify everything with real tools. Rails 8.1 gives you good defaults, plus expires_in, fresh_when, and stale? when you need more control, and Propshaft makes fingerprinted assets automatic.

Start by inspecting the headers your own app sends today. You may find some quick wins.

Jean Emmanuel Cadet
Written by Jean Emmanuel Cadet
Jean Emmanuel is a Full-Stack Software Engineer specializing in Ruby on Rails and the modern Rails ecosystem. He builds scalable, maintainable web applications using Rails, Hotwire (Turbo & Stimulus), PostgreSQL, and SQLite, with a focus on fast, dynamic user experiences. Through CodeCurious, he shares practical lessons, development insights, and real-world solutions for modern developers.

Code. Learn. Grow.

A friendly newsletter sharing dev tips, lessons, and wins from my journey.