GraphQL Cache Normalization Explained: __typename, Composite Keys & Stale List Invalidation
Document-level caching (storing raw JSON responses keyed by query string and variables) is easy to implement, but it breaks down the moment a single entity appears in two views. Update a user's display name on a profile screen, and the sidebar header still renders the old string until the user hard-refreshes. Normalized caching fixes this by flattening nested GraphQL trees into an identity table—so every component reading the same object observes updates immediately.
1. How Entity Identity Works (__typename + Primary Key)
To merge two different query responses cleanly, the client must uniquely identify every object node in the graph. It does so by automatically injecting the meta-field __typename defined in the GraphQL Type Name Introspection specification alongside an object's identifier field (typically id or _id):
| GraphQL Object Shape | Normalized Cache Key | Behavior When Re-Fetched |
|---|---|---|
{ __typename: "User", id: "42", name: "Ada" } |
User:42 |
Fields shallow-merged into one shared record across all active views |
{ __typename: "ProjectMember", orgId: "7", userId: "42" } |
ProjectMember:7:42 |
Requires custom composite keyFields in ClientOptions |
{ __typename: "Money", amount: 1990, currency: "USD" } |
Embedded value object (no ID) | Stored inline under its parent field path; never merged globally |
2. Configuring Composite Keys Without Breaking Proxy Tracking
When a schema exposes join-table records or multi-tenant objects without a single global id column, configure custom identifier extraction in normalization.keyFields. In a proxy-driven client (see How ES6 Proxy Query Generation Works), declaring key fields guarantees that the query builder silently appends those fields to every selection targeting that type:
import { createClient } from 'gqless';
import { generatedSchema, scalarsEnumsHash } from './schema.generated';
export const client = createClient({
schema: generatedSchema,
scalarsEnumsHash,
normalization: {
identifier(obj) {
if (obj.__typename === 'ProjectMember' && obj.orgId && obj.userId) {
return `ProjectMember:${obj.orgId}:${obj.userId}`;
}
return undefined; // fall back to default __typename:id
},
keyFields: {
ProjectMember: ['orgId', 'userId'],
InvoiceLine: ['invoiceId', 'lineNumber'],
},
},
});
PageInfo, DateRange, or PriceBreakdown. Merging two unrelated PageInfo objects into a single cache slot will corrupt cursor pagination across concurrent tabs.
3. The Hardest Problem: Stale Lists After Create & Delete Mutations
Updating an existing entity's scalar fields propagates automatically because every list holds a pointer to User:42. Creating or deleting an entity, however, changes list membership—the normalized store cannot guess whether a newly created Issue belongs inside issues(status: "OPEN", label: "bug") or issues(assignee: "me").
- Targeted query refetching: For small-to-medium lists, invalidating the parent query root after a mutation is safer and simpler than hand-writing brittle reducer logic for every filter combination.
- Optimistic removal on delete: Evict the deleted entity's normalized key immediately so dangling references disappear cleanly while the background list refetch settles.
- Hydrating normalized snapshots in SSR: When serializing server-rendered data to the browser with
prepareRenderand cache hydration, ship the normalized graph rather than raw query payloads so client mutations seamlessly merge into SSR-hydrated records on first interaction.