Response Caching
The public GraphQL API caches resolved responses by default. The first request for a given query resolves normally; repeat requests for the same query within the cache lifetime return the previously-resolved bytes directly, skipping the resolver. Edits invalidate cached entries automatically.
This is a big perf win for read-heavy storefronts. A page query that takes 1+ second cold can return in well under 100ms warm — most of the warm-request time is network, not server work.
What’s cached
Every public (non-inline) model caches by default, with the following defaults:
| Model kind | Default scope | Default lifetime |
|---|---|---|
| Standard | PUBLIC — one cached entry serves every caller with the same query | 60 seconds |
Owned (access.ownerPlane = user or organization) | PRIVATE — entries are isolated per owner | 60 seconds |
PUBLIC and PRIVATE refer to the cache scope, not the visibility of the data itself. A PUBLIC entry can be served to any caller whose query, variables and schema channel match — and whose identity fingerprint matches.
The fingerprint is much wider than the caller’s scopes, because anything that can change a response body without appearing in the query or the variables has to appear in the key instead. It folds in:
- whether the caller is a console session, and which context it is simulating in preview
- the signed-in user’s id, on every scope rather than only
PRIVATE— aPUBLICbody can still carry a segment-targeted variant chosen from the user’s own profile, none of which reaches the variables - the raw scope set the credential holds, and the authority resolved from it
- the key’s kind
- the country and location the edge derived for the request
- the organization the credential is confined to
So PRIVATE does not mean “the user id is in the key” — the user id is always in the key. PRIVATE means the entry is never offered to a different owner.
Owned-plane models cannot be
PUBLIC. Saving a model with an owned plane (access: { ownerPlane: 'user' }or'organization') andcacheControl: { scope: 'PUBLIC' }is refused withINVALID_ARGUMENT, on create, on update, through a model group and through a config bundle alike. There is no downgrade path you can rely on: the read side does treat a storedPUBLICon an owned plane asPRIVATE, but that is a backstop against a row that should not exist and it logs at error level when it fires. Treat it as an alarm, not as a supported configuration.
Entries are also partitioned by organization. In a project with organizations, every cached entry, PUBLIC or PRIVATE, is keyed by the organization the request stands in: the one a key is confined to, or the one a project key names with X-Org-Id or by its address with X-Org-Url. The key is the organization’s id, not its path or the page’s URL, so a reseller and each of its clients hold separate entries. Moving an organization drops the cached entries of the moved subtree and of the organizations above it before and after the move, because the rows each of them reaches have changed.
Mutations are never cached. Draft-channel reads and reads that pass preview: true are never shared and never stored downstream: they come back Cache-Control: private, no-store. Foir keeps one for the caller holding drafts:read, under that caller’s own key, for 60 seconds at most.
Tuning a model
Open a model in the console and find the Caching sub-section on its Settings tab. The toggle controls whether responses are cached at all; the scope and lifetime inputs control the rest. Owned-plane models (those with an access.ownerPlane of user or organization) lock the scope to private.
The same settings live in foir.config.ts under config.cacheControl. Either surface writes to the same place — the console reflects what’s in foir.config.ts and vice versa.
{
key: 'page',
name: 'Page',
config: {
publishing: true,
cacheControl: { maxAge: 60, scope: 'PUBLIC' },
},
// ...
}A 60-second default is short enough that staleness from an edit is bounded to one minute even if invalidation somehow misses; long enough to absorb realistic storefront traffic spikes. Slow-changing settings (navigation, UI copy, redirects) often warrant longer lifetimes — 300 seconds is common.
Opting out
Some responses can’t safely be cached. To opt a model out, set the scope to 'NO_CACHE':
{
key: 'live_dashboard',
config: {
cacheControl: { scope: 'NO_CACHE' },
},
}Toggling the Caching switch off in the console does the same thing.
When to opt out:
- Real-time data — chat presence, live metrics, anything where the API consumer expects to see writes immediately.
- Frequently-changing aggregates — leaderboards, counters, anything whose value depends on a write rate higher than your cache TTL.
- Per-request side effects — queries that fire an analytics event or update a “last seen” field as part of resolution.
Opting out doesn’t free up TTL tuning later. If a model lives on NO_CACHE for a while and you decide its read rate justifies caching, you can flip it back on and the same defaults apply.
How invalidation works
When you edit a record — create, update, delete, publish, or unpublish — every cached response that referenced that record drops immediately. List responses drop when any record in the list is edited. Cached entries for one model don’t invalidate when an unrelated model is edited.
Invalidation is post-commit, not write-through. The invalidations a write owes are collected during the transaction and applied once it has committed — they cannot run inside it, because a transaction that rolled back after dropping cache entries would have thrown away entries that are still correct.
That leaves a short window, between the commit and the invalidation landing, in which a read can still be served the pre-write body. It is milliseconds rather than seconds, and there is no background job involved, but it is not zero. If you need a read to observe your own write with certainty, do not rely on the invalidation having landed — use a staleness floor, which is exact rather than fast.
If the cache layer can’t talk to Redis, the edit still commits and the failure is logged; the next read resolves normally and re-populates the cache.
The cache lifetime (TTL) is a safety net for the unlikely case where an invalidation gets lost — the entry expires on its own at most maxAge seconds after it was stored.
An entry that has expired is fetched fresh by the next request for it. Requests for the same read that arrive during that fetch are answered from the expired copy, marked X-Foir-Stale: true, rather than kept waiting. An edit removes the copy as it lands, as it does any cached entry. See Errors & Rate Limits for when else a stale copy is served.
Per-request opt-outs
Storefronts can bypass the cache for a specific request using the standard HTTP Cache-Control request header:
| Header | Behaviour |
|---|---|
Cache-Control: no-cache | Skip the cached entry, run the resolver fresh, and re-populate the cache with the new response. For reading your own write, prefer a staleness floor — it keeps the entries that are already fresh enough. |
Cache-Control: no-store | Skip the cache entirely — no read, no write. Useful for one-off debugging without polluting the shared cache. |
# Force a fresh read; subsequent normal callers get the new entry
curl -X POST https://api.foir.dev/graphql \
-H "x-api-key: foir_pub_..." \
-H "Cache-Control: no-cache" \
-d '{"query":"{ pages { id title } }"}'These headers only affect the single request that carries them. They don’t change the model’s configured caching behaviour.
Reading your own write
Cache-Control: no-cache works for this, and it is blunt: it throws away a warm entry whether or not that entry was already new enough. One write then makes the next visitor on that query pay a cold read.
A staleness floor is the precise version. A mutation hands back a token naming where it committed; a subsequent read carries the token; the server serves a cached entry only if that entry resolved at or after the write, and resolves fresh otherwise.
POST /graphql → X-Foir-Write-Token: <opaque> (on the mutation's response)
POST /graphql ← X-Foir-Write-Token: <opaque> (on the next read's request)A cacheable read also carries X-Foir-Project-Seq, the project’s logical clock at the moment it was resolved, which is what a floor is compared against, and what lets a client discard an out-of-order response instead of applying it. It is absent when the server does not know the position, and on a read that bypasses the cache.
The token is opaque. It names the event the write emitted, not a position, and only the server can resolve one to the other. Do not parse it.
That indirection is what keeps writes fast: positions are stamped asynchronously, so a mutation that waited for its own would be unable to complete whenever the process doing the stamping fell behind. Instead the read resolves the token, and when the write is too recent to have a position yet the read simply resolves fresh — which is exactly no-cache behaviour, for the few milliseconds it applies.
A floored read cannot be served from the shared CDN lane. That edge has no view of the clock, so it cannot tell whether what it holds is new enough, and serving from it would look like the floor was satisfied. The SDK routes any token-bearing read to the origin for this reason, and reports floor as the lane reason so the decision is visible rather than inferred.
With @foir/sdk, the header is named for you:
import { readFoirWriteToken, foirWriteTokenHeaders } from '@foir/sdk/live';
const token = readFoirWriteToken(mutationResponse.headers);
// …then on the next read:
const headers = foirWriteTokenHeaders(token);How long to hold a token is yours to decide — which write it stands for, and for how long, are application questions the SDK cannot answer for you. Hold it too long and reads stay pinned to the origin after the write has stopped mattering.
X-Foir-Write-Token is on Foir’s CORS allow-list in both directions — exposed on responses so browser JavaScript can read it, and accepted on requests so a browser can send it back. Neither needs any configuration from you.
If you put your own proxy in front of the API, it has to preserve the header both ways. A proxy that drops it on the response makes the token read as
null, which looks exactly like a mutation that never emitted one; drop it on the request and the floor is silently never applied.
Cache headers on responses
A read that succeeded carries:
Cache-Control: private, max-age=<seconds>on/graphqlSurrogate-Key: <space-separated tags>for downstream CDN cache-tag purges
A read that comes back with errors carries Cache-Control: no-store, on both endpoints. Foir does not keep an answer like that itself, so nothing downstream is told to keep it either.
/graphql responses are always private, even when the model’s cache scope is PUBLIC. The two words mean different things. The model scope decides whether Foir’s own cache can serve one stored entry to several callers. The header decides whether a cache outside Foir can, and a cache outside Foir keys on the URL alone. Your API key travels in a header, not the URL, so two keys with different reach would collide on one entry. private is the honest answer, and it means a browser may reuse the response but a CDN will not store it.
To get a response a CDN will store, use the shared endpoint below.
The shared endpoint
/cdn/graphql serves the reads that are identical for every visitor, with a Cache-Control that a CDN will honour. It is the same schema, the same resolvers and the same auth as /graphql. You point an existing query at a different path and nothing about the query changes.
It exists because a storefront’s site-wide chrome, the navigation, the footer, the banner, is the same bytes for every visitor and is fetched on every single page view. Those reads never need to reach us.
Both endpoints always return the same content. /cdn/graphql resolves exactly as /graphql does, including your variants. The only thing it decides differently is whether the answer may be shared, and that is carried on a header.
Using it
Put your publishable key in the URL, not only in the header:
GET /cdn/graphql?key=foir_pub_...&query={...}The key has to be in the URL because that is what a CDN keys on. If it rode only in a header, two different keys would share one cache entry. For the same reason the key in the URL is the only one this endpoint answers for: a request whose header names a different key is refused. Only a publishable key is accepted. It is already in your client bundle where every visitor can read it, so naming it in a URL gives nothing away. A server key and an admin key are never put in a URL.
Use GET rather than POST. A shared cache will not store a POST however cacheable its content, because the thing that distinguishes one read from another is in the body, which caches do not look at.
Pair it with persisted queries so the URL carries a hash rather than the whole document.
What it refuses
These are things your code does, so they fail immediately and visibly rather than quietly costing you a cache miss. Each returns HTTP 400 with extensions.code: "NOT_SHAREABLE" and a condition naming which one:
condition | Cause | Fix |
|---|---|---|
credential | The key was only in the header, a header names a different key from the URL’s, or it is a server key or an admin key | Put one publishable key in ?key=. A header may repeat it and may not name another |
organization | The request names an organization with X-Org-Id or X-Org-Url | A header is not part of the URL. Use a key confined to the organization, or send the read to /graphql |
signedIn | The request carries a token in the Authorization header, whether or not it is still valid | Signed-in reads resolve per user. Send them to /graphql |
operation | A mutation or subscription | Send writes to /graphql |
channel / preview | Draft channel, or preview: true | Unpublished content is never shareable |
A refusal is never stored. Neither is anything else that is not a successful read: a response with errors, a rate limit, a failure, and the persisted-query handshake’s “not found” all leave with Cache-Control: no-store.
What it serves but will not cache
These are decisions your content team makes, and they can change on any day without anyone touching your code. So they never fail your build. The response is correct and complete, it simply comes back private and no CDN stores it:
- a field or model whose cache scope is
PRIVATEorNO_CACHE - an owned model, meaning one with
access.ownerPlaneofuserororganization - a record from a model that has variants, even when the visitor was served the default
That last one catches people, so it is worth being plain about. Variant targeting can read the visitor’s country and location, which Foir derives from the request rather than taking from you, and which therefore appear nowhere in the URL. If a shared cache stored a targeted response, the next visitor would be served the previous visitor’s targeting. A visitor who matches no variant is served the default, and a shared copy of that default would then reach a visitor who does match. So any response containing a record of a model with variants is marked private.
Targeting on locale, device, platform or your own custom dimensions is unaffected in principle, because you pass those in the query and they are part of the URL. Today Foir cannot yet tell which dimension drove a given variant, so it takes the safe answer and withholds sharing from all of them. If that matters for your workload, tell us.
Where it is stored
On Foir’s own API host, Cloudflare sits in front of this endpoint and keeps each response that is marked public, for as long as its max-age says. A repeat of the same URL inside that time is answered at the edge. It never reaches Foir, so it spends none of your rate limit.
The edge keys a stored response on the full URL and on the request’s Origin header. Each browser origin therefore fills its own copy, and server-side callers, which send no Origin, share one.
Nothing else is stored there. A response marked private or no-store passes straight through, every time.
How long an edit takes to show
Foir’s own cache drops a response the moment a record in it changes. The copy at the edge is not dropped: it lives until its max-age runs out. So an edit you publish shows through this endpoint at most maxAge seconds later, which is 60 unless you have tuned the model. The same read on /graphql shows it at once.
Choose maxAge with that in mind. It is the longest a visitor can be shown the previous version, and it is also how long the edge can answer without asking us.
On your own API domain
A custom API domain is fronted by your CDN, on your account, where no setting of ours reaches. Foir’s edge cache serves api.foir.dev and nothing else. So on your own domain these reads are cached near your visitors only if your CDN is set up to cache them. Until it is, every read travels to Foir, where Foir’s own cache still answers it.
Whichever CDN you use, the same four things have to hold:
- Cache
GET /cdn/graphqland nothing else. Every other path answers one caller. - Key on the whole URL and on the request’s
Originheader. The URL carries the key, the query and its variables. The answer’s CORS headers name the origin that asked, so two browser origins must never share a copy. Server-side callers send noOriginand share one. - Take the lifetime from the origin’s
Cache-Control, and never override it. This endpoint answerspublic, max-age=…only for a read everybody may share. A read that belongs to one caller, a refusal, a rate limit and a failure all leave asprivateorno-store. A CDN told to store them anyway serves them to everybody. - Send straight to the origin any request that carries an
Authorization,X-Org-Id,X-Org-UrlorX-Foir-Write-Tokenheader. Foir refuses the first three on this endpoint, and a cache that keys on the URL would otherwise answer such a request from a stored copy without asking: the caller would get everybody’s answer where they were owed a refusal. Foir’s own edge skips them.
To check your CDN, send the same GET twice and read the cache status it reports for the second: on Cloudflare, cf-cache-status: HIT. Then send it once more with Authorization: Bearer x. That one must not be a hit.
Below is the recipe for Cloudflare. On any other CDN, set it up so the four rules above hold, and check it the same way. The recipe starts from a zone that already serves your domain, with /graphql answering through it, and covers only what makes it cache.
Cloudflare
Cloudflare does not store these reads until you say so. It treats a URL that has a query string and no file extension as dynamic, and does not keep it whatever Cache-Control says.
-
The rule. Under Caching → Cache Rules, add a rule for the path
/cdn/graphqlthat makes it eligible for cache and takes both lifetimes from the origin’s headers. They are two settings, and both have to be added:- Edge TTL: “Use cache-control header if present, bypass cache if not”.
- Browser TTL: “Respect origin TTL”. A rule that sets only the edge TTL leaves what browsers are told to the zone’s own Browser Cache TTL setting.
Never choose an option there that sets a TTL of its own.
-
The key. Nothing to do. Cloudflare’s default cache key is the full URL and the
Originheader. -
The requests to skip. Leave them out in the rule’s expression, so a request that carries one of the four headers above is never eligible for cache. With your own hostname in place of
api.example.com:(http.host eq "api.example.com" and http.request.uri.path eq "/cdn/graphql" and not any(http.request.headers["authorization"][*] ne "") and not any(http.request.headers["x-org-id"][*] ne "") and not any(http.request.headers["x-org-url"][*] ne "") and not any(http.request.headers["x-foir-write-token"][*] ne ""))
Purging on publish
A copy at your CDN lives until its max-age runs out, so an edit shows there at most that many seconds late. To show it at once, purge on publish.
Two events say that content went live: RECORD_PUBLISHED, once for each record published singly or by a schedule, and BULK_PUBLISH_COMPLETED, once for a bulk publish, in place of the per-record events it would otherwise send. Give each a hook that runs an operation of yours, and have that operation call your CDN’s purge API. The event’s keys arrive as input on the payload your endpoint receives.
import { defineConfig } from '@foir/cli/configs';
export default defineConfig({
key: 'my-app',
name: 'My App',
operations: [{ key: 'purge-cdn', name: 'Purge the CDN', endpoint: '/purge-cdn' }],
hooks: [
{ key: 'purge-on-publish', event: 'RECORD_PUBLISHED', operationKey: 'purge-cdn' },
{ key: 'purge-on-bulk-publish', event: 'BULK_PUBLISH_COMPLETED', operationKey: 'purge-cdn' },
],
});Add RECORD_UNPUBLISHED and RECORD_DELETED the same way if a page you take down has to vanish at once too.
On Cloudflare, purge by prefix, which covers every query string under it:
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/purge_cache" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{"prefixes": ["api.example.com/cdn/graphql"]}'The last two clear every shared read on the domain, not only the ones that changed. That costs one trip to Foir for each, where Foir’s own cache answers. On Cloudflare’s Free plan a zone may purge by prefix five times a minute, so a storefront that publishes more often than that should let max-age do the work.
When to use it
Worth it: navigation, footers, banners, settings, published marketing pages, anything a logged-out visitor sees.
Not worth it: anything personalised. Those reads were never shareable by anyone, so nothing is lost by leaving them on /graphql.