Skip to the content
Documentation
Help Start
Reading in:
  • German: 9,212 of 9,212 pages
About the help in other languages
All help pages

Cache tags and invalidation

What this is. Every cache between Exponential's content and a reader's screen, and how each one is kept current: the server's response cache for persisted queries, ETags and 304, HTTP caching headers, the purge tags in…

Download as PDF

Address: https://doc.exponential.earth/learninminutes/exphelp/viewer/headless/caching.md

On this page

Cache tags and invalidation

What this is. Every cache between Exponential's content and a reader's screen, and how each one is kept current: the server's response cache for persisted queries, ETags and 304, HTTP caching headers, the purge tags in X-Exponential-Cache-Tags, CDN purging by tag, and the caches of the SDK and of front-end frameworks.

When to use it. When you design the caching of a front end, put a CDN in front of the API or of your pages, or find out why a page shows old content.

Quick example: every answer of a query names what it showed.

EXP=https://www.example.com
curl -s -D - -o /dev/null "$EXP/api/graphql" -H 'Content-Type: application/json' \
  -d '{"query":"{ node(id: 89) { name children(limit: 2) { nodes { name } } } }"}' | grep -i -E 'cache-tags|etag|cache-control'
# Cache-Control: private, no-store
# X-Exponential-Cache-Tags: ez-all c87 ct43 s1 l89 pl2 p2 p89 pl89 c90 ct45 l92 p92 c128 l130 p130
# ETag: W/"2f0229ecf10c2b8f137da5dbf8ac24d4"

When the object 90 is published again, its event carries objectId: 90, nodeIds: [92], parentNodeIds: [89]; purging c90, l92, pl89 and l89 drops this answer (it carries c90 and pl89).

Contents

  1. The caches, from the database to the screen
  2. The response cache
  3. ETags and 304
  4. Cache-Control and shared caches
  5. Purge tags
  6. From an event to the tags to purge
  7. CDN purging
  8. The SDK and framework caches
  9. Strategies by project
  10. Edge cases
  11. Clearing caches by hand
  12. Settings

The caches, from the database to the screen

LayerHoldsKept current byConfigured in
Kernel caches (content, view, template, INI)rendered views, objects, settingsthe kernel on every publishsite.ini, ezcache.php
GraphQL response cacheanswers of persisted queries, per siteaccess, rights, variables, addressexpired as a whole on every publish, class change, persisted query changegraphql.ini [GraphQLSettings] ResponseCache*
Credential cachethe rights of a key or token seen recentlyforgotten when a key, a role or a user's rights change; CredentialCacheTtlCredentialCacheTtl
Browser / HTTP clientany answer, revalidated with ETagIf-None-Match → 304 or a new answerCache-Control the API sends
Your framework's data cache (Next.js, Nuxt, SvelteKit ...)answers you fetchedyour webhook route purges by tagyour code, with the SDK
A CDN in front of your pagesyour HTMLyour webhook route calls the CDN's purge-by-tag APIthe tag header you send
A CDN in front of the APIanswers of persisted GET requestsshort TTLs or tag purges of your ownsee Edge cases

The kernel never sends purge requests to a proxy or a CDN in front of it. It tells you what changed (events) and what each answer showed (tags); your code connects the two.

The response cache

The server keeps the answers of persisted queries (and only those) in var/cache/graphql/responses/.

What is cached: an answer to a persisted query (by id or by hash) that is a query operation, has no errors and has data. A signed-in query that selects currentUser is not cached (the answer would name the user). Ad-hoc queries are never cached; they are answered with X-GraphQL-Cache: BYPASS.

The key of an entry is the siteaccess, the schema hash, the user's rights (a hash of the roles and their limitations, the same the view cache uses), the persisted query, the variables, the operation name and the address (scheme and host). Two users with the same roles share entries; anonymous visitors all share one.

The early answer. At the very start of index_rest.php, before the settings and the database, a GET or a JSON POST naming a persisted query is looked up:

  • anonymous: answered from the cache when there is an entry;
  • with a key or an OAuth token: answered when the kernel checked these credentials within the last CredentialCacheTtl seconds (60) and remembered their rights; the rate limit of the credential is still counted;
  • otherwise: the request goes on to the kernel, which answers and stores.

X-GraphQL-Cache says HIT (from the cache), MISS (computed now and stored) or BYPASS (an ad-hoc query).

Expiry. The whole cache expires at once (an expired marker with a time; entries older than it are ignored) when:

  • content is published, moved, hidden, removed (whenever the kernel clears view caches);
  • a GraphQL mutation changed something;
  • a content class changes;
  • persisted queries are stored or removed;
  • php bin/php/ezcache.php --clear-id=graphql (also --clear-tag=ini and --clear-tag=content) runs.

An entry also ends after ResponseCacheTtl seconds (86400) without any of these; 0 keeps it until expiry. The cache is per server: on several web servers each has its own, each expired by its own publishes only when var/cache is shared or every server clears it (see Operations, "Several servers").

Off: ResponseCache=disabled, or Debug=enabled.

Check it with two requests of a persisted query:

curl -s -o /dev/null -D - -G "$EXP/api/graphql" --data-urlencode 'id=articles' | grep -i x-graphql-cache   # MISS
curl -s -o /dev/null -D - -G "$EXP/api/graphql" --data-urlencode 'id=articles' | grep -i x-graphql-cache   # HIT

Measure it with ./console exp:graphql:bench --url=$EXP/api/graphql --id=articles: cached answers must come within 33 ms (targets 20 ms and 13 ms for the median and p95).

ETags and 304

Every answer has an ETag:

  • an ad-hoc query: a weak tag W/"<32 hexadecimal characters of the SHA-1 of the answer without its request id>";
  • a persisted query: a strong tag "<32 hexadecimal characters of the SHA-1 of the cached body>".

Send it back as If-None-Match; when the answer would be the same, the API answers 304 Not Modified with no body. For persisted queries the 304 comes from the early answer, before the kernel starts: the cheapest request there is.

ETAG=$(curl -s -D - -o /dev/null -G "$EXP/api/graphql" --data-urlencode 'id=articles' | awk 'tolower($1)=="etag:" {print $2}' | tr -d '\r')
curl -s -o /dev/null -w '%{http_code}\n' -G "$EXP/api/graphql" --data-urlencode 'id=articles' -H "If-None-Match: $ETAG"   # 304
let etag = null, cached = null;
async function articles() {
  const url = 'https://www.example.com/api/graphql?id=articles';
  const res = await fetch(url, { headers: etag ? { 'If-None-Match': etag } : {} });
  if (res.status === 304) return cached;
  etag = res.headers.get('ETag');
  cached = await res.json();
  return cached;
}

Browsers do this by themselves for GET requests they may cache.

Cache-Control and shared caches

AnswerCache-ControlVary
ad-hoc query, mutation, error of the requestprivate, no-store
persisted query, anonymouspublic, max-age=0, must-revalidateOrigin, Authorization
persisted query, signed inprivate, no-cacheOrigin, Authorization
  • max-age=0, must-revalidate lets a browser or a shared cache keep an anonymous answer but ask again every time (cheaply, with If-None-Match). The API never promises freshness it cannot keep: it does not know when your CDN would purge.
  • Vary: Origin, Authorization keeps a shared cache from serving one origin's CORS headers or one user's answer to another.
  • Signed-in answers are private: never cache them in a shared cache.

Purge tags

Every answer of a query carries X-Exponential-Cache-Tags: the purge tags of everything it showed, separated by spaces, ez-all first. They are the tags of the kernel's own HTTP cache, so one purge vocabulary serves both.

TagAdded forPurge it when
ez-allevery answeranything changes (a whole-cache clear)
c<object id>each content shownthat object changes (publish, update, trash, delete, states, section)
ct<class id>each content shown(the class changes; class changes expire the server cache as a whole)
s<section id>each content shown(sections are reassigned)
l<node id>each location a content was reached bythat location changes, moves, hides
pl<parent node id>the parent of each content shown, and the parent of every list (children)a child of that parent is added, moved away, removed, hidden, or changed
p<node id>every node on the path of each content shown (/1/2/89/92/ gives p2 p89 p92), and the parent of a list deeper than its children (depth > 1)anything below that node changes
dqevery search answer (and the kernel's dynamic queries)any content changes

Rules:

  • At most 500 tags per answer (MAX_CACHE_TAGS); an answer that would name more names only ez-all. An answer whose content could not name its tags also names only ez-all.
  • Mutations and errors of the request name no tags.
  • CacheTags=disabled sends none.
  • When httpcache.ini [HttpCacheSettings] TagHeader names a header (xkey, Surrogate-Key, Cache-Tag), the same value goes there too, for a purging proxy in front of the API.
  • To read the header in a browser on another origin, list it in rest.ini [CorsSettings] ExposedHeaders[] (CORS).

With the SDK: result.cacheTags (parsed), parseCacheTags(header), and CACHE_TAG_HEADER.

From an event to the tags to purge

A webhook or a subscription event carries the ids of what changed. The tags to purge:

EventTags
publish, updatec<objectId>, l<n> for every nodeIds, pl<p> and l<p> for every parentNodeIds, and dq
trash, deletethe same (the content leaves its parents' lists)
movec<objectId>, l<n>, pl and l of oldParentNodeId and newParentNodeId, and dq
hide, revealc<objectId>, l<n>, pl and l of the parents, and dq
mutationas the event it caused (a mutation also writes its own publish, move ... event)
clearez-all
a package eventwhat your code knows it concerns

The SDK's tagsForEvent(event) returns exactly c, l and the parents' pl and l (and ez-all for clear). Two things it does not return, which you add when your pages need them:

  1. dq for search answers: add it for every content event if you cache search results.
  2. p<ancestor> for lists deeper than the children (children(depth: 4), Tag.content): the event has no path. Either fetch the content's path in the receiver, or keep such lists on a short TTL, or let a webhook with Payload=query deliver the path (see the cookbook recipe Webhooks with a query payload).
import { tagsForEvent, type ContentEvent } from '@exponentialcms/client';

async function tagsToPurge(event: ContentEvent): Promise<string[]> {
  const tags = new Set(tagsForEvent(event));
  if (event.event !== 'clear') tags.add('dq');
  // the ancestors, for subtree lists: ask where the content is now (after a delete it is gone; its parents are enough)
  if (event.objectId && event.event !== 'delete' && event.event !== 'trash') {
    const { content } = await serverClient.request<{ content: { locations: { pathString: string }[] } | null }>(
      'query($id: Int!) { content(id: $id) { locations { pathString } } }', { id: event.objectId });
    for (const location of content?.locations ?? []) {
      for (const id of location.pathString.split('/').filter(Boolean)) if (Number(id) > 1) tags.add(`p${id}`);
    }
  }
  for (const parent of event.parentNodeIds ?? []) tags.add(`p${parent}`);
  return [...tags];
}

CDN purging

Two places to put a CDN, with different purging.

Your front end renders pages from API answers. Send each page with the union of the tags of every answer it used, in the CDN's tag header, and purge by tag from your webhook receiver.

CDNHeaderSeparatorLimits (SDK)
CloudflareCache-Tag,about 16 KB per header
FastlySurrogate-Keyspaceabout 16 KB
NetlifyNetlify-Cache-Tag,
AkamaiEdge-Cache-Tag,128 characters per tag
Varnish (xkey)xkeyspace
import { cdnCacheTagHeaders, CacheTagOverflowError } from '@exponentialcms/client';

const page = await client.execute(PageQuery, { alias });
const nav = await client.execute(MenuQuery);
let headers: Record<string, string>;
try {
  headers = cdnCacheTagHeaders([...page.cacheTags, ...nav.cacheTags], 'cloudflare', 'site1-');   // { 'Cache-Tag': 'site1-ez-all,site1-c87,...' }
} catch (e) {
  if (!(e instanceof CacheTagOverflowError)) throw e;
  headers = { 'Cache-Control': 'public, max-age=60' };   // too many tags: a short TTL instead
}

Use a prefix per site or environment (site1-) when several share one CDN zone, so a purge of c90 on staging never purges production. The SDK never cuts tags; on overflow it throws CacheTagOverflowError, and applyCacheTags() drops the tags and sets no-store (or the value you give).

The purge call itself, from the webhook receiver (Cloudflare as an example):

async function purgeCloudflare(tags: string[]) {
  for (let i = 0; i < tags.length; i += 30) {                   // Cloudflare takes up to 30 tags per call
    const res = await fetch(`https://api.cloudflare.com/client/v4/zones/${process.env.CF_ZONE}/purge_cache`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${process.env.CF_TOKEN}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ tags: tags.slice(i, i + 30).map((t) => `site1-${t}`) }),
    });
    if (!res.ok) throw new Error(`purge failed: ${res.status}`);
  }
}

Check your CDN's current API and limits; they change more often than this page.

A CDN in front of the API

Possible for anonymous persisted queries by GET only. The API sends public, max-age=0, must-revalidate, so a CDN revalidates on every request (cheap: a 304 from the early answer). To let the CDN serve without asking, override the TTL at the CDN (a few seconds to a minute) and accept that staleness, or purge by tag: with TagHeader set in httpcache.ini, the answers carry the CDN's tag header, and your webhook receiver purges the same tags at the CDN.

Never cache POST requests, signed-in answers (private) or /api/graphql/subscribe at a CDN. Keep Vary: Origin, Authorization.

The SDK and framework caches

The client itself keeps no cache: every request()/execute() goes to the server. It gives you what a cache needs:

ClientResult fieldUse
cacheTagstag your cache entry
cacheStateHIT, MISS or BYPASS of the server's response cache
schemaHashdrop everything when it changes
requestIdlogs
rateLimit{ limit, remaining, resetSeconds }

The framework packages tie the tags to the framework's cache:

PackageCachePurge
@exponentialcms/nextthe Next.js data cache (fetch tags, unstable_cache)a webhook route that calls revalidateTag()
@exponentialcms/nuxtthe Nitro cache with a tag indexthe webhook handler
@exponentialcms/sveltekitthe page's purge tags in load functionsthe webhook route
@exponentialcms/astrocached pagesthe webhook end point
@exponentialcms/edgeanswers in the edge cachethe webhook fetch handler
@exponentialcms/nodeCDN tag headers for Express, Fastify, Honothe webhook route

A minimal tag-indexed cache of your own (any runtime):

const entries = new Map<string, { value: unknown; tags: string[] }>();
const byTag = new Map<string, Set<string>>();

export async function cachedQuery<T>(key: string, run: () => Promise<{ data: T; cacheTags: string[] }>): Promise<T> {
  const hit = entries.get(key);
  if (hit) return hit.value as T;
  const { data, cacheTags } = await run();
  entries.set(key, { value: data, tags: cacheTags });
  for (const tag of cacheTags) (byTag.get(tag) ?? byTag.set(tag, new Set()).get(tag)!).add(key);
  return data;
}

export function purge(tags: string[]) {
  for (const tag of tags) {
    for (const key of byTag.get(tag) ?? []) entries.delete(key);
    byTag.delete(tag);
  }
}
// cachedQuery('page:recipes', () => client.execute(Page, { alias: 'recipes' }))

Strategies by project

ProjectStrategy
Small site, SSRno cache of your own; persisted queries; the server's response cache does the work
Busy site, SSR or ISRframework cache tagged with cacheTags, a webhook receiver purging tagsToPurge(event), a CDN in front of the pages with the same tags
Static siterebuild on webhook, debounced (one build per minute at most); tags not needed
SPAanonymous persisted GET + ETag; the browser revalidates
Appits own store, refreshed on resume and on push messages your server sends from webhooks
Search pagescache with dq and purge it on every content event, or do not cache them

Edge cases

  • Scheduled publishing and expiry. Content published by a cronjob (a future publish date, a workflow that goes on) writes its events when the cronjob runs; purging follows then. Content that "expires" by a date field without a publish writes no event: cache such pages with a TTL.
  • Visibility by date or state in templates. If your query filters by a date at read time (in your code), the answer does not change when time passes: TTL.
  • Role changes. A changed role changes which answers a user gets; the server's response cache is keyed by rights, so it is right at once. Your own caches of signed-in answers are not: key them by user, or do not cache them.
  • Several servers. The response cache, the rate counters and the credential cache are per server unless var/cache is shared. A publish on server A expires A's cache; server B's cache follows when it clears its own view caches (cluster setups do) or after ResponseCacheTtl.
  • Moved content. A move changes URLs: purge both parents (move events name them) and any page that linked to the old URL (c<objectId> covers answers that showed the object).
  • Translations. A new translation is an update (or publish) event with language and languages; the tags are the same.
  • Layouts. Changing a layout in the layout editor writes no content event. Answers of layout carry the tags of their items, not of the layout: give pages with layouts a TTL, or purge ez-all from the editor's workflow.
  • Image aliases. An alias made on demand is a new file, not a content change; its URL is stable once made.
  • Over 500 tags. The answer names ez-all only; any event then purges it. Split very large queries.

Clearing caches by hand

php bin/php/ezcache.php --clear-id=graphql --allow-root-user        # the GraphQL response cache (expires it)
php bin/php/ezcache.php --clear-tag=content --allow-root-user       # content caches, the GraphQL cache with them

Setup > GraphQL shows the response cache (entries, size, last expiry) and clears it (graphql/administrate). Clearing the content caches as a whole writes a clear event (with data.scope content or graphql) to receivers that ask for it; purge ez-all then.

Settings

graphql.ini [GraphQLSettings]DefaultMeaning
ResponseCacheenabledcache answers of persisted queries
ResponseCacheTtl86400seconds an answer is kept at most; 0 until expired
CredentialCacheTtl60seconds the rights of a key or token are remembered for early answers; 0 signed-in requests always go through the kernel
CacheTagsenabledsend X-Exponential-Cache-Tags
PersistedQueriesenabled
httpcache.ini [HttpCacheSettings] TagHeaderdisabledalso send the tags in xkey, Surrogate-Key or Cache-Tag

Something wrong on this page? Report an error

Documentation license

This documentation is free documentation, licensed under the GNU Free Documentation License 1.3 or later.

Exponential Copyright © 1998-2026 Exponential Foundation and 7x