Caching GraphQL

Intermediate · 9 min

Why one POST URL defeats HTTP caching, and the layers that work instead: client cache, DataLoader, server response cache with invalidation, and CDN.

Before thisPersisted queriesThe Apollo cacheDataLoader and batching

ChilliCream · 9 min

Caching GraphQL

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by ChilliCreamReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • REST gets HTTP caching because each URL names one resource. GraphQL sends different queries to one URL, so caches have no natural key.
  • There are four layers to cache at: the client's normalized cache, a per-request DataLoader, a server response cache, and a CDN.
  • A server response cache keys on the query, variables and, for private data, the user; a missing or wrong session key can serve one user's data to another.
  • Invalidation is the hard part. Time-to-live is simple and stale, while invalidating by type and id on mutation is accurate and needs entity ids in responses.
  • CDN caching needs GET requests, which persisted queries make practical, plus Cache-Control values derived from the least cacheable field in the response.

Why GraphQL feels hard to cache

REST borrowed HTTP’s cache for free. A GET /books/1 is a stable address, so browsers and CDNs store the response and serve it again. GraphQL breaks that on two counts. Requests are POSTs, which shared caches do not store. And they all go to one URL, so even if they did, the URL would not say what was asked.

Caching is still possible. It just happens at several layers, each with a different job. It helps to separate them.

Layer 1: the client

The first and cheapest cache is on the user’s device. Apollo’s normalized cache answers repeat reads without a request, and urql’s document cache does the same by query. This is covered already. It is per-user and per-tab, which is why it never has a security problem, and it does not help the second user who asks for the same data.

Layer 2: DataLoader, per request

DataLoader memoizes within one request, so ten resolvers asking for author(2) hit the database once. It is a cache in the sense that it deduplicates, but it lives and dies with the request. Create loaders in the context function and never share them across requests, or you will serve stale and cross-user data.

Layer 3: a response cache on the server

A response cache stores the whole JSON for a query and returns it for an identical query. It saves resolver and database work, and it is where most servers start. I ran @graphql-yoga/plugin-response-cache 4.1.0 with GraphQL Yoga 6.1.0:

import { useResponseCache } from "@graphql-yoga/plugin-response-cache";

createYoga({
  schema,
  plugins: [
    useResponseCache({
      session: (request) => request.headers.get("x-user"),
      ttl: 60_000,
    }),
  ],
});

With a counter in the resolver, the results were:

  • The same query twice from one user ran the resolver once.
  • A different user’s identical query ran it again, because the key included the session.
  • A mutation that renamed an item, rename(id: "1", title: "B"), invalidated the cached list: the next items query hit the resolver and returned the new title.

That last point is the useful part. The plugin invalidates by entity: each cached response records the types and ids it contained, and a mutation that returns an entity with its id evicts the responses that include it. That is why returning id from mutations matters here as much as in the client cache. A pure time-to-live approach, where entries just expire, is simpler and serves stale data until they do.

The cross-user trap

I made a mistake while testing that is worth repeating. My first session function was written as if it received the GraphQL context, but the plugin passes the incoming Request. My function returned undefined, which means “no session”, and the second user’s query was answered from the first user’s cached response. Nothing failed. That is exactly how this bug looks in production: it works, and it leaks.

Three rules follow. Test with two users. Decide per field what is private. And for anything user-specific, make sure the cache key includes the identity, as with Apollo-style @cacheControl(scope: PRIVATE) annotations or the plugin’s per-coordinate scope settings. I did not test those options end to end, so check the docs for your server’s names. Authorization from the earlier lesson still runs on a cache miss only, so a hit must never bypass the rule that decided who may see it.

Layer 4: the CDN

To cache at the edge you need two things. The request must be a GET with the query identified in the URL, and the response must carry Cache-Control headers. Persisted queries supply the first: a hash fits in a URL, and I confirmed a persisted query served over GET returned data. The second comes from the schema. Servers that support cache hints let you annotate types and fields with a max age and scope, and compute the response’s Cache-Control from the most restrictive field in it, so one private field makes the whole response private. I did not run an edge cache, so this layer is docs and the video, not verified here.

Edge caches also do not know your authorization rules. Cache only responses that are the same for everyone, mark user-specific ones private, and think about Vary on the authorization header. Edge caching is the weakest fit for personalised data and the best for public catalogues and content.

Which layer, when

Situation Reach for
Same data shown in many components client normalized cache
Repeated lookups inside one query DataLoader
Expensive public queries repeated across users server response cache or CDN
Per-user dashboards client cache, short private TTLs, optimised resolvers

Start with the layers that cannot leak data, the first two, and add the others when measurements justify the invalidation work. For monitoring hit rates, see observability and tracing.

What the video covers

ChilliCream’s “How to make GraphQL cacheable with Hot Chocolate 13?” is a nine-minute video from February 2023. Its chapters are: introduction to GraphQL caching, setting up cache control, implementing caching, persisted queries, field-level caching logic, public versus private caching, and configuring default cache settings. Those chapters follow this lesson’s CDN and cache-hint sections closely. It uses Hot Chocolate, a .NET server, so the code is not JavaScript, but the concepts of per-field hints and computed cache headers carry across; the Yoga code above is from my own run. A 2022 talk on edge caching GraphQL, by a very small channel, was dropped as too far from the lesson. I could not read a transcript.

Where this fits

This ends the security and performance group. The server is now guarded and faster. Next comes scale across teams: schema stitching and federation.

Check yourself

  1. 01Why can't a CDN cache GraphQL the way it caches REST?

    Requests are POSTs to a single URL, and the response depends on the body, so the URL does not identify what is being asked for.

  2. 02What is dangerous about a response cache for user-specific data?

    If the cache key does not include the user, one user's response can be returned to another. The key must carry the session for private fields.

  3. 03Why does a response's Cache-Control come from the least cacheable field?

    The whole response is one document. If any field is private or short-lived, caching the entire response for longer would expose or stale that field.

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark