iTranslated by AI
Apollo Client InMemoryCache Limits and Behavior
Overview
In some cases, ApolloClient is used when implementing GraphQL with Node.js.
This article investigates the cache limits when using ApolloClient's InMemoryCache.
For an overview of ApolloClient's cache, refer to the following:
Mechanism of InMemoryCache
Specifying a Limit with resultCachMaxSize
In ApolloClient 3.x, resultCacheMaxSize can be specified to set the upper limit on the number of objects that can be stored in the cache.
Example Usage:
const cache = new InMemoryCache({ resultCachMaxSize: 5000 });
If this limit is exceeded, it is expected that items will be removed starting from the oldest referenced ones.
optimism
InMemoryCache internally uses a library called optimism.
optimism is a reactive cache, and its code can be found here:
If resultCachMaxSize is not specified in InMemoryCache, this limit defaults to "Math.pow(2, 16)".
Furthermore, by checking the following logic, it can be confirmed that items are removed starting from the oldest referenced ones.
Resetting the Cache
There are situations, such as when conducting tests, where you might want to reset the cache.
In such cases, as shown below, using client.resetStore will delete the cache.
Additionally, clearing the cache can be expected to cause unexpected behavior in parts of the application that were referencing it.
In this case, by specifying a callback with client.onResetStore, it becomes possible to set initial values when the cache is reset.
Individual Cache Deletion
In ApolloClient 3, it is possible to delete specific cache entries using evict and gc.
How to Check Cache Status from the Browser
You can check it from the following:
window.__APOLLO_CLIENT__.cache
There is also a Chrome extension available for checking the status:
Considerations on ApolloClient's Cache
As mentioned above, the cache has an upper limit, and once it reaches a certain size, items are removed starting from the oldest ones.
It is also possible to clear it explicitly.
While ApolloClient's cache can also be used to store local state, given that there is a cache limit and data may disappear, there is a risk in using this mechanism to hold data that would cause problems if lost.
Discussion