Controlling Drupal 8 Caching

Category
Drupal Version

Drupal 8 has a much more sophisticated and ultimately aggressive caching system.  While this is supposed to be a good change, sometimes it really gets in your way.  The recently released BigPipe caching engine is supposed to help with some common caching problems, but it's not ready for everyone to be using just yet.

Below are some technical tricks for gaining a bit of control over the standard caching system.


Module Generated Blocks

A lot of documentation points out that you can disable the caching of a block generated by a module by adding the following to the render hash array:

  ['#cache']['max-age'] = 0

Unfortunately, that doesn't solve the whole problem, as there's both block caching and anonymous page caching.  Just adding the above will keep the block fresh for logged-in users, but anonymous (outside) visitors will still see the last cached version of the page that the block is placed on, including the version of the content in the block at the time the page was cached.  So, the only way to make a block always show the latest information to anonymous users is by using the "kill switch" method of adding the following like to your render function somewhere before it returns the render hash array:

  \Drupal::service('page_cache_kill_switch')->trigger();

Of course, be aware that this will prevent caching of any part of any page that the block is placed on, but at the moment, there doesn't seem to be a better way of presenting always up-to-date block content.

Module Generated (Dynamic) Pages

The only approach that seems to work reliably is the "kill switch" method, triggered by adding the following like to your render function somewhere before it returns the render hash array:

  \Drupal::service('page_cache_kill_switch')->trigger();

Dynamic Route Caching

You can also play with adjusting the caching options on a route through adding the following to any route in a module's routing.yaml file:

  options:
    no_cache: TRUE