Caching
Caching in REST is easy to explain: GET /products/42 is a URL, and browsers, CDNs and proxies can cache responses by URL. GraphQL usually sends every request as POST /graphql with a different body, so that HTTP machinery doesn't apply out of the box. Instead, GraphQL caching happens at several other layers.
| Layer | What is cached | Example tools |
|---|---|---|
| Client (normalized cache) | individual objects, by __typename + id |
Apollo Client, Relay, urql Graphcache |
| Request (DataLoader) | lookups within one request | DataLoader |
| Server (response / field cache) | whole results or expensive fields, for a time | Redis, in-memory LRU, @cacheControl |
| HTTP / CDN | GET requests with persisted queries |
CDNs, Varnish |
| Parse/validate cache | parsed + validated documents | built into most servers |
Client-side normalized caching
A smart client doesn't store responses per query. It splits them into objects, keyed by type and id, so that two queries returning the same User:1 share one entry. When a mutation returns an updated User:1, every component showing that user updates. This is why schemas should expose stable id fields and clients should request __typename:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type User { id: ID!, name: String!, friends: [User!]! }
type Query { me: User! }
`);
const people = { 1: { id: 1, name: 'Ana', friendIds: [2, 3] }, 2: { id: 2, name: 'Ben', friendIds: [1] }, 3: { id: 3, name: 'Cy', friendIds: [1] } };
const toUser = (p) => ({ ...p, friends: () => p.friendIds.map((id) => toUser(people[id])) });
const { data } = await graphql({
schema,
rootValue: { me: () => toUser(people[1]) },
source: '{ me { __typename id name friends { __typename id name friends { __typename id name } } } }',
});
// Normalize: replace nested objects with references.
const cache = {};
function normalize(value) {
if (Array.isArray(value)) return value.map(normalize);
if (value && typeof value === 'object') {
const entry = {};
for (const [k, v] of Object.entries(value)) entry[k] = normalize(v);
if (value.__typename && value.id) {
const key = `${value.__typename}:${value.id}`;
cache[key] = { ...cache[key], ...entry };
return { __ref: key };
}
return entry;
}
return value;
}
const root = normalize(data);
console.log(JSON.stringify(root));
for (const [key, entry] of Object.entries(cache)) console.log(key, JSON.stringify(entry));{"me":{"__ref":"User:1"}}
User:1 {"__typename":"User","id":"1","name":"Ana","friends":[{"__ref":"User:2"},{"__ref":"User:3"}]}
User:2 {"__typename":"User","id":"2","name":"Ben","friends":[{"__ref":"User:1"}]}
User:3 {"__typename":"User","id":"3","name":"Cy","friends":[{"__ref":"User:1"}]}
User:1 appeared three times in the response (as me and as a friend of Ben and Cy) but is stored once.
Server-side: caching expensive fields
Some fields are slow but change rarely: exchange rates, a recommendation list, a weather lookup. A cache with a time to live (TTL) in front of the data source avoids repeating the work. We pass a fake clock so the example is deterministic:
import { graphql, buildSchema } from 'graphql';
function createTtlCache({ ttlMs, now }) {
const entries = new Map();
return async (key, compute) => {
const hit = entries.get(key);
if (hit && now() - hit.storedAt < ttlMs) return hit.value;
const value = await compute();
entries.set(key, { value, storedAt: now() });
return value;
};
}
let clock = 0;
const cached = createTtlCache({ ttlMs: 60_000, now: () => clock });
let apiCalls = 0;
const fetchRate = async (pair) => {
apiCalls += 1;
return { 'EUR/USD': 1.08, 'EUR/GBP': 0.86 }[pair];
};
const schema = buildSchema(`type Query { rate(pair: String!): Float }`);
const rootValue = { rate: ({ pair }) => cached(`rate:${pair}`, () => fetchRate(pair)) };
for (const t of [0, 10_000, 59_000, 61_000]) {
clock = t;
await graphql({ schema, rootValue, source: '{ rate(pair: "EUR/USD") }' });
console.log(`t=${t / 1000}s api calls so far: ${apiCalls}`);
}t=0s api calls so far: 1
t=10s api calls so far: 1
t=59s api calls so far: 1
t=61s api calls so far: 2
Warning: Cache keys must include everything the value depends on: the arguments and, for private data, the user. A key of
"profile"without the user id would show one person's profile to everyone.
HTTP caching with persisted queries
To make CDNs useful, clients can send queries as GET requests. Long query strings make poor URLs, so persisted queries replace the text with a hash: the server keeps a map from hash to query (registered at build time, or learned on first use with "automatic persisted queries").
GET /graphql?extensions={"persistedQuery":{"version":1,"sha256Hash":"ecf4edb46db40b5132295c0291d62fb65d6759a9eedfa4d5d612dd5ec54a6b38"}}&variables={"id":"42"}The same hash + variables is the same URL, so a CDN can cache it with ordinary Cache-Control headers. Here is the server-side lookup with a simple (non-cryptographic) hash, standing in for SHA-256:
import { graphql, buildSchema } from 'graphql';
const hash = (text) => {
let h = 5381;
for (const ch of text) h = ((h * 33) ^ ch.charCodeAt(0)) >>> 0;
return h.toString(16);
};
const schema = buildSchema(`type Query { product(id: ID!): String }`);
const rootValue = { product: ({ id }) => `Product ${id}` };
// Registered at build time from the client's .graphql files.
const productQuery = 'query Product($id: ID!) { product(id: $id) }';
const persisted = new Map([[hash(productQuery), productQuery]]);
console.log('registered hash:', hash(productQuery));
async function handleGet({ queryHash, variables }) {
const source = persisted.get(queryHash);
if (!source) return { errors: [{ message: 'PersistedQueryNotFound' }] };
return graphql({ schema, rootValue, source, variableValues: variables });
}
console.log(JSON.stringify(await handleGet({ queryHash: hash(productQuery), variables: { id: '42' } })));
console.log(JSON.stringify(await handleGet({ queryHash: 'deadbeef', variables: {} })));registered hash: fcaa68e8
{"data":{"product":"Product 42"}}
{"errors":[{"message":"PersistedQueryNotFound"}]}
A side benefit: if the server only accepts registered hashes, attackers can't send arbitrary queries at all. That's a strong security measure for private APIs.
Test yourself
How does a normalized client cache identify an object?
- By the query text
- By
__typenameplusid - By the HTTP URL
- By the field name
Why don't CDNs cache typical GraphQL requests?
- GraphQL responses aren't JSON
- Requests are usually POSTs to one URL with varying bodies
- GraphQL forbids caching
- Responses are too large
What must a server-side cache key for a private field include?
- Only the field name
- The arguments and the user it was computed for
- The server's hostname
- Nothing; private data can't be cached