On this page
Cache max-age
Cache max-age = time dependencies
Cache max-age is analogous to HTTP's
Cache-Control
header'smax-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 seconds100
means cacheable for 100 seconds0
means cacheable for zero seconds, i.e. not cacheable\Drupal\Core\Cache\Cache::PERMANENT
(value-1
) meanscacheable 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-age
does not work for anonymous users and the Drupal core Page Cache module. For example, see these issues:
- #2352009: [pp-3] Bubbling of elements' max-age to the page's headers and the page cache
- #2449749: Add #cache['downstream-ttl'] to force expiration after a certain time and fix #cache['max-age'] logic by adding #cache['age']
- #2835068: PageCache caching uncacheable responses (violating HTTP/1.0 spec) + D8 intentionally disabling HTTP/1.0 proxies = WTF
- #2951814: Improve X-Drupal-Cache and X-Drupal-Dynamic-Cache headers, even for responses that are not cacheable
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
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion