Loading...


Related Products


Date Published: March 8, 2022

Setting up custom cache tags to reduce Varnish misses on views page

To prevent a view page from being invalidated by all node changes, it may be desired to set up custom cache tags. 

If a site has hundreds of views and nodes of content, invalidating the caches of these views can add performance issues because every node change invalidates every view. As a result, the view page will get more Varnish cache misses than hits.

To improve the Varnish cache hit-rate on views pages, use the Views Custom Cache Tag module:

Drupal 8 automatically adds cache tags to every view so that their content can be invalidated when any of the content changes... However, Drupal 8 only has a single list cache tag for every entity type. Every view that lists nodes is tagged with node_list and will be invalidated when a node is added, changed or deleted.

This module replaces the hardcoded cache tag with a form that allows developers to set different cache tags based on configuration of the view.

To use this module and set up custom cache tags:

  1. Edit the View.
  2. Go to Advanced and click on "Caching: Tag based".
  3. Select "Custom tag based".
  4. Insert a custom cache tag, e.g. node:type:page.
  5. Save the view.

Next, use hook_node_presave() in a helper module or custom module:

// For hook_ENTITY_TYPE_presave.
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityInterface;

/**
* Implements hook_ENTITY_TYPE_presave().
*
* Invalid cache tags for node lists.
*/

function kb_invalidate_custom_cache_tags_node_presave(EntityInterface $entity) {
$cache_tag = 'node:type:' . $entity->getType(); Cache::invalidateTags([$cache_tag]); }

This hook will be fired each time a node is created or updated to invalidate the cache of only the specified node types.

Did not find what you were looking for?

If this content did not answer your questions, try searching or contacting our support team for further assistance.

Back to Section navigation
Back to Site navigation