← All tutorials
GraphQL

GraphQL

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.

The core idea. One endpoint, one strongly-typed schema, client-specified queries. It kills over-fetching and under-fetching and gives you a self-documenting contract — at the cost of new problems (caching, N+1, query-cost control) that REST solved for free. This is how it works and how to run it safely.

Foundations  The schema & type system

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 blockWhat it is
ScalarsLeaf values: Int, Float, String, Boolean, ID (+ custom, e.g. DateTime)
Object typesNamed sets of fields (User, Post) — the nodes of the graph
! and []Non-null and list modifiers — the schema is the type contract
Enum / Interface / UnionFixed value sets; shared field contracts; "one of several types"
Input typesStructured arguments for mutations (input CreatePostInput { … })
Schema-first thinking: design the graph around how clients consume data, not how your tables are laid out. The schema is a product surface and a contract — get the types and nullability right and the rest of the API follows.

The client side  Queries, mutations & subscriptions

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.

One round-trip, but one big query. The client fetching 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 server side  Resolvers

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.

How a resolver chain executes a query The query user then posts then title resolves top-down: the Query.user resolver returns a user, passed as parent to the posts resolver, then each post to the title resolver, hitting different data sources. Query.user→ fetch User(id) parent User.posts→ fetch posts of user each Post.title→ default: parent.title JSON resolvers run top-down; each field's result becomes the next field's parent a field with no resolver falls back to reading the property off parent
// (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.

The classic trap  The N+1 problem & DataLoader

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.

One loader set per request. Create fresh DataLoaders in the request 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.

Lists at scale  Pagination

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 buildYesMore boilerplate
Stable under inserts/deletesNo — rows shiftYes
Deep pagesSlow (scans & skips)Fast (seeks by cursor)
Jump to page NEasyNot directly
Cursor = keyset. A cursor is just an opaque encoding of "where we left off" (e.g. the last id/timestamp), so the DB can WHERE id > ? instead of skipping rows — the same keyset-pagination win covered in query performance.

Half-success  Errors & nullability

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" }
  }]
}
Nullability is a design decision. Marking a field non-null (!) 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.

The hard part  Caching

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:

🗂️ 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.

🌐 CDN via persisted queries

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.

⚙️ Server / field caching

Cache expensive resolver results (e.g. in Redis) with per-field TTLs, plus DataLoader's per-request cache to dedupe within a single operation.

Give objects a global 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.

Guardrails  Security & performance

A flexible query language means a client can ask for something ruinously expensive. A public GraphQL API needs these limits before it ships.

ControlStops
Depth limitingDeeply nested cyclic queries (author → posts → author → …)
Cost / complexity analysisExpensive queries — assign each field a cost, reject over a budget
Pagination capsfirst: 1000000 — enforce a max page size
Timeouts & rate limitsSlow/abusive operations exhausting the server
Persisted-query allowlistArbitrary ad-hoc queries — only pre-approved operations run
Auth per field, not per endpoint. There's one URL, so URL-based authorization is meaningless — enforce it in resolvers against the request 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.

At org scale  Federation

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!]!
}
Don't reach for it early. Federation solves an organisational scaling problem — many teams, many services. A single well-structured schema is simpler and right for most apps. Adopt federation when team boundaries, not query volume, force it.

End to end  Worked example: a blog API done right

Expose posts with their authors and paginated comments — and avoid every trap above.

Step 1 · Model the graph (with connections)

type Post {
  id: ID!
  title: String!
  author: User!
  comments(first: Int! = 10, after: String): CommentConnection!
}
type Query { post(id: ID!): Post }

Step 2 · Resolve authors with a loader (no N+1)

// 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) }

Step 3 · Enforce the guardrails

Risk in this APIGuardrail 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 exposedUser.email resolver checks ctx.user
Repeated author lookupsDataLoader batches + caches per request
Ad-hoc expensive queriesPersisted-query allowlist in production
The pattern: design the schema around the client, resolve relationships through DataLoaders, paginate lists with cursors, authorize inside resolvers, and bound every query with depth/cost limits. Do those five things and GraphQL is a joy; skip any one and it bites. Compare the whole approach against REST & gRPC in the API-styles guide.

Cheat sheet

QuestionShort 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.

Knowledge check

Six questions. Pick an answer for each, then check your score.

1. What most distinguishes GraphQL from typical REST?

2. A resolver's signature is…

3. Querying 20 posts and each post's author fires 1 + 20 DB queries. This is…

4. Where should DataLoaders be created?

5. Why is HTTP caching harder in GraphQL than REST?

6. Which is essential before exposing a public GraphQL API?

Next steps

🔗 API styles compared

REST vs GraphQL vs gRPC — when GraphQL is (and isn't) the right call.

▲ Next.js

Consume it — fetch GraphQL from Server Components.

🐘 Query performance

Under the resolvers — the N+1 & keyset pagination at the DB level.

🛡️ Web security

Lock it down — the attack surface a flexible query API opens.