Posted in

How to implement caching in Relay?

If you’ve ever built a frontend application that pulls dynamic data from a GraphQL API, chances are you’ve dealt with slow load times, redundant network calls, or broken state when the same data gets updated across different parts of your app. For teams relying on Relay—a JavaScript framework built specifically for GraphQL—caching isn’t just a performance optimization; it’s the backbone of a smooth user experience. As a Relay provider that’s worked with dozens of engineering teams to ship scalable apps over the past five years, I’ve seen firsthand how misconfigured caching can turn a clean Relay setup into a source of frustration. This post is a step-by-step guide to implementing caching in Relay the right way, from understanding how Relay’s cache works to tuning it for your app’s unique needs. Relay

First, let’s ground this in what Relay’s cache actually is, because it’s not a traditional browser or server cache you might be used to. Unlike REST, where caching usually sits between your app and the API (like HTTP caches or localStorage), Relay’s cache is a normalized client-side store. That means it stores data as a graph, not a flat blob: every entity (say, a User or a Post) gets a unique ID, and related data is linked to that ID instead of being duplicated in every query that references it. For example, if two components fetch data for the same User with ID 123, Relay will pull that user’s details from the cache for the second component, no network call needed. That normalization is key to avoiding redundant data and keeping your app’s state consistent.

The first step to implementing caching in Relay is setting up the cache itself during your Relay environment configuration. If you’re using Relay Modern (the current stable version), you’ll work with the RelayNetwork and RelayStore modules that make up your environment. Most teams start with a basic in-memory store, but that’s only enough for simple apps. Let’s walk through a minimal working setup first: when you initialize your Relay environment, you’ll define a Store with a DataWriter that handles how data is written to the cache, and a Reader that handles how it’s read. A common mistake here is skipping custom configuration, which can lead to cache bloat or stale data. For example, setting a garbage collection (GC) policy is non-negotiable for apps that load large datasets. By default, Relay’s GC runs in the background and removes unused data from the cache, but you can customize when it runs. If you don’t, a long-lived app (like a project management tool where users load hundreds of tasks) will eventually run out of memory. I usually recommend setting a custom gcReleaseBufferSize when creating the store: this is the number of unused objects the cache will hold before triggering a GC. For most apps, 10,000 is a safe baseline, but for apps with heavy media (like photo galleries), you might bump that to 20,000 to avoid unnecessary evictions mid-session.

Next, you need to align your queries and mutations with Relay’s cache policy. Even the best store configuration won’t work if your GraphQL operations don’t play nicely with the normalized structure. Here’s where most teams slip up: if your query doesn’t include the unique id field for every entity, Relay can’t normalize it, so it can’t cache it correctly. For example, a query like query GetUser { user { name } } will never be cached properly, because there’s no id to key the user’s data against. Relay will treat every request for that user as a new entity, leading to duplicate data and wasted network calls. I always train our clients to enforce that every top-level field in a query has a globally unique identifier, and that nested objects also include id if they’re referenced across multiple components. Another critical point for mutations: when you update or delete an entity, you need to tell Relay how to modify the cache, not just expect it to refetch data on its own. Relay’s commitMutation API lets you specify an updater function that directly edits the cache, which is way faster than a full refetch. For example, if you’re deleting a comment, your updater can remove that comment’s ID from the list of comments for its parent post, and remove the comment’s data entirely from the cache. Skipping this step leads to stale data: a user might see a deleted comment in one part of the app, even though the API already removed it.

Once your basic cache is set up, you can move to more advanced caching patterns tailored to different app needs. For apps that need to persist data across page reloads (so users don’t re-fetch data when they navigate), Relay supports integrating with localStorage or IndexedDB via a cache persist strategy. This is a game-changer for e-commerce sites, where users often return to their cart or past orders. A common approach is to serialize the Relay store to JSON on unload, and deserialize it back into the store when the app initializes. But here, too, there’s a right and wrong way: I’ve seen teams try to persist the entire cache, which works fine for small apps but leads to slow initial load times for large datasets. Instead, you should only persist data that’s user-specific and not likely to change frequently, like saved preferences, profile details, and cart items. For public data (like product listings or blog posts), you can rely on network-level caching alongside Relay’s client-side cache to reduce the amount of data you need to persist. Another advanced pattern is partial caching for long lists, like a feed of posts or a list of users. Relay supports pagination with connections, and you can configure the cache to keep the most recent N pages in memory, while evicting older pages to save space. For example, if your feed loads 20 posts per page, you can set the cache to keep the last 3 pages, so a user scrolling back doesn’t have to re-fetch posts they already viewed.

But caching isn’t just about storing data—it’s about invalidating it at the right time. Stale cache data is one of the top complaints I hear from teams using Relay, and it almost always boils down to bad invalidation rules. Relay’s default cache invalidation works on a time-to-live (TTL) for individual queries, but you can customize this with fetchPolicy when you run a query. The fetchPolicy parameter lets you choose how Relay interacts with the cache for a specific request: store-or-network (the default, uses cache first, falls back to network), network-only (bypasses cache entirely), store-only (never hits the network), and cache-first (uses cache, only hits network if data is missing). For data that rarely changes, like a product catalog, you can use cache-first to avoid network calls entirely. For data that updates frequently, like real-time chat messages, you’ll use network-only to ensure the latest data is always fetched, but you can pair that with a short TTL (a few seconds) so that even if you do use the cache, it’s not outdated. A trick I recommend for dynamic data is tag-based invalidation: when an entity updates (like a post being edited), you can add a tag to that entity’s cache entry, and configure Relay to invalidate any query that includes that tag. This is more flexible than TTL, because you don’t have to guess how often data will change—you can invalidate it exactly when it updates via your mutation. For example, when your backend sends a POST_UPDATED event via WebSocket, you can trigger a cache invalidation for all queries that include that post’s ID, so components automatically refresh with the new data.

I should also address common pitfalls that even experienced Relay developers run into. First, cache normalization errors: if two different entities end up with the same ID, Relay will merge their data, leading to broken states. For example, if a User and an Admin type both use the same ID field, or if a nested object accidentally uses the wrong ID, Relay will treat them as the same entity. I always suggest using Relay’s debug tools (the Relay DevTools browser extension) to inspect the cache during development: it lets you see exactly how entities are stored, their relationships, and which queries are pulling data from them. Another pitfall is over-caching: caching data that’s too granular, or caching data that should be ephemeral (like a temporary form draft). For ephemeral data, it’s better to use component-level state (like React’s useState) instead of the Relay cache, to avoid bloating the store with data that doesn’t need to be shared across components. Finally, don’t forget about server-side caching if you’re using Relay with a backend that supports it. Relay works great with GraphQL endpoints that support HTTP caching, so combining Relay’s client-side cache with an HTTP cache for public queries can cut network load times even further.

As a Relay provider, I’ve worked with teams of all sizes, from startups building their first React app to enterprise teams scaling multi-tenant platforms, and the teams that get the most out of Relay’s caching setups are the ones that treat it as part of their overall data strategy, not just a feature to enable. It’s not enough to just turn on caching and hope for the best—you need to configure the store to fit your app’s memory constraints, align your operations with the normalized cache structure, set clear invalidation rules, and use the right fetch policies for each type of data. The result is an app that feels fast, consistent, and reliable, with fewer network calls and less state management overhead.

Plastic Case and Terminal Block If you’re looking to implement or optimize caching in your Relay setup, or you want to avoid the common mistakes that lead to stale data or bloated caches, our team of Relay experts is here to help. We work with teams to audit their current caching strategies, customize their store configurations, and build scalable setups that grow with their apps. Get in touch to discuss your specific needs and how we can support your project.

References

  1. Relay Documentation: Cache Configuration
  2. Relay Modern: Garbage Collection Guide
  3. GraphQL.org: Normalized Caching Best Practices
  4. React Blog: Working with Client-Side Caching in Relay

Jian Xin Technical Limited
Jian Xin Technical Limited is well-known as one of the leading relay manufacturers and suppliers in China. If you’re going to buy high quality relay with low price, welcome to get pricelist from our factory. Also, customized service is available.
Address: Jianxin Industry Park, Longtan Load, Yuhang District, Hangzhou, China. 311121
E-mail: marketing@jianxintechnical.com
WebSite: https://www.jianxintechnical.com/