Editorial illustration; the request, context and cache labels are representative examples, not a live Drupal installation.
A Drupal site can return a 200 OK in 30 milliseconds and still be completely broken. An editorial menu leaks to an anonymous visitor, a Bahasa Melayu heading shows up on the English route, or a dashboard link disappears for a moderator because an unprivileged user warmed the cache first.
Those bugs almost always come down to missing or misjudged cache contexts. Drupal’s Cache API splits caching into three separate questions: tags say what invalidates cached data when content changes, max-age says how long it stays valid, and contexts say which request variations must get their own separate cached copy.
Choosing the narrowest context that is still right
When a render array depends on something from the current request, you attach cacheability metadata right where that decision is made—not as an afterthought in a theme preprocess hook.
Suppose a custom block displays a “Review pending submissions” link only to users with a specific permission, and the label is translated across site languages. You do not want to vary the block by user (which creates one cache entry per logged-in account) when user.permissions and languages:language_interface already capture the exact inputs:
use Drupal\Core\Cache\Cache;
$build = [
'#markup' => $has_access ? $this->t('Review pending submissions') : '',
'#cache' => [
'contexts' => [
'user.permissions',
'languages:language_interface',
],
'tags' => ['node_list'],
'max-age' => Cache::PERMANENT,
],
];
Notice what happens if you guess wrong in either direction:
- Too narrow or missing: You omit
user.permissions. Whoever hits the page first sets the cached HTML for everyone else until the cache clears. - Too broad: You drop
useronto a block shared across 5,000 members just because it feels “user-related.” Now Drupal stores 5,000 identical copies incache_render, blowing up cache storage and killing your hit rate.
If a component genuinely varies per individual user—like a greeting showing their own name or unread count—isolate that tiny fragment into a #lazy_builder callback so Drupal’s BigPipe and auto_placeholder_conditions can placeholder it instead of ruining cacheability for the whole page.
Reading cacheability headers in local development
Guessing whether metadata bubbled up properly wastes hours. Turn on Drupal’s debug cacheability headers in sites/default/development.services.yml during local work:
parameters:
http.response.debug_cacheability_headers: true
Rebuild the container once with drush cr, then inspect the response headers in curl -I or your browser DevTools Network tab:
X-Drupal-Cache-Contexts: Lists every context that bubbled up to the final page response.X-Drupal-Cache-Tags: Lists every invalidation tag attached to the page.X-Drupal-Cache-Max-Age: Shows the shortest max-age across all rendered components (-1means permanent).
Test by changing one variable at a time. Load the page as an anonymous visitor, then as a regular authenticated user, then as a moderator, and across a second language if multilingual is enabled. Do not rely on running drush cr before every page load—a correct cache setup stays accurate after the cache is warm, not just on the first cold hit.
Why Drupal contexts alone won’t save you behind a CDN
Drupal’s internal Page Cache and Dynamic Page Cache understand user.permissions and route natively. External reverse proxies—Varnish, Nginx microcaching, or Cloudflare sitting in front of your origin—do not.
An edge CDN only keys responses on standard HTTP properties like URL, query string, cookies, or Vary headers. If your Drupal site renders personalized content for anonymous visitors based on a custom cookie or GeoIP header, and you only add a Drupal cache context without configuring the edge cache key or bypassing the edge cache for that path, Cloudflare will happily serve the first visitor’s cached HTML to everyone else in the region.
For authenticated traffic, Drupal’s session cookie (SESS* / SSESS*) normally signals Varnish or Cloudflare to bypass edge caching and let Drupal’s Dynamic Page Cache handle the per-role or per-permission assembly. Verify that end-to-end through your actual staging domain, not just localhost, so you catch edge-layer mismatches before production.
For adjacent workflows, see how to troubleshoot Drupal cache without clearing everything and how Drupal Search API design begins with an index.
Mistakes that keep showing up in code reviews
- Treating
tagsas a substitute forcontexts(invalidating on node save does not fix two roles seeing each other’s markup). - Setting
max-age => 0on a block to “fix” stale personalization instead of adding the right context or lazy builder, which silently disables caching up the entire render tree. - Testing only as UID 1 (
admin), which bypasses permission checks and hides brokenuser.permissionsmetadata. - Forgetting to merge cacheability with
CacheableMetadata::createFromRenderArray()or$renderer->addCacheableDependency()when pulling data from entities or config objects in custom controllers.
Cache correctness is really just data-dependency hygiene: name the exact input that changes the markup, attach the narrowest context at the source, and verify the warmed response through the full proxy stack.