Lesson 21 / 25
Caching Strategies
Server, HTTP and client caches.
Cache at several layers
GraphQL responses are harder to cache at the HTTP layer because one endpoint serves many queries, but there are options. Send queries with GET (or automatic persisted queries using hashes) so CDNs can cache public responses, and add cache hints per type or field to compute a response max-age. Inside the server, DataLoader caches per request, and resolvers can use shared caches (Redis) for expensive lookups. On clients, normalised caches avoid refetching. Never cache user-specific responses in shared caches.
Cache hints in the schema
Apollo-style cacheControl directive (requires server support).
type Product @cacheControl(maxAge: 300) {
id: ID!
name: String!
price: Money!
stock: Int! @cacheControl(maxAge: 10) # changes often
myReview: Review @cacheControl(scope: PRIVATE) # user-specific
}
# the response max-age is the minimum of all fields requested;
# any PRIVATE field makes the whole response non-shareableSeparate public and private data
Queries mixing per-user and public data cannot be cached publicly; split them where caching matters.
Quick check: Why is HTTP caching harder for GraphQL than for REST?
- GraphQL responses are binary
- Many different queries share one endpoint, often sent with POST
- GraphQL forbids caching
- Browsers do not support GraphQL
Answer
Many different queries share one endpoint, often sent with POST — Use GET, persisted queries and hints.