Cache max-age

Last updated on
18 May 2017

Cache max-age = time dependencies

Cache max-age is analogous to HTTP's Cache-Control header's max-age directive

Why?

Cache max-age provides a declarative way to create time-dependent caches.

Some data is only valid for a limited period of time, in that case, you want to specify a corresponding maximum age. However, in Drupal 8 core's case, we don't have any data that is valid for only a limited period of time; we typically cache permanently (see below) and rely entirely on cache tags for invalidation.

What?

A cache max-age is a positive integer, expressing a number of seconds.

Cache max-ages are passed around as individual integers, because a given cache item can only logically have a single max-age.

Examples:

  • 60 means cacheable for 60 seconds
  • 100 means cacheable for 100 seconds
  • 0 means cacheable for zero seconds, i.e. not cacheable
  • \Drupal\Core\Cache\Cache::PERMANENT means cacheable forever, i.e. this will only ever be invalidated due to cache tags. (In other words: ∞, or infinite seconds.)

So if you for example want to prevent a rendered block from being cached, you should specify max-age=0 on it.