Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Deployment and Performance

Caching and Cache Tags

Understand Drupal's cache system: page cache, dynamic page cache, render cache, cache tags, contexts and max-age, invalidation in code and a runnable tag-invalidation stand-in.

Drupal builds pages from many pieces: entities, fields, menus, blocks, views. Generating all of that on every request would be slow, so Drupal caches almost everything. The hard part of caching is not storing data, it is knowing when the stored copy is wrong. Drupal solves it with cache metadata that travels with every render array: tags, contexts and max-age. If you learn this vocabulary, you can make a site fast without ever serving stale or wrong content.

Drupal cannot run on this site, so the PHP is read-only. The TryIt blocks build a miniature tag-based cache.

The cache layers

  1. Internal Page Cache (module page_cache): caches complete responses for anonymous users. Very fast, can be skipped if the page varies per visitor.
  2. Dynamic Page Cache: caches the page for everyone (including logged-in users), leaving parts that vary (per user, per session) as placeholders filled in at the end, a technique called auto-placeholdering or big pipe.
  3. Render cache: caches individual render arrays (blocks, entities, fields) in the cache.render bin.
  4. Other bins: cache.config, cache.entity, cache.discovery, cache.data, backed by the database by default and by Redis or Memcache in production.
  5. Outside Drupal: a reverse proxy or CDN (Varnish, Cloudflare, Fastly) using the same tags in an X-Drupal-Cache-Tags header.

On production, also enable CSS/JS aggregation and OPcache, and keep Twig debug off.

Cache metadata

Every render array can include a #cache key:

PHP
$build = [
  '#markup' => $this->t('Hello, @name', ['@name' => $name]),
  '#cache' => [
    'keys' => ['tutorial_notes', 'greeting'],
    'contexts' => ['user'],
    'tags' => ['user:' . $account->id(), 'config:system.site'],
    'max-age' => 3600,
  ],
];
  • Cache tags answer "what is this made from?" Examples: node:5 (node 5), node_list (any listing of nodes), node_list:article, user:3, config:system.site, taxonomy_term:12. When one of these things changes, Drupal invalidates every cached item carrying that tag.
  • Cache contexts answer "what does this vary by?" Examples: user, user.roles, user.permissions, languages:language_interface, route, url.path, url.query_args:page, theme, session. A separate copy is stored for each different value of the context.
  • Max-age answers "how long is it good for?" in seconds. Cache::PERMANENT (-1) means until invalidated. 0 means never cache, and it bubbles up: one max-age: 0 element makes the whole page uncacheable, so avoid it.
  • Keys make an item cacheable as its own entry in the render cache.

Metadata bubbles up: if a block inside a page uses user context and the node:5 tag, the page inherits both. That is what makes the system correct, but also why careless metadata (for example session or max-age: 0) can destroy page caching.

Node.js Stand-in: cache tags invalidate dependents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Saving node 5 invalidated its own render, and the listing that depends on articles, but not node 6. That precision is the reason Drupal can cache aggressively.

Using contexts correctly

If the output of a block changes per language or per role, add the context. If you forget it, the first visitor's version is served to everyone. The stand-in below shows why: the cache key includes the context values.

Node.js Stand-in: contexts split cache entries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Invalidating in code

When your module changes data that other pages show, invalidate the matching tags:

PHP
use Drupal\Core\Cache\Cache;

// Your custom data changed:
Cache::invalidateTags(['tutorial_notes_list']);

// Or with the service:
\Drupal::service('cache_tags.invalidator')->invalidateTags(['node:' . $nid]);

Entities already provide their tags: $entity->getCacheTags() returns ['node:5'], and getListCacheTags() the list tags. When you build output from an entity, add it as a dependency so you never forget:

PHP
$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($build, $node);

Entity and config objects, access results and CacheableMetadata implement the same interface (CacheableDependencyInterface), so you can merge metadata from several sources.

Cache API for your own data

For expensive calculations use a cache bin directly:

PHP
$cid = 'tutorial_notes:stats:' . $uid;
if ($cache = \Drupal::cache()->get($cid)) {
  return $cache->data;
}
$stats = $this->expensiveStats($uid);
\Drupal::cache()->set($cid, $stats, Cache::PERMANENT, ['user:' . $uid, 'tutorial_notes_list']);
return $stats;

Inside a class, inject cache.default instead of calling \Drupal::cache() (DI).

Debugging caching

  • Add http.response.debug_cacheability_headers: true in services.yml to get X-Drupal-Cache, X-Drupal-Dynamic-Cache, X-Drupal-Cache-Tags and X-Drupal-Cache-Contexts headers.
  • X-Drupal-Dynamic-Cache: UNCACHEABLE points to a max-age: 0 somewhere (often a form or a custom block without metadata).
  • Use drush cr to rebuild everything. In production prefer targeted invalidation to full rebuilds, which cause a stampede of slow requests.

Common mistakes

  • Using \Drupal::request() or $_GET in a block without the url.query_args context.
  • Setting max-age: 0 to "fix" stale data instead of adding the right tag.
  • Calling drupal_flush_all_caches() on a busy site.
  • Ignoring the cache tags header at the CDN, so purges do not reach the edge.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do cache tags describe?

    Tags name dependencies such as node:5; changing them invalidates the item.
  2. 2. A block shows content per user role. What must it declare?

    The context makes Drupal store a separate copy per role set.
  3. 3. What is the effect of max-age 0 on one element in a page?

    Cache metadata bubbles to the parent render arrays.
  4. 4. How do you refresh cached output after your module changes its own data?

    Tag-based invalidation targets exactly the affected items.

Summary

  • Drupal caches pages, dynamic pages, render arrays and data bins.
  • Cache tags (what), contexts (vary by) and max-age (how long) bubble up from fragments to pages.
  • Invalidate with tags, not full cache rebuilds; avoid max-age 0.
  • Use CacheableMetadata, addCacheableDependency() and the cache bins for custom data.
  • Enable debug headers to see what is cached.

Next: Performance Tuning and Updates