How do you implement field-level caching with cache hints in GraphQL?
Answer
GraphQL doesn't have native HTTP caching since all queries are POST requests to a single endpoint. Apollo Server's cache control plugin allows setting cache hints per field that propagate to the overall response. In the schema: type Query { publicPosts: [Post!]! @cacheControl(maxAge: 60) } type Post @cacheControl(maxAge: 300) { id title }. Or programmatically in resolvers: info.cacheControl.setCacheHint({ maxAge: 60, scope: 'PUBLIC' }). The response includes Cache-Control: max-age=60, public headers (for GET persisted queries). CDNs like Cloudflare or Fastly can then cache responses. scope: PRIVATE prevents CDN caching for user-specific data. The minimum maxAge across all fields in the query is used. This works best with persisted queries (GET requests) since POST requests aren't normally cached by CDNs.
Previous
What is deferred query execution in GraphQL?
Next
What is Apollo Federation v2 and how does the supergraph work?
More GraphQL Questions
View all →- Intermediate How do you implement pagination in GraphQL?
- Intermediate What is the Relay specification in GraphQL?
- Intermediate How do you implement authorization in GraphQL resolvers?
- Intermediate What is graphql-shield and how does it work?
- Intermediate How do you implement real-time subscriptions with GraphQL?