Drupal Cache Contexts and Tags: Stop Stale or Shared Render Output

A custom Drupal block shows the right message to an administrator but the wrong message to an anonymous visitor. Another block stays stale after its referenced content changes. These are often cache metadata problems: Drupal needs to know what makes output vary and what changes should invalidate it.

This guide is for Drupal developers returning render arrays from controllers, blocks or components. It focuses on two decisions: use a cache context when output differs by request conditions, and use a cache tag when output depends on data that can change. Cache max-age controls how long an item may be cached; it does not replace either dependency.

Editorial illustration of Drupal cache contexts varying output by user and cache tags invalidating output after content changes

Editorial illustration: contexts vary a cache item; tags let Drupal invalidate it when dependent data changes.

Summary

  • Add a cache context when the same data should render differently for different request contexts, such as user permissions.
  • Add cache tags for entities or configuration whose changes should invalidate the output.
  • Keep max-age as a separate lifetime decision, and test with different users and updated content.

Three questions before adding metadata

Ask what changes the output, what source data it depends on, and how long the result can remain valid. The answers usually map to cache contexts, cache tags and max-age respectively.

For example, a block that lists recent news nodes depends on those node records. If it shows unpublished items only to editors, it also depends on the viewer’s permissions. If the list is otherwise stable for a short period, max-age may bound its lifetime. Setting only max-age could leave permissions unaccounted for; setting only a user context may create too many variants and still fail to invalidate after an article is edited.

Vary the output with a context

Cache contexts describe request conditions that affect the rendered result. They are similar in purpose to HTTP’s Vary header: a cached result must not be reused where the relevant context differs. Common examples include the active user, permissions, language or URL, but choose the narrowest context that actually matches the logic.

A custom block whose text depends on whether the current user has a permission can declare the dependency in its render array:

return [
  '#theme' => 'item_list',
  '#items' => $items,
  '#cache' => [
    'contexts' => ['user.permissions'],
  ],
];

The context does not run access control for you. It tells Drupal that the rendered result varies by that condition. Your code must still check access correctly. Avoid using a broad context such as the full user identity when permission differences are enough; a broader context can fragment the cache and reduce reuse.

Invalidate output with tags

Cache tags identify data dependencies. If a render array depends on a node, term or configuration object, Drupal can invalidate cache entries carrying the relevant tag when that data changes. A simple render array might include:

return [
  '#markup' => $summary,
  '#cache' => [
    'tags' => ['node:42'],
  ],
];

In application code, prefer obtaining cacheability metadata from the entity or object rather than writing a guessed tag string. Drupal entities expose cache tags, and render arrays can bubble cacheability metadata up to their parents. This matters when a component is nested: a child’s dependency should be reflected in the final response.

If output depends on a query over a changing set—such as “all published articles in this category”—tagging one entity may not cover changes to membership. Use the cache metadata supplied by the relevant entity query, view or data source, or define a deliberate invalidation strategy. Test additions, removals and edits, not just updates to one existing record.

Set a realistic max-age

Max-age is the maximum time a cache item may remain valid, in seconds. 0 disables caching for that item; Cache::PERMANENT expresses no time-based expiry. Permanent does not mean immutable: tags can still invalidate the item.

Use the longest safe lifetime that fits the data and invalidation mechanism. Setting everything to zero hides missing metadata and can harm performance. Setting everything permanent without correct tags risks stale output. When an external data source cannot trigger Drupal invalidation, a finite max-age may be a reasonable fallback, but explain the delay it permits.

Combine metadata instead of overwriting it

Render arrays often inherit metadata from children, entities and plugins. If custom code replaces #cache wholesale, it can discard dependencies added earlier. When merging cacheability data, use Drupal’s cacheability APIs such as CacheableMetadata and Cache::mergeTags() where appropriate, then apply the merged metadata to the render array. Follow the API for the Drupal version your project supports.

A useful review checklist for a component is:

  1. Does the output differ by user, permission, language, route or query argument?
  2. Which entities and configuration objects contribute data?
  3. Can a changing collection gain or lose members?
  4. Which metadata already bubbles from child render arrays?
  5. Is a time limit needed because an external dependency cannot invalidate Drupal’s cache?

Test the bug, not just the page

Use at least two accounts with different permissions and compare anonymous versus authenticated output. Edit the source entity, add a new matching item, remove one, and repeat without manually clearing all caches. If a manual cache clear fixes the display but routine edits do not, the tag or collection dependency is likely incomplete.

Inspect the rendered result and response cache behavior in a development environment. Avoid relying only on one administrator browser session: permission contexts can make a bug invisible to the developer who built the block. Also review reverse proxies and CDN rules if the response leaves Drupal; application cache metadata and HTTP cache policy are related but not interchangeable.

My Take

When a Drupal cache bug appears, disabling cache can be a useful short diagnostic, but it is rarely a complete fix. Naming the exact varying condition and data dependency usually reveals the missing metadata and keeps valid cache hits for everyone else. A small test matrix—anonymous, editor, changed node, newly added node—often catches more than repeatedly clearing caches by hand.

The same cache metadata matters when adding dynamic blocks that use Drupal’s lazy builder. For a separate performance concern, see how Drupal render-cache metadata bubbles through arrays.

Conclusion

Use contexts to vary output by request conditions, tags to invalidate it when dependent data changes, and max-age to cap its lifetime. Keep those responsibilities separate, preserve metadata as render arrays bubble, and test both user differences and content changes. The next time a custom block is stale or shared incorrectly, start by listing its dependencies.

Sources