Performance & Caching — GraphQL

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…

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 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" }
  }
}

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:

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] });

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() });

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

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.

What you will learn