A deep-dive into Apollo Client's in-memory cache: how it normalizes server responses, resolves queries from a flat entity store, handles pagination, optimistic updates, and garbage collection. This is not a tutorial — it is a system-design analysis of a client-state engine that powers thousands of production GraphQL applications.
System DesignApolloGraphQLCache
What Are We Building?
Apollo Client is the de-facto GraphQL client for the React ecosystem. Its core innovation is the InMemoryCache — a normalized, reactive, client-side data store that mirrors the shape of your GraphQL schema. When a query returns nested data, the cache flattens it into a flat map of entities, deduplicates every object, and resolves future queries from the store without hitting the network.
Understanding the cache is essential because nearly every production GraphQL pain point traces back to it: stale data, over-fetching after mutations, pagination that resets the list, and mysterious "Cache data may be lost" warnings. Once you understand the normalization engine, all of these become predictable.
Here is the basic setup — a client with an InMemoryCache configured with type policies:
The cache sits between your React components and the GraphQL server. Every query passes through it. Every mutation updates it. It is not optional — Apollo Client ships with a cache by default, and the default configuration covers most use cases. The difficulty is in customizing it correctly.
1 · Requirements & Scoping
Before diving into the implementation, let's define what the cache must do and what it explicitly should not.
Functional requirements
Normalize server responses: Flatten deeply nested GraphQL responses into a flat entity store. Each entity is stored once, keyed by __typename:cacheId.
Resolve queries from cache: Given a query document and variables, reconstruct the response by reading entities from the store and replacing references back into their original nested shape.
Diff queries against cache: Identify which fields are already in the cache and which must be fetched from the network. This is the foundation of the cache-first policy.
Update cache after mutations: Automatically merge mutation responses into the store and notify all watchers that reference the affected entities.
Support pagination: Append or prepend pages to existing lists without losing previously cached data.
Optimistic updates: Apply a predicted mutation result to the cache before the server responds, then roll it back or reconcile with the real response.
Garbage collection: Evict entities that are no longer referenced by any root query.
Non-functional requirements
Memory efficiency: No duplicated entities. A book referenced by three different queries is stored in exactly one location.
Cache consistency: If one mutation updatesBook:1, every UI component displaying that book must re-render with the new data.
No network waterfalls: A component that renders cached data should not block on unrelated queries.
Developer experience: The cache API must be introspectable in devtools, debuggable, and predictable.
Bundle size: The cache module must be tree-shakable. Apollo Client's cache is gzipped to ~26 KB.
What we are NOT building
This article focuses on the read path — how data flows from the server through the cache to the UI. We scope out the transport layer (HTTP link chain, WebSocket subscriptions), batching, persisted queries, and the Apollo Studio integration. These are important, but they are transport concerns, not cache concerns.
Tip
Apollo Client v3 introduced the modular cache API that we analyze here. V4 (still in alpha) moves to a proxy-based cache with deeper React 19 integration, but the normalization principle remains the same. The concepts here map directly to URQL's DocumentStore and Relay's RecordSource — every GraphQL cache is a normalized entity store.
2 · Architecture & High-Level Design
Apollo Cache is not a single class. It is a layered system with three tiers that sit between your components and the server.
Layer 1: The Store (data)
At the bottom is a flat Map<string, Entity> — a JavaScript Map where every key is a string like "Author:1" or "Book:42", and every value is the entity's data. There are no nested objects here; nested relationships are stored as { __ref: 'Type:id' } references. This is the same pattern used by relational databases: normalize on write, denormalize on read.
Layer 2: Policies (schema)
Above the store sits the policy layer — a set of rules that tell the cache how to interpret your schema. TypePolicy defines how entities of a type are identified (which fields form the cache key) and how their fields are merged. FieldPolicy defines custom read and merge functions for individual fields. This layer is what makes Apollo Cache configurable: you tell it "Author is keyed by ID, merge books by concatenation," and the cache handles the rest.
Layer 3: Watchers (reactive)
On top is a publisher-subscriber system. Every active useQuery call registers a "watcher" with the cache. The watcher holds the query document, variables, and a callback to re-render the component. When the cache is modified — by a mutation response, an optimistic update, or a direct cache.modify() call — the cache broadcasts to all watchers that reference the affected entities. Only the watchers whose data changed re-render.
Figure 1 — The normalized cache store. Server responses are flattened into a key-value map keyed by __typename:cacheId. Nested objects become references (__ref). No entity is duplicated.
Architecture decisions
I considered three caching strategies before settling on the normalized approach:
Option A: Document cache (rejected)
Store each query response as a JSON blob keyed by the query string + variables. This is what Apollo Client v1 did, and it is how plain HTTP caching works. The problem is that updating one entity requires finding every query that references it and invalidating the entire blob. This is O(n) on writes and destroys all unrelated data in the same query.
Option B: Normalized store (chosen)
Flatten every response into entities. Store each entity once. References replace nested objects. Reads reconstruct the tree from the flat store. This is O(1) for entity lookups, O(1) for entity updates, and O(n) for query reconstruction where n is the number of referenced entities. This is the same approach Relay pioneered and Apollo adopted in v3.
Option C: Proxy cache (future)
Apollo v4 (alpha) uses Proxies to intercept property access on the data object, lazily resolving entities from the store. This eliminates the need to explicitly reconstruct the tree on reads — the proxy handles it transparently. This is promising but makes debugging harder because the data object is no longer a plain value.
Document cache (v1)
Simple blob storage — impossible to update one entity without invalidating the whole query. Rejected.
Lazy proxy-based resolution. Less boilerplate, harder to debug. Future direction.
Key Insight
The normalized store is a textbook application of data normalization principles to client-state management. If you understand database normalization (3NF), you understand Apollo Cache — the same reasoning that eliminates duplicate rows in a relational database eliminates duplicate entities in the cache.
3 · Data Model & Store Shape
The store is embarrassingly simple: a key-value map where keys are strings and values are flat JSON objects. The complexity lies in how keys are generated and how references are resolved.
store-shape.tstypescript
// What the store looks like internally (simplified):const store: Record<string, Record<string, unknown>> = { "Author:1": { __typename: "Author", id: "1", name: "J.R.R. Tolkien", books: [ { __ref: "Book:1" }, // reference, NOT nested data { __ref: "Book:2" }, ], }, "Book:1": { __typename: "Book", id: "1", title: "The Hobbit", }, "Book:2": { __typename: "Book", id: "2", title: "The Lord of the Rings", }, "ROOT_QUERY.getAuthor({\"id\":\"1\"})": { __typename: "Author", __ref: "Author:1", // points to the entity },};
Cache key generation
Every entity gets a unique key in the format __typename:cacheId. By default, Apollo uses the id or _id field as the cache ID. If neither exists, the entity is not normalized — it is embedded inline in its parent.
You can customize key generation with keyFields in the type policy. This is critical for types that use a non-standard ID field:
When the cache normalizes a response, it replaces every nested object that has a __typename and cacheable ID with a reference object: { __ref: 'Book:1' }. The original nested data is extracted and stored as a top-level entity.
This has a critical consequence: two queries that both fetch Book:1 — even through different paths — end up reading the same entity. If one mutation updates the book's title, both UI components re-render. This is the cache consistency guarantee.
Note
The reference pattern means the cache is a graph, not a tree. Two root queries can reference the same entity, and a mutation that updates that entity will cause both queries to re-render. This is the key difference between normalized and document-based caching.
ROOT_QUERY and ROOT_MUTATION
Top-level query fields are stored under the synthetic key ROOT_QUERY. Each field + arguments combination becomes a key like ROOT_QUERY.getAuthor({"id":"1"}). The value is either a reference to a normalized entity or an inline value. Mutation results are similarly stored under ROOT_MUTATION, but these are typically transient — they are used to update the store and then the mutation root entries are evicted.
4 · Interface Definition (API)
The cache API is the surface area that application developers interact with. It is divided into three tiers: direct read/write, in-place modification, and garbage collection.
cache-api.tstypescript
// ---- Read from cache ----const cached = client.cache.readQuery({ query: GET_AUTHOR, variables: { id: "1" },});// ---- Read a fragment from a specific entity ----const fragment = client.cache.readFragment({ id: client.cache.identify({ __typename: "Book", id: "1" }), fragment: gql` fragment BookTitle on Book { title publishedDate } `,});// ---- Write directly to cache ----client.cache.writeQuery({ query: GET_AUTHOR, variables: { id: "1" }, data: { __typename: "Query", author: { __typename: "Author", id: "1", name: "J.R.R. Tolkien (updated)", }, },});// ---- Modify an entity in place ----client.cache.modify({ id: client.cache.identify({ __typename: "Book", id: "1" }), fields: { title(existingTitle) { return existingTitle.toUpperCase(); }, tags(existingTags = []) { return [...existingTags, "classic"]; }, },});// ---- Evict a single field or entire entity ----client.cache.evict({ id: "Author:1", fieldName: "temporaryField" });client.cache.evict({ id: "Book:3" });// ---- Garbage collect unreachable entities ----client.cache.gc();
readQuery / readFragment
These are the read paths. readQuery takes a query document and variables, runs the cache diff algorithm, and returns the reconstructed data — exactly as if the server had responded. If any field is missing from the cache, it returns null for that field (or the whole query, depending on the policy). readFragment reads from a single entity, identified by its cache key, and extracts only the requested fields.
writeQuery / writeFragment
These are the direct write paths. They bypass the mutation flow entirely — you provide data, and the cache normalizes and merges it into the store. This is useful for seeding the cache from localStorage or for tests. The write triggers a broadcast to all affected watchers.
cache.modify()
This is the surgical update tool. Instead of providing an entire query response, you target a specific entity and a specific field with a modifier function. The modifier receives the existing value and returns the new value. This is the safest way to update the cache after a mutation because it does not risk overwriting unrelated fields.
cache.evict() and cache.gc()
evict removes a field from an entity or the entire entity from the store. gc (garbage collection) scans the store for entities that are no longer reachable from any root query and removes them. An entity is "reachable" if any root query field or another entity references it. Entities are NOT reachable if they were loaded speculatively or if all references to them were evicted.
Warning
cache.gc() is conservative by default. It only evicts entities with zero incoming references. If you have a circular reference chain (Author → Book → Author), none of them will be collected. You must break the cycle manually or use cache.evict() first.
Field policies API
Field policies are the most powerful customization point. They let you intercept reads and writes at the field level:
field-policies.tstypescript
const cache = new InMemoryCache({ typePolicies: { Book: { fields: { // ---- Custom read: transform stored data ---- displayTitle: { read(existing, { toReference, cache }) { // Derive a computed field from existing data return existing ?? "Untitled Book"; }, }, // ---- Relative time field ---- publishedAgo: { read(existing, { readField }) { const date = readField<string>("publishedDate"); if (!date) return null; return timeAgo(new Date(date)); }, }, }, }, Query: { fields: { // ---- Pagination: cursor-based with merge ---- feed: { keyArgs: ["sortOrder"], merge(existing = [], incoming, { args, readField }) { if (args?.cursor === null) return incoming; const merged = existing.slice(0); const existingIds = new Set( existing.map((ref) => readField("id", ref)), ); for (const item of incoming) { const id = readField("id", item); if (!existingIds.has(id)) { merged.push(item); existingIds.add(id); } } return merged; }, }, // ---- Redirect from old field name ---- deprecatedPosts: { read() { // Redirect to current field return cache.readQuery({ query: GET_POSTS }); }, }, }, }, },});
The read function transforms stored data before it reaches your component. The merge function controls how incoming data is combined with existing data — essential for pagination. The keyArgs option tells the cache which arguments differentiate one field value from another; fields with the same keyArgs share the same cache slot.
5 · Deep Dive — Cache Interaction Flow
Let's trace through the full lifecycle of a query and a mutation to see how the pieces work together.
Query lifecycle
When a component calls useQuery, the following sequence runs synchronously:
Register watcher: The query manager creates a watcher with the query document, variables, and a callback. This watcher is now subscribed to cache changes.
Cache diff: The cache runs a diff algorithm against the store. It walks the query tree and for each field checks if the store has the data. References are followed to their entity and their fields checked recursively.
Full hit → return cached: If every field is present, the watcher immediately resolves with cached data. No network request. This is the fast path — O(fields) to reconstruct the tree from the flat store.
Partial miss → fetch: If any field is missing, the query is sent through the link chain to the server. The response is normalized and merged into the store. The merge triggers a broadcast to watchers.
Figure 2 — cache-first policy decision tree. Apollo diffs the query against the store. On a full hit, no network request fires. Other policies skip or augment this path.
The diff algorithm
The diff algorithm is the core of the cache read path. It takes a query document and walks the selection set depth-first. For each field:
If the field has a read function (field policy), call it with the stored value and the cache API. The result is what gets passed to the component.
If the field value is a reference ( { __ref } ), follow it to the referenced entity and recurse into its fields.
If the field value is a reference array (e.g., books), follow each reference individually.
If the field is a scalar, return the stored value directly.
If the field is missing from the store, mark it as "missing" in the diff result. The query manager uses this to decide whether to fetch.
Figure 3 — Query lifecycle. A query passes through cache read, link chain, and server response normalization before merging into the store and broadcasting to all dependent watchers.
Normalization on write
When data arrives from the server (or from cache.writeQuery), the cache runs the normalization pipeline:
Walk the response tree depth-first.
For each object with __typename: generate its cache key via keyFields. If no key can be generated, the object stays inline (not normalized).
Extract the entity from its parent and store it at its key in the entity store. Replace the nested object with a reference ({ __ref: 'Type:id' }).
Call the field-level merge function if one is defined. For paginated fields, this appends or inserts the incoming data into the existing array.
Store the root query field under ROOT_QUERY with the field name and arguments as the sub-key.
Mutation update strategies
Mutations are the primary way the cache changes. Apollo provides three strategies:
A. Automatic merge: If the mutation response contains an entity with a cacheable ID, the cache automatically normalizes and merges it into the store. Any watchers referencing that entity re-render. This works out of the box — no update function needed.
B. Manual update function: For complex updates — like inserting a new item into a list or removing a deleted item — you provide an update callback that receives the cache instance. You call cache.modify() or cache.writeQuery to update the store.
C. refetchQueries: The nuclear option. After the mutation completes, re-fetch specific queries from the server. This is the safest but slowest approach — it guarantees cache consistency at the cost of a network round-trip.
Figure 4 — Three mutation update strategies. Automatic merge (simplest), manual cache.modify() (most flexible), and refetchQueries (most expensive but safest). All three converge on store update → broadcast.
Optimistic updates
Optimistic updates are the cache's superpower. They let you apply a predicted mutation result to the store immediately, before the server responds. If the server confirms the mutation, the optimistic data is replaced with the real response. If the server rejects it, the optimistic changes are rolled back.
optimistic-update.tstypescript
function AddTodoForm() { const [addTodo] = useMutation(ADD_TODO, { // ---- Optimistic update: render instantly ---- optimisticResponse: { __typename: "Mutation", addTodo: { __typename: "Todo", id: -1, // temporary id; server returns real one text: "", completed: false, }, }, // ---- Update cache after mutation ---- update(cache, { data }) { // Read existing todos from cache cache.modify({ id: cache.identify({ __typename: "Query" }), fields: { todos(existingTodos = []) { const newTodoRef = cache.writeFragment({ data: data.addTodo, fragment: gql` fragment NewTodo on Todo { id text completed } `, }); return [...existingTodos, newTodoRef]; }, }, }); }, // ---- Handle server response ---- onCompleted({ addTodo }) { // Server returned the real todo with real id // Apollo automatically replaces the optimistic entity console.log("Todo created:", addTodo.id); }, }); const handleSubmit = (text: string) => { addTodo({ variables: { text } }); }; return <TodoForm onSubmit={handleSubmit} />;}
Behind the scenes, Apollo creates a "forged" layer in the cache that overlays the optimistic data on top of the real data. All reads go through this overlay. When the real response arrives, the overlay is removed and the real data takes its place. The transition is seamless — React components see a single state change from optimistic to confirmed.
Key Insight
The optimistic overlay is implemented as a separate layer in the entity store, not as a mutation of existing data. This means rollback is O(1) — just remove the overlay. This is the same pattern used by Git's staging area: you stage changes (optimistic), commit them (server confirms), or discard the staging area (server rejects).
Pagination patterns
Pagination is where most cache misconfigurations happen. The default behavior replaces the existing list with the new one on every fetch. For pagination, you must provide a merge function in the field policy.
Apollo supports two pagination models:
Offset-based: You track a page or offset variable. The merge function places incoming items at the correct offset index. The keyArgs option ensures different pagination endpoints (e.g., by search query) have separate cache slots.
Cursor-based: Each item has a cursor. Themerge function appends items that are not already in the list, deduplicating by ID. This is the GitHub GraphQL API pattern.
6 · Performance Optimization
The normalized cache is already an optimization over document-based caching, but there are several ways to tune it.
Entity deduplication
This is the biggest win. Without normalization, two queries that both fetch Author:1 would store two copies of the same data. With normalization, the author is stored once and both queries reference it. For deeply nested schemas, this reduces memory usage by 40-60% depending on the overlap between queries.
Dependency tracking (watchers)
Each watcher tracks which entities it depends on. When a mutation updates Book:1, the cache only notifies watchers that reference Book:1. A watcher for Author:2 is not notified. This precision is essential for performance: a mutation that updates one entity should not cause the entire page to re-render.
Garbage collection strategy
The cache grows over time as the user navigates. Without GC, every entity ever loaded stays in memory. Apollo's GC marks entities that are reachable from any root query field, then sweeps the rest. You can tune this with the cache.gc() call, which returns an array of evicted IDs for debugging.
Cache-first vs cache-and-network
The default cache-first policy means the UI renders immediately from cache if data exists, with zero network latency. This is the same tradeoff as HTTP caching: freshness vs latency. For data that changes frequently (like user notifications), use cache-and-network to show cached data first and update in the background.
Complex read path (tree reconstruction), merge functions required for pagination
Proxy cache (v4)
Transparent reads, less boilerplate than normalized
Proxy objects break serialization, harder to debug
cache-first
Zero-latency renders, no network for cached data
Stale data until background refetch
cache-and-network
Instant render + fresh data
Always fires a network request (even on cache hit)
7 · Security Considerations
The cache is a client-side store of server-provided data. Its security surface is smaller than a DOM component's, but there are real risks.
Sensitive data in cache: The cache retains data in memory for the lifetime of the page. If the user logs out, cached queries from the previous session are still in memory. Always call client.cache.reset() on logout to clear the store. For sensitive fields (SSN, credit cards), mark them with @deprecated or use field-level policies to exclude them from caching.
Persisted cache attacks: If you persist the cache to localStorage (via apollo3-cache-persist), an XSS attacker can read the cache contents. Treat persisted cache data as user-controllable — validate types and lengths on restore.
Cache poisoning via error responses: If your error handling writes partial data to the cache, a malicious server response could inject incorrect data. Apollo v3+ does not write to cache when errors are present in the response, but custom update functions may bypass this guard.
Timing side channels:cache-first responses are synchronous and instantaneous. Network responses have measurable latency. An attacker who can observe render timing can infer whether data was cached — and thus whether the user has accessed that data before. For sensitive applications, artificially delay cache responses to mask this signal.
Warning
If you persist the Apollo cache to localStorage, the persisted data is accessible via window.localStorage to any JavaScript running on the page. This includes third-party scripts and extensions. Do not cache auth, token, or any field whose exposure would be a security incident.
8 · Testing Strategy
Apollo provides MockedProvider for testing components in isolation. The mock replaces the real link chain with a fake one that returns predefined responses. The cache still normalizes and stores the data — you can verify both the rendered output and the cache state.
The tests I consider essential for any cache-dependent component:
Render from cache: Verify that a query with all data cached renders immediately without a loading state.
Cache update after mutation: Fire a mutation, verify the UI updates with the new data without a second network request.
Optimistic update rollback: Fire a mutation that fails on the server, verify the UI reverts to the pre-mutation state.
Pagination merge: Load page 1, then page 2, verify that both pages are visible and not duplicated.
Cache eviction: Evict an entity, verify the component shows an error or loading state (depending on the component's handling).
Cross-query consistency: Two components displaying the same entity must both update when the cache changes.
Note
Use MockedProvider with addTypename: true. If you omit __typename from mock responses, the cache cannot normalize the data and falls back to inline storage — which breaks the deduplication guarantee and may produce false negatives in your tests.
9 · Key Takeaways
Normalization is the core insight. A flat entity store with references gives you O(1) entity lookups, automatic deduplication, and precise cache broadcasting — exactly what a document cache cannot provide.
Type policies are required for non-standard IDs. If your schema uses _id, slug, or composite keys, you must configure keyFields. Otherwise the cache cannot normalize those types and they stay inline.
Field policies are required for pagination. Without a custom merge function, each page fetch replaces the previous page. The keyArgs option keeps different pagination endpoints separate.
cache.modify() is safer than writeQuery. When updating the cache after a mutation, prefer targeting specific fields with modifier functions. writeQuery requires the entire query tree and can overwrite unrelated data.
Optimistic updates use a staging layer. Apollo's optimistic overlay is a separate layer on top of the real entity store. Rollback is O(1) — just remove the overlay. This is identical to Git's staging area model.
Garbage collection requires conscious design.cache.gc() only evicts entities with zero incoming references. Circular references prevent collection. Call evict() first for the types you want to remove.
Cache consistency is the killer feature. Two queries referencing the same entity will both update when that entity changes. This is the primary reason to use a normalized cache over a document cache or plain global state.
Reset the cache on logout.client.cache.reset() clears the entire store. Failure to do so leaves the previous user's data in memory, accessible via the devtools or a timing side channel.
Apollo's InMemoryCache is not just a cache — it is a client-side data engine that applies relational-database principles to GraphQL state management. The normalized store, type policies, field policies, and watcher system form a coherent architecture that makes a difficult problem — keeping a UI consistent with server state — feel inevitable. Once you understand how the store works, every "cache not updating" bug report becomes a predictable consequence of a missingmerge function or a misconfigured keyFields.