GraphQL · Concept
Caching a GraphQL API
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
Our home screen comes from GraphQL, and every request is a POST to /graphql, so the CDN caches nothing. How can you cache a GraphQL API, and at which layers?
Then
Follow-ups the interviewer asks next
- Why doesn't HTTP caching work out of the box?
- What are persisted queries, and how do they help the CDN?
- The home screen has a public part and a personal part. How do you cache it?
- What does a client cache do differently?
- Can you cache inside the server, and what goes wrong?
- How do you invalidate when a restaurant changes its menu?
The answer
What a strong answer covers
- HTTP caches key on method and URL; a POST with the query in the body isn't cached. GraphQL queries can use GET with the query in the URL, but long documents hit URL size limits.
- Persisted queries: the client sends a hash or id instead of the whole document (trusted documents registered at build time, or automatic persisted queries). With GET and a short id, the CDN can cache by URL, and the server can refuse unknown queries.
- Cache hints: the server computes
Cache-Controlfrom per-field hints; the shortest max-age wins, and any private field makes the whole response private. - Split the screen: a public query (restaurants for a city) cached at the CDN for a short time, and a personal query that isn't;
@deferfor slow personal parts where the server supports it. - Client caches (Apollo Client, Relay, urql) normalise objects by type and id, so updating one object refreshes every screen that shows it.
- Server side: a response cache keyed by query, variables and user or role, or caching the data sources below resolvers (Redis). DataLoader's cache lasts one request only.
- Invalidation: TTLs plus purge by tag (restaurant id) at the CDN when a menu changes, or event-driven deletes in Redis.
The red pen
Common traps
Avoid:caching personal data at a CDN; calling DataLoader a cross-request cache; "GraphQL can't be cached".
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.