⬡ GraphQL Intermediate

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.