Drupal: cache tags for all, regardless your backend

Matt Glaman
7 min readAug 22, 2022

Phil Karlton is quoted as having said, “There are only two hard things in Computer Science: cache invalidation and naming things.” As someone who suffers horribly from the latter, I’m glad Drupal’s caching APIs make the former a breeze. The long short of it is that caching of data improves performance by not having to perform the same operations multiple times after it has been done the first time until you need to re-run that operation again. It involves some storage (static variable in memory, memory backend storage, or the database.) Generally, you store the data with a given identifier for later retrieval, the actual data to be cached for later reuse, and possibly an expiration time for automatic invalidation.

And that’s where cache invalidation is hard. What if you need a cache object to be invalidated before its automatic invalidation? Or what if the cache is set to be permanent? First, you need to know when and how to invalidate something. This may get even more complicated if your when means you need to invalidate multiple cache objects. That’s where cache tags are helpful and allow invalidating a group of cache objects without knowing their identifiers.

Drupal’s 8.0.0 release introduced cache tags to the Cache API. Previously Drupal supported using wild card cache identifiers for bulk cache invalidation. Thanks to sdboyer, catch, and everyone else who made this possible!

Cache tag support

The problem After [#81461] we are still left with a very monolithic API for clearing caches on content changes. cache_clear_all() is hard coded to the page and block caches. Node, user, taxonomy and many other modules call cache_clear_all() after any form submission — even though the entity in question may not even be shown on any of the pages or blocks that were cached. This can result in a very low cache hit rate especially on sites with lots of content getting posted.

Cache tag support

What is a cache tag?

--

--

Matt Glaman

PHP software engineer, open source contributor, and speaker