The Apollo cache
How InMemoryCache normalizes responses into entities keyed by typename and id, why one edit shows up everywhere, and how keyFields and eviction work.
The Apollo cache
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- InMemoryCache splits each response into entities and stores each once, under a key built from __typename and id.
- Nested objects in a stored entity become references like { __ref: "Author:1" }, so one edit is visible to every query that mentions it.
- An object with no id, or whose key fields are missing from the query, is stored inside its parent and cannot be shared or updated alone.
- keyFields in typePolicies changes the identity of a type, for example to an isbn.
- Evicting an entity leaves dangling references, and a query that depends on it reads as incomplete until it is refetched.
The problem a cache has to solve
A query response is a tree. The same book can appear in a list of books, on its own detail page, and inside an author’s profile. If the cache stored each response as a tree under the query that produced it, those three copies would drift apart. Rename the book on the detail page and the list still shows the old title.
The fix is the one relational databases use: store each thing once and point at it. That is normalisation, and it is the heart of Apollo’s cache.
What the cache actually holds
I ran the books query from the previous lesson against a local Yoga server with @apollo/client 4.3.8 and printed client.cache.extract(). The keys were:
Author:1, Book:1, Author:2, Book:2, ROOT_QUERY
and the Book:1 entry was:
{ "id": "1", "__typename": "Book", "title": "Dispossessed", "author": { "__ref": "Author:1" } }
Three ideas are visible there. Each object with a __typename and an id becomes its own entry, keyed Typename:id. A field whose value is another entity holds a __ref pointing at that key. And ROOT_QUERY holds the entry point: which root fields were fetched, with their arguments, each pointing into the entities.
Apollo adds __typename to every selection set automatically, which is why you never wrote it. You do have to ask for id. That is the practical rule behind the cache: if an object is missing its identifier from your query, Apollo cannot give it a key, so it stores the object inside its parent and treats it as unshareable.
Why edits show up everywhere
To see the payoff, I wrote a fragment straight into the cache:
client.writeFragment({
id: "Author:1",
fragment: gql`fragment A on Author { name }`,
data: { __typename: "Author", name: "Ursula K. Le Guin" },
});
Reading the original books query afterwards returned the new name for the first book’s author, with no request. One entity changed, and every query that points at Author:1 reads the new value. That is also the reason a mutation that returns the updated object, with its id, usually fixes your UI for free: the response is merged into the entity, and every subscribed component re-renders. The next lesson uses this.
Changing identity with keyFields
The default key is __typename plus id. Some types do not fit. In a test with typePolicies: { Book: { keyFields: ["isbn"] } }, the book was stored as Book:{"isbn":"978"}. keyFields can name several fields, and you can write a function for odd cases. Types with no sensible identity, such as a Money or Coordinates object, are better left unkeyed so they live inside their parent. Type policies also handle fields: read and merge functions customise how a field is read or combined, which is where pagination helpers live, and you will meet them again with relay-style connections.
Eviction and garbage collection
The cache does not clean up on its own schedule. cache.evict({ id }) removes an entity, and cache.gc() removes entries nothing can reach any more. In my test I evicted Author:1. The Book entry survived and kept its author: { __ref: "Author:1" }, now dangling. Calling cache.gc() returned nothing to collect, since the book still referenced the author’s key. Then readQuery on the original query returned null, because the cache could no longer answer it in full.
That last behaviour is the one to remember. Missing data is not an error in the cache; it just means a cache-first query will go back to the network, as covered in the basics lesson. Evict when you know something is gone, such as after a delete, and expect the next read to refetch.
Reading and writing by hand
Beyond extract(), the useful calls are readQuery, writeQuery, readFragment, writeFragment and cache.modify. Prefer a mutation response that carries the new data over hand-edited cache writes. Reach for manual writes when the server response cannot describe the change, such as appending a created item to a list that was fetched earlier.
What the video covers
Raman Lally’s talk at GraphQL Summit 2022, published by Apollo in April 2023, runs about eight minutes. Its chapters are: introduction to caching, fetch policies, normalizing and keys, the flattened cache structure, automatic cache updates, manual update scenarios, garbage collection, and eviction. That order maps closely to this lesson. It is a short conference talk, so expect an overview rather than a worked example with merge functions. I read the chapter list, not a transcript.
Where this fits
The cache decides what the UI can show without asking the server. Next, mutations and optimistic UI uses it to show a change before the server confirms it. If you have used a key-based cache in React, cache invalidation and mutations is the same problem seen from the other side.
Check yourself
Why does Apollo ask for __typename and id on every object?
They form the cache key. Without them an object cannot be stored as a shared entity, so it cannot be updated in one place.
What does the cache store for a field whose value is another entity?
A reference to that entity's key, not a copy of its data.
What happens to a query that depended on an evicted entity?
The cache can no longer satisfy it completely, so reading it from the cache returns null or incomplete data until a network request fills the gap.
When would you configure keyFields?
When a type is identified by something other than id, or by several fields together, such as an isbn.
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.