cache-guide
cache-guide/cache-control/max-age

cache-control: max-age

max-age = N: This directive is your key to keeping your cached content fresh. It controls how long the response data remains fresh after it's generated.

Understanding max-age

In the context of HTTP caching, understanding max-age is crucial. When you define max-age=N, you're essentially specifying how long the response data will stay fresh after it's been generated by the origin server. In simpler terms, it means the data remains valid and can be used from the cache for up to N seconds from the moment it was first created by the server. This helps ensure that users receive up-to-date content while minimizing the need to re-fetch data from the server.

  • When you set max-age = N, it means the response data remains fresh until N seconds after it's generated.
  • Note that "generated" refers to when the origin server initially generated the response.

Calculating freshness

In the context of browser caching, freshness is a measure of how long a cached response remains valid and up-to-date. It's determined by the max-age header in the HTTP response, which sets the maximum time a response can be considered fresh. If the response's current-age hasn't exceeded this freshness-lifetime, the data is still considered fresh and can be used from the cache.

  • Let's say your browser cache receives a response with a max-age header set to max-age=600. This means that the cached data remains fresh until it's 10 minutes old.
  • In this context, "fresh" means that a response's current-age has not exceeded its freshness-lifetime, which, in this case, is the 600-second value we assigned to max-age. You can visualize this freshness using the following formula:

The Age header and intermediate caches

When a request is made for a resource, it may pass through one or more intermediate caches (e.g., caching proxies, CDNs) before reaching the client. Each of these intermediaries may store a cached copy of the resource. As the response passes through each intermediary, the Age header is incremented to reflect the time spent in that cache.

  • If there are additional layers between the origin server where the response was generated and the destination client, the Age header comes into play.
  • The Age header value represents the time the response spent at each step in this journey.
  • An Age header value of 0 typically indicates that the content was retrieved directly from the origin server.
response_is_fresh = (freshness_lifetime > current_age)

What does it look like?

Now that we've explained max-age, let's view a sample request-response cycle involving this header:

client
cache
server
HTTP Message Type: request

request: GET /script-v1.js, GET /styles-v1.css, GET /cats-v1.jpg

What's happening?
Client requests a script, a stylesheet, and an image.