Caching GraphQL APIs trough custom proxy
Author: Jakub Sydor
Problem context
Caching GraphQL APIs can be a challenging task due to the nature of the GraphQL query language. Unlike REST APIs where each endpoint has a unique URL, GraphQL allows for a single endpoint to return different results based on the shape of the query. This makes it difficult to cache the results of a query because the same query could return different results based on the arguments passed in or the context of the request.
Additionally, GraphQL allows for real-time updates through subscriptions, making it difficult to determine when the cache should be invalidated.
Despite these challenges, there are limited tools available for caching GraphQL APIs. The most popular of these is Apollo Server, which provides a caching layer that can be used to cache the results of frequently requested queries. However, this caching layer is not suitable for all use cases.
To achieve caching in a GraphQL API, one approach is to implement a custom caching layer on top of the GraphQL server. This layer can store the results of frequently requested queries and return them from cache instead of executing the query again. The cache can be invalidated based on a set of rules or events, such as a specified time interval or the mutation of a related data source.
In one of our projects we were using Strapi as a headless CMS with GraphQL API. We were facing the problem of caching GraphQL API, as it was not possible to use Apollo Server caching layer. We decided to implement a custom caching layer on trough a custom proxy server.
In this article we will explore how to implement a custom caching layer for a GraphQL API using Node.js and Redis.