The Bookshop catalogue page is opened again and again, and each time the server works out the same answer. On top of that, one deeply nested query can make the server do thousands of times the work. Fast GraphQL needs two habits: don't work out the same answer again and again (caching), and don't take on orders that are too big (cost limits).
At a bookshop, the question everyone asks, "which books do you have?", is answered from a photocopied sheet pinned up front, with the time it goes stale written on it. Regular customers also jot the answer down in their own notebooks. And an order for "every book of every author of every book..." is politely turned down before the clerk walks to the warehouse.
Why HTTP caching is hard with GraphQL
HTTP caches (browsers, CDNs) keep responses by method and URL. REST has GET /books/1, GET /books/2 and so on: each piece of data has its own URL, so it's easy to keep. GraphQL sends everything as POST /graphql to one endpoint, with the query in the body. Browsers and CDNs don't keep POST responses, and even if they did, the URL is the same for every query. That's why HTTP caching is harder with GraphQL.
The way out: send queries with GET. Apollo Server accepts GET for queries only; a mutation over GET is refused with status 405 and the message GET requests only support query operations, not mutation operations. The catch: the query text goes into the URL, so the URL gets long, and a tiny change makes a different URL.
Persisted queries: send a hash, not the text
Automatic Persisted Queries (APQ): the client computes the SHA-256 of the query text, a 64-character hexadecimal fingerprint, and sends only that hash. For query Catalog { books { id title stock } } it is 49166941fe7f8d78fd1c7e9120c57833d987b13193b512e81803a1c87400fc3b. Here is the real exchange with Apollo Server 5.5.1 (in a real URL the extensions part is encoded):
# 1. First visit: just the hash
GET /graphql?extensions={"persistedQuery":{"version":1,"sha256Hash":"49166941...c3b"}}
200 OK
{"errors":[{"message":"PersistedQueryNotFound","extensions":{"code":"PERSISTED_QUERY_NOT_FOUND"}}]}
# 2. The client retries with the whole text and its hash, and the server stores it
POST /graphql
{"query":"query Catalog { books { id title stock } }","extensions":{"persistedQuery":{"version":1,"sha256Hash":"49166941...c3b"}}}
200 OK
Cache-Control: max-age=10, public
# 3. From then on, from any visitor: just the hash, straight to data
GET /graphql?extensions={"persistedQuery":{"version":1,"sha256Hash":"49166941...c3b"}}
200 OK
Cache-Control: max-age=10, public
{"data":{"books":[{"id":"1","title":"The Rainbow Troops","stock":12}, ...]}}
- The server recomputes the hash from the text in step 2. If they don't match, the answer is 400
provided sha does not match query. - A hash is stored only once its query has passed validation. A refused query is never registered.
- The result: small requests, and the URL in step 3 never changes, so a CDN can keep it. So a persisted query is a query stored on the server with its hash as its ID, and the client sends only the hash.
- APQ is not a security measure, because anyone can register a new query through step 2. To refuse unknown queries, use trusted documents (also called a persisted query list or safelist): at build time, every operation in the client code is collected into one manifest (for example with
@apollo/generate-persisted-query-manifest1.4.0), and the server only runs hashes on that list.
The server cache: cache hints
The server says how long a response may be kept. In Apollo Server, you do it with the @cacheControl directive in the SDL:
enum CacheControlScope { PUBLIC PRIVATE }
directive @cacheControl(maxAge: Int, scope: CacheControlScope, inheritMaxAge: Boolean) on FIELD_DEFINITION | OBJECT | INTERFACE | UNION
type Query {
books: [Book!]! @cacheControl(maxAge: 60)
book(id: ID!): Book @cacheControl(maxAge: 60)
authors: [Author!]!
viewer: User @cacheControl(maxAge: 30, scope: PRIVATE)
}
type Book @cacheControl(maxAge: 3600) {
id: ID!
title: String!
price: Int!
stock: Int! @cacheControl(maxAge: 10)
author: Author!
}
type Author @cacheControl(maxAge: 86400) {
id: ID!
name: String!
}
The rule, for every field that resolves: take the hint of its return type, then the field's own hint overrides it. A field that returns an object (or a root field) with no hint at all gets maxAge 0. The whole response uses the smallest maxAge, and becomes PRIVATE if even one field is PRIVATE. The headers Apollo Server 5 sends:
| Query | Cache-Control |
|---|---|
{ books { title price } } |
max-age=60, public |
{ books { id title stock } } |
max-age=10, public (stock is 10 seconds) |
{ book(id: 1) { title author { name } } } |
max-age=60, public |
{ authors { name } } |
max-age=86400, public (from type Author) |
{ books { title } viewer { name } } |
max-age=30, private |
A response with errors, or with a maxAge of 0, gets Cache-Control: no-store. CDNs and browsers use this header (for GET), and so does the @apollo/server-plugin-response-cache 5.0.0 plugin, which keeps whole responses in memory or Redis. PRIVATE responses are kept per user only, and the plugin needs a sessionId function for that. A resolver can set a hint too: info.cacheControl.setCacheHint({ maxAge: 30, scope: "PRIVATE" }).
The client cache: normalised
Apollo Client 4.3.3 keeps responses in InMemoryCache. It adds __typename to every selection set of your query, then splits the response into one entry per object, keyed __typename:id.
Before looking at the cache, guess. The catalogue page has loaded query Catalog { books { id title stock } }, with This Earth of Mankind's stock at 0. An admin then runs mutation Restock { updateStock(id: 2, stock: 7) { id stock } }. Without querying again, does the catalogue list on screen show 7 too?
After Catalog, Detail (book(id: 2)) and Restock, cache.extract() holds:
{
"Book:1": { "__typename": "Book", "id": "1", "title": "The Rainbow Troops", "stock": 12 },
"Book:2": { "__typename": "Book", "id": "2", "title": "This Earth of Mankind", "stock": 7 },
"Book:3": { "__typename": "Book", "id": "3", "title": "Beauty Is a Wound", "stock": 5 },
"ROOT_QUERY": {
"__typename": "Query",
"books": [{ "__ref": "Book:1" }, { "__ref": "Book:2" }, { "__ref": "Book:3" }],
"book({\"id\":2})": { "__ref": "Book:2" }
},
"ROOT_MUTATION": {
"__typename": "Mutation",
"updateStock({\"id\":2,\"stock\":7})": { "__ref": "Book:2" }
}
}
- This Earth of Mankind is stored once, in
Book:2.booksandbook({"id":2})only hold references (__ref) to it. - Restock returns
idandstock, so Apollo knowsBook:2changed and sets itsstockto 7. Catalog is read through the same reference, so the list on screen shows 7 too, with no request at all. If the mutation didn't ask forid, the cache wouldn't know which entry to change and the screen would stay stale. - This is what sets Apollo Client apart from plain
fetch: an automatically normalised cache, reactive state (hooks likeuseQueryre-render a component when its entries change), and loading and error states already handled. - urql 5 has the same idea through
@urql/exchange-graphcache9.0.2. Without Graphcache, urql only keeps results per query and variables. - Relay, Meta's GraphQL client, also normalises its cache, but more strictly: it requires global IDs (the
Nodeinterface from "Schema Design Patterns"), Connections for pagination, and fragments placed next to their components, compiled at build time. Because those patterns are mandatory, its performance is optimal by default; the price is a steeper learning curve than Apollo's.
Cost limits: depth and complexity
A query can nest as deep as it likes, so one request can make the server work thousands of times harder. Two measures are computed from the query text, before any resolver runs:
- Depth (
graphql-depth-limit1.1.0): every field with a selection set adds one level; scalar fields add none.Cataloghas a depth of 1. - Complexity (
graphql-query-complexity2.0.0): every field is worth 1 plus what's inside it. A list field marked@complexity(value: 1, multipliers: ["first"])counts as (1 + its contents) ×first.
| Query | Depth | Cost |
|---|---|---|
Catalog |
1 | 4 |
Deep: authors { books { author { books { author { books { title } } } } } } |
6 | 7 |
Bulk: booksConnection(first: 100) { edges { node { title author { name books { title } } } } } |
5 | 800 |
Bulk with first: 10 |
5 | 80 |
Bulk's cost is counted from the inside out: books { title } = 2, author { name books } = 1 + 1 + 2 = 4, node = 1 + 1 + 4 = 6, edges = 7, then booksConnection = (1 + 7) × 100 = 800. Deep is cheap but deep; Bulk is shallow but expensive. So set both:
import depthLimit from "graphql-depth-limit";
import { getComplexity, directiveEstimator, simpleEstimator } from "graphql-query-complexity";
const costLimit = {
async requestDidStart() {
return {
async didResolveOperation({ request, document, schema }) {
const cost = getComplexity({
schema,
query: document,
operationName: request.operationName,
variables: request.variables, // first: $n counts with its real value
estimators: [directiveEstimator(), simpleEstimator({ defaultComplexity: 1 })],
});
if (cost > 200) {
throw new GraphQLError(`Query too complex: ${cost}. Maximum allowed complexity: 200`, {
extensions: { code: "QUERY_TOO_COMPLEX", http: { status: 400 } },
});
}
},
};
},
};
const server = new ApolloServer({ typeDefs, resolvers, validationRules: [depthLimit(5)], plugins: [costLimit] });
depthLimit(5)runs with validation. Deep is refused with status 400:'Deep' exceeds maximum operation depth of 5(codeGRAPHQL_VALIDATION_FAILED).- The cost is computed in a plugin because a validation rule doesn't see
variables. Bulk is refused:Query too complex: 800. Maximum allowed complexity: 200. Withouthttp: { status: 400 }, an error thrown fromdidResolveOperationgoes out with status 500. - The
@complexitydirective must be declared in the SDL:directive @complexity(value: Int!, multipliers: [String!]) on FIELD_DEFINITION.
Other options: graphql-depth-limit 1.1.0 was released in August 2017 and has not been updated since, although it still works on graphql 16. A package that is still maintained, @escape.tech/graphql-armor 3.2.0 (for Apollo Server 4 and 5), sets several limits at once. Its defaults: depth 6, aliases 15, cost 5,000, tokens 1,000, directives 50, and field name suggestions (Did you mean ...) hidden.
import { ApolloArmor } from "@escape.tech/graphql-armor";
const armor = new ApolloArmor({ maxDepth: { n: 5 }, maxAliases: { n: 15 } });
const server = new ApolloServer({ typeDefs, resolvers, ...armor.protect() });
- The alias limit stops one field from being asked for again and again under different names in one request:
a1: book(id: 1) { title } a2: book(id: 2) { title } .... A depth limit does not stop this, because the query stays shallow. Tested on Apollo Server 5.5.2: 16 aliases are rejected with status 400,Syntax Error: Aliases limit of 15 exceeded, found 16.TheSyntax Errorprefix comes from the package itself, even though the query has no typo. - It counts depth differently:
Deepcounts as 7, not 6, so it is rejected withQuery depth limit of 5 exceeded, found 7. - The cost from graphql-armor multiplies by a
first: 100written in the query itself, but does not readvariables. So thecostLimitabove is still used forfirst: $n.
DataLoader stays per request
Every cache above works across requests. DataLoader (the "N+1 Problem & DataLoader" lesson) works inside one request: the same author is fetched only once. Still create new loaders in context for every request; a global loader keeps old data and can leak one user's data to another.
⚠️ Caches that go stale, miss, or let the heavy query in
- A mutation that doesn't return
id. The client cache can't merge it, so the screen keeps showing old data. - One object type with no hint. Its field gets
maxAge0, and the whole response becomesno-store. - Detail isn't answered from the cache.
Book:2is there, butbook(id: 2)still goes to the network becauseROOT_QUERYhas nobook({"id":2})yet. Point it there withtypePolicies:book: { read: (_, { args, toReference }) => toReference({ __typename: "Book", id: args.id }) }. - Treating APQ as security, or lists without a limit. APQ accepts new queries from anyone; use trusted documents. And
bookswithoutlimitcounts as ×1 however much it holds, so give every list an argument that caps it at a maximum.
TL;DR: HTTP caching is hard with GraphQL because every request is a POST to one endpoint. APQ sends the SHA-256 of the query text (PersistedQueryNotFound once, then a POST that registers it, then a GET with just the hash that a CDN can keep); trusted documents limit the server to queries registered at build time. @cacheControl gives a maxAge per type and field; a response uses the smallest (max-age=10, public once stock is in it), PRIVATE spreads, and errors or an object without a hint make it no-store. Apollo Client stores each object once as __typename:id, so a mutation that returns id and stock updates every query that uses that book at once. Relay normalises too, but requires global IDs, Connections and compiled fragments. Refuse heavy queries before they run: depthLimit(5) (Deep, depth 6) and a maximum cost of 200 in a plugin (Bulk, 800). DataLoader stays one per request.
⚡ Why HTTP caching is hard
Meaning: The HTTP cache in browsers and CDNs stores responses by method and URL. GraphQL sends every request as a POST to the same endpoint, with the query in the body, and POST responses aren't stored.
⚡ Persisted queries: send a hash, not the text
Write:
GET /graphql?extensions={"persistedQuery":{"version":1,"sha256Hash":"49166941...c3b"}}
Guess first: APQ only runs queries whose hash is registered. So are unknown queries refused automatically?
No. Anyone can register a new query by sending its text and hash in a POST. To refuse unknown queries, use trusted documents.
Meaning: The client sends the SHA-256 of the query text. Requests stay small, and the GET URL never changes, so a CDN can keep it.
⚡ Cap the depth and the cost
Meaning: Bulk is only 5 deep, but first: 100 makes its cost (1 + 7) × 100 = 800. With depthLimit(5) and a cost plugin capped at 200, a query that's too deep or too costly is refused before a single resolver runs.