Caching in GraphQL can be quite challenging. Due to the flexible and dynamic nature of GraphQL queries, caching can become very complex, especially when dealing with mutations or queries with different variables or arguments. Cache invalidation becomes crucial to ensure that clients receive up-to-date data when it changes on the server.
This is an area where REST api’s shine. Due to the static nature of the endpoints, caching can be based on the HTTP specification.
In HotChocolate caching can be done at the entity level. Therefore you need to add the HotChocolate.Caching
nuget package:
dotnet add package HotChocolate.Caching
We also have to update the GraphQL configuration:
Now we can set a [CacheControl]
attribute on our queries:
Or if you are using a code first approach:
If we now run our query, a cache control header is emitted in the response that can be used by the browser or a CDN to cache the data accordingly: