0
0
GraphQLquery~5 mins

Response caching strategies in GraphQL

Choose your learning style9 modes available
Introduction

Response caching helps save time by storing answers to repeated questions. This means faster replies and less work for the server.

When many users ask the same question often, like fetching popular product details.
When data changes slowly, so cached answers stay useful for a while.
When you want to reduce server load during busy times.
When you want to improve user experience by giving quick responses.
When you want to save bandwidth by not sending the same data repeatedly.
Syntax
GraphQL
type Query {
  book(id: ID!): Book @cacheControl(maxAge: 60)
}

# or using HTTP headers for caching
# Cache-Control: max-age=60
Use @cacheControl(maxAge: seconds) directive in GraphQL schema to set caching time.
HTTP headers like Cache-Control can also control caching behavior.
Examples
This caches the user query response for 120 seconds.
GraphQL
type Query {
  user(id: ID!): User @cacheControl(maxAge: 120)
}
This caches the latest news for 30 seconds, good for frequently updated data.
GraphQL
type Query {
  latestNews: [News] @cacheControl(maxAge: 30)
}
This HTTP header tells the client to cache the response for 5 minutes.
GraphQL
# HTTP header example
Cache-Control: max-age=300
Sample Program

This GraphQL query asks for popular books. The @cacheControl(maxAge: 60) directive caches the response for 60 seconds, so repeated requests within that time get faster answers.

GraphQL
type Query {
  popularBooks: [Book] @cacheControl(maxAge: 60)
}

# Query
{
  popularBooks {
    title
    author
  }
}
OutputSuccess
Important Notes

Cache duration should match how often data changes to avoid showing old info.

Use caching carefully for sensitive or user-specific data to avoid leaks.

Combining server-side and client-side caching can improve performance.

Summary

Response caching stores answers to speed up repeated requests.

Use @cacheControl directive or HTTP headers to set caching time.

Choose caching times based on how fresh your data needs to be.