🗂️ Client cache (normalized)
Apollo Client, urql, and Relay keep a normalized cache keyed by type + id, so repeated objects are deduped and updates propagate. This is where most GraphQL caching actually happens.
GraphQL is a query language for your API and a runtime for answering those queries. Instead of many endpoints each returning a fixed shape, you expose one endpoint and a typed graph of your data — and the client asks for exactly the fields it wants, no more, no less. That flips who controls the response shape from the server to the client.
Everything starts with the schema, written in the Schema Definition Language (SDL). It defines the types, their fields, and how they connect — the graph clients are allowed to traverse. Three root types are the entry points: Query (reads), Mutation (writes), Subscription (live streams).
type User {
id: ID! # ! = non-null (guaranteed present)
name: String!
email: String
posts: [Post!]! # non-null list of non-null Posts
}
type Post {
id: ID!
title: String!
author: User! # the graph: Post → User → Posts …
}
type Query {
user(id: ID!): User # a field with an argument
posts(first: Int): [Post!]!
}
| Building block | What it is |
|---|---|
| Scalars | Leaf values: Int, Float, String, Boolean, ID (+ custom, e.g. DateTime) |
| Object types | Named sets of fields (User, Post) — the nodes of the graph |
! and [] | Non-null and list modifiers — the schema is the type contract |
| Enum / Interface / Union | Fixed value sets; shared field contracts; "one of several types" |
| Input types | Structured arguments for mutations (input CreatePostInput { … }) |
A client sends an operation that mirrors the shape it wants back. The response JSON has the same structure as the query — that predictability is a big part of the appeal.
# Query with a variable, nested selection, and an alias
query GetUser($id: ID!) {
user(id: $id) {
name
posts { title } # traverse the graph in one round-trip
}
}
# Mutation — a write, returning the fields you want back
mutation AddPost($input: CreatePostInput!) {
createPost(input: $input) { id title }
}
Reusable field sets go in fragments; Subscriptions push updates over a persistent transport (typically WebSockets) when server-side events fire.
user → posts → comments → author in a single request is the superpower — and the risk. A deeply nested query can fan out into an enormous amount of work on the server. That's what resolvers, DataLoader, and cost limits (below) exist to control.The schema says what exists; resolvers say how to fetch it. Every field can have a resolver function; the engine walks the query tree, calling each field's resolver and passing its result down as the parent of the next.
// (parent, args, context, info) => value — the resolver signature
const resolvers = {
Query: {
user: (_parent, { id }, ctx) => ctx.db.user(id),
},
User: {
// resolves User.posts using the parent user's id
posts: (user, _args, ctx) => ctx.db.postsByAuthor(user.id),
},
};
context is where auth lives. Build a per-request context (the authenticated user, DB handles, loaders) once and every resolver receives it. Do authorization in resolvers against that context — not at a single gateway — because any field can expose data.Resolvers running per-field per-item cause GraphQL's most infamous performance bug. Query 10 posts and ask each for its author: the Post.author resolver fires 10 times → 1 query for posts + N queries for authors. At scale this melts your database.
// ✗ N+1: this resolver runs once PER post
Post: { author: (post, _a, ctx) => ctx.db.user(post.authorId) }
// → SELECT * FROM users WHERE id = ? (fired N times)
// ✓ Batch with DataLoader: collect ids in one tick, one query
Post: { author: (post, _a, ctx) => ctx.loaders.user.load(post.authorId) }
// → SELECT * FROM users WHERE id IN (?, ?, …) (fired once)
DataLoader is the standard fix: it collects all the .load(id) calls made during one tick of the event loop, dispatches a single batched fetch (WHERE id IN (…)), and caches results per request so repeated ids are free.
context, never as module singletons — their cache must not leak data between users. This is the same "dedupe within a request" idea as an ORM's identity map, and it's mandatory for any non-trivial GraphQL server. The database side of this is the N+1 anti-pattern.Returning [Post!]! unbounded is a footgun. Two paginate styles exist; the GraphQL community standard is cursor-based (Relay) connections, which survive inserts and deletes that break OFFSET.
type PostConnection {
edges: [PostEdge!]!
pageInfo: PageInfo!
}
type PostEdge { node: Post! cursor: String! }
type PageInfo { hasNextPage: Boolean! endCursor: String }
type Query {
posts(first: Int!, after: String): PostConnection!
}
Offset (limit/offset) | Cursor (connections) | |
|---|---|---|
| Simple to build | Yes | More boilerplate |
| Stable under inserts/deletes | No — rows shift | Yes |
| Deep pages | Slow (scans & skips) | Fast (seeks by cursor) |
| Jump to page N | Easy | Not directly |
WHERE id > ? instead of skipping rows — the same keyset-pagination win covered in query performance.Unlike REST's single status code, a GraphQL response can be partially successful: it returns both a data object and an errors array. If a non-null field errors, the null "bubbles up" to the nearest nullable parent.
{
"data": { "user": { "name": "Ada", "email": null } },
"errors": [{
"message": "Not authorized to read email",
"path": ["user", "email"],
"extensions": { "code": "FORBIDDEN" }
}]
}
!) means an error there nullifies its whole parent — powerful but blast-radius-heavy. Use extensions.code for machine-readable error categories, and never leak internal messages/stack traces to clients in production.REST gets HTTP caching for free — a GET /posts/1 is cacheable by URL. GraphQL usually POSTs every query to /graphql, so that layer doesn't apply. You recover caching deliberately, at three levels:
Apollo Client, urql, and Relay keep a normalized cache keyed by type + id, so repeated objects are deduped and updates propagate. This is where most GraphQL caching actually happens.
Send a hash instead of the full query (Automatic Persisted Queries) and use GET, so a CDN can cache by hash — recovering edge caching for read-heavy queries.
Cache expensive resolver results (e.g. in Redis) with per-field TTLs, plus DataLoader's per-request cache to dedupe within a single operation.
id. Normalized client caches rely on stable identifiers. Expose a unique id on every object type so the client can cache and update entities precisely — it's the single most impactful thing you can do for cacheability.A flexible query language means a client can ask for something ruinously expensive. A public GraphQL API needs these limits before it ships.
| Control | Stops |
|---|---|
| Depth limiting | Deeply nested cyclic queries (author → posts → author → …) |
| Cost / complexity analysis | Expensive queries — assign each field a cost, reject over a budget |
| Pagination caps | first: 1000000 — enforce a max page size |
| Timeouts & rate limits | Slow/abusive operations exhausting the server |
| Persisted-query allowlist | Arbitrary ad-hoc queries — only pre-approved operations run |
context. Also consider disabling introspection and the GraphiQL playground in production, and cap query depth/cost, or a single crafted query can become a denial-of-service. See OWASP and web security for the broader picture.One giant schema owned by every team becomes a bottleneck. Federation (e.g. Apollo Federation) lets each team own a subgraph; a gateway composes them into one supergraph that clients see as a single API. Types can be extended across services via @key entity references.
# users subgraph owns User
type User @key(fields: "id") { id: ID! name: String! }
# reviews subgraph EXTENDS User with a reviews field
extend type User @key(fields: "id") {
id: ID! @external
reviews: [Review!]!
}
Expose posts with their authors and paginated comments — and avoid every trap above.
type Post {
id: ID!
title: String!
author: User!
comments(first: Int! = 10, after: String): CommentConnection!
}
type Query { post(id: ID!): Post }
// context created per request — loaders live here
function context(req) {
return {
user: authenticate(req), // for per-field authz
loaders: { user: new DataLoader(ids => usersByIds(ids)) },
};
}
Post: { author: (post, _a, ctx) => ctx.loaders.user.load(post.authorId) }
| Risk in this API | Guardrail applied |
|---|---|
post → author → posts → author … | Depth limit (e.g. max 7) |
comments(first: 100000) | Cap first at 50; validate the arg |
| Author's private email exposed | User.email resolver checks ctx.user |
| Repeated author lookups | DataLoader batches + caches per request |
| Ad-hoc expensive queries | Persisted-query allowlist in production |
| Question | Short answer |
|---|---|
| What is GraphQL? | One endpoint + a typed schema; clients request exactly the fields they need. |
| Three root types? | Query (read), Mutation (write), Subscription (stream). |
What does ! mean? | Non-null; an error there bubbles to the nearest nullable parent. |
| What's a resolver? | (parent, args, context, info) → the field's value. |
| The N+1 fix? | DataLoader — batch per tick, cache per request (in context). |
| Best pagination? | Cursor-based connections (edges/node/pageInfo). |
| Why is caching hard? | Single POST endpoint → no free HTTP caching; use client/CDN/field caches. |
| Must-have guardrails? | Depth + cost limits, pagination caps, per-field auth. |
| When to federate? | Team/org scaling — not query volume. |
Six questions. Pick an answer for each, then check your score.
REST vs GraphQL vs gRPC — when GraphQL is (and isn't) the right call.
Consume it — fetch GraphQL from Server Components.
Under the resolvers — the N+1 & keyset pagination at the DB level.
Lock it down — the attack surface a flexible query API opens.