Here's a simple "Hello World" controller. It's working correctly, except for the "max-age" statement. The request returns a Drupal cache hit every time after the first request, rather than just for 5 seconds. I've tried to find a simple example of how to do this but haven't had much luck. If anyone could help, that would be very much appreciated.

 * @file
 * Contains \Drupal\hello_world\Controller\HelloController.

namespace Drupal\hello_world\Controller;
use Drupal\Core\Controller\ControllerBase;

class HelloController extends ControllerBase {

  public function content() {

    return array(
      '#type' => 'markup',
      '#markup' => $this->t('Hello, World!'),

      '#cache' => array("max-age" => 5),
  • Are you sure you're not exceeding 5 seconds in the time it takes you to make the additional request? What happens when you use a value such as 60? – mradcliffe Feb 15 '16 at 16:30
  • As it's a very fast "hello world" page, it's not exceeding 5 seconds. I'm getting cache HITS (page IS being cached), both before and after 5 seconds. – rangfu Feb 15 '16 at 19:35

The page cache module doesn't respect max-age. Unfortunate but the problem is that Drupal usually contains elements like forms that are by default set to max-age 0, but that only applies to authenticated users most of the time.

To invalidate the page cache, you need to use cache tags, which you invalidate when something changes.

If that doesn't work, you can try to set the Expires header on the response, but for that you either need to return a Response object or alter it in an event when it has been created.

Note: max-age does work for dynamic page cache (authenticated users), rendered blocks, views, entities and so on. Just not for the anonymous page cache.

| improve this answer | |
  • thank you very much for the info, that is really useful. – rangfu Feb 15 '16 at 19:31
  • Can you give a code example of using the cache tags? And when using cache tags, should you NOT use '#cache' => array("max-age" => x) ? – Anders8 May 18 '16 at 20:49
  • drupal.org/developing/api/8/render/arrays/cacheability has examples, see also the Cache tags link at the end. You can mix contexts, tags and max-age in any way you see fit. – Berdir May 18 '16 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.