Shopify2023-10-18Explainer
Apollo Cache is Your Friend, If You Get To Know It
Summary
Shopify’s migration from Apollo GraphQL client 2 to client 3 prompted a closer examination of the Apollo InMemoryCache after past bugs were linked to misunderstanding or misuse. The cache stores an in-memory representation of queried data for the current browser session, and its lifecycle covers fetching, normalization, updating and merging, then garbage collection and eviction. Fetch policies determine whether data comes from the cache, the network, or both; under the default cache-first policy, incomplete data triggers a network request. Normalization breaks responses into objects, assigns cache identifiers usually from __typename and id or configured key fields, and stores them in a flattened structure. Automatic UI updates depend on matching identifiers and suitable query or mutation responses, while objects made unreachable by changed identifiers can remain until garbage collection removes them.
Context
Shopify was migrating from Apollo GraphQL client 2 to client 3, prompting discussion of past bugs commonly connected to misuse or misunderstanding of the cache. The post focuses on understanding how cached objects are fetched, transformed, stored, updated, and removed.
Approach / What changed
The post explains the Apollo InMemoryCache through an object lifecycle: fetching according to fetch policies, normalization into uniquely keyed objects in a flattened structure, merging and updating data from queries or mutation responses, and garbage collection and eviction of unreachable objects. It also uses a pixelated Pikachu example to show how changed identifiers can orphan earlier cached objects.
Takeaways
With the default cache-first policy, Apollo returns cached data when all requested data is present; otherwise it queries the network, saves the response in the cache, and returns it.
Normalization assigns cache identifiers normally from __typename and id, while the keyfields API supports other stable, reproducible field combinations for objects without suitable id fields.
Automatic UI updates require incoming data to match cached identifiers and include the relevant fields; objects with replaced identifiers can become unreachable and later be removed by garbage collection.
Source and freshness
- Source
- shopify.engineering
- Published
- Added to Yomu
- Last updated
Summaries are generated from the original by a language model. Check the original before relying on it.
Keep reading
Related reading
The Good Stuff
Paid picks we use ourselves. Links carry a referral code — a subscription through one earns us a commission at no extra cost to you.
The best engineering reads, once a week
One useful email. Unsubscribe anytime.