Cache max-age

Last updated on
3 May 2022

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 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 (value -1) 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.

Example for most render arrays:

$build['#cache']['max-age'] = 0;

Example in a function:

\Drupal::cache()->set('my_cache_item', $school_list, \Drupal::time()->getRequestTime() + (86400));

If you want to change block max-age to 0 then you must implement getCacheMaxAge method.

Limitations of max-age

Unfortunately, max-agedoes not work for anonymous users and the Drupal core Page Cache module. For example, see these issues:

Until these (and perhaps other) issues are resolved, beware that setting max-age on a render array included in a page is insufficient to ensure that anonymous users will see a new version after the max-age as elapsed. In the meanwhile, the Cache Control Override contributed module tries to mitigate the problems. You might also have more luck setting a custom cache tag on pages with time-dependent content and invalidating those cache tags manually via hook_cron(). Good luck!

Help improve this page

Page status: No known problems

You can: