Vitor M
Vitor M

Reputation: 967

How to tell browsers to revalidate cached asset only once every X minutes?

TL;DR: How to implement a caching like Cache-Control: public,must-revalidate, but somehow tell the browser to revalidate only once every, lets say, 30 minutes, instead of on every single request?

Long Version:

I'm serving a few js and css files, and I want the users to always keep the local cache updated, but with some freedom. Browsers should be able to cache the file locally, but there should be no need to revalidate on every single request. After the first 304 response, for example, it would be ok to keep using the already locally cached file for another 30 minutes: there would be no need for the browser to check the freshness again after the user navigates to the very next page.

I've read a few articles about how to implement a caching that works like that but no success.

I understand the 304 request is quite fast (I'm using a CDN btw), as the response body is empty, but still, the browser still has to wait a few miliseconds, and if 4-5 request such as these are made, browsers already start queuing up these revalidation requests.

The closest i got was: Cache-Control: max-age=1800,public,must-revalidate

The browser will cache the asset for the initial 30 minutes, but after it becomes stale, browser will start revalidating every single time. Is there any way around that?

Sources: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control https://support.cloudflare.com/hc/en-us/articles/115003206852-Origin-Cache-Control

Upvotes: 1

Views: 386

Answers (1)

TomDane
TomDane

Reputation: 1066

If the revalidation succeeds, it will cache it for another 30 minutes. See RFC 2616 10.3.5:

If a cache uses a received 304 response to update a cache entry, the cache MUST update the entry to reflect any new field values given in the response.

The flow is like this:

  • It will be cached for 30 minutes.
  • The max-age will expire.
  • It will be forced to re-validate.
  • It will update the max age with a new 30 minutes.

See also Max-age and 304 Not Modified Processing

Upvotes: 1

Related Questions