Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 133 ยท Frameworks and Ecosystem

GraphQL Servers

Learn how a GraphQL server works in Node.js - schema, queries, mutations, resolvers, partial errors, the N+1 problem and the DataLoader batching pattern, with a runnable hand-written mini server.

In a REST API, the server decides what each URL returns. A screen that needs a book, its author and the author's other books may need three requests, or one request that returns far more data than the screen uses. GraphQL turns this around. The server publishes a typed schema that describes everything that can be asked, and the client sends a query that names exactly the fields it wants. The answer has the same shape as the question, in one round trip.

Over HTTP, a GraphQL server is surprisingly plain: usually a single endpoint, POST /graphql, with a JSON body like { "query": "{ authors { name } }" }, and a JSON reply with data and, if something went wrong, errors. The interesting part is what happens inside: how the server walks the query, calls small functions called resolvers to fetch each field, and avoids asking the database the same thing hundreds of times.

In production you would use a library (graphql for the core, GraphQL Yoga, Apollo Server or graphql-http for serving). Our editor has no npm packages, so this lesson does something better for learning: it builds a small but real GraphQL-style server by hand, so that the library's behavior stops being magic. Compare it with the REST style in REST API Design as you go.

The schema and the query language

A schema declares types and the entry points. In the SDL (schema definition language) it looks like this:

GRAPHQL
type Author {
  id: Int!
  name: String!
  books: [Book!]!
}

type Book {
  id: Int!
  title: String!
  year: Int
  author: Author!
}

type Query {
  authors: [Author!]!
  books: [Book!]!
  author(id: Int!): Author
}

type Mutation {
  addBook(title: String!, authorId: Int!, year: Int): Book!
}

! means non-null, [Book!]! is a non-null list of non-null books, and author(id: Int!) is a field that takes an argument. Query is where reads start; Mutation is where writes start. A client then asks:

GRAPHQL
{
  authors {
    name
    books { title year }
  }
}

Only the fields named come back. Asking for a field that is not in the schema is an error, which is why GraphQL tooling can autocomplete and validate queries before they run.

With the real library the same schema is a few lines (read-only: needs npm install graphql):

JavaScript
// read-only: requires the "graphql" package
import { buildSchema, graphql } from 'graphql';

const schema = buildSchema(`
  type Query { greeting(name: String!): String! }
`);
const rootValue = { greeting: ({ name }) => `Hello, ${name}!` };

const result = await graphql({ schema, source: '{ greeting(name: "Ada") }', rootValue });
console.log(result.data);   // { greeting: 'Hello, Ada!' }

For HTTP you would hand the schema to createYoga({ schema }) or graphql-http's createHandler, and plug the result into node:http or Express (Express and Minimal Frameworks).

How a query is executed

The server does three things for every request: parse the query text into a tree, validate it against the schema, and execute it. Execution walks the tree from the root. For each field it calls a resolver, and for each object it finds, it resolves the selected sub-fields.

flowchart TD
    Q["Query text"] --> P["Parse to a tree"]
    P --> V["Validate against the schema"]
    V --> E["Execute root fields"]
    E --> R1["Resolver: Query.authors"]
    R1 --> L["List of author objects"]
    L --> R2["Resolver: Author.books<br/>(once per author)"]
    R2 --> J["Assemble JSON<br/>same shape as the query"]

Execution calls a resolver per field. Fields of list items are resolved once per item, which is where N+1 queries come from.

A resolver is a function (parent, args, context) => value (the real signature has a fourth info argument). parent is the object the field belongs to, args holds the field's arguments, and context is a per-request object where you put the logged-in user, database access and loaders. If you do not write a resolver for a field, a default one simply reads parent[fieldName].

The N+1 problem, again

Resolvers are small and independent, which is lovely for code organization and dangerous for performance. Ask for 100 books and their authors: Query.books runs one query, then Book.author runs once per book, so 101 queries. If the author then lists books too, it fans out further. This is the same N+1 trap you met in ORMs: Prisma and Sequelize, and GraphQL makes it easy to fall into, because the client controls the shape of the query.

The standard cure is the DataLoader pattern. Instead of fetching immediately, Book.author calls authors.load(id). The loader collects every load call made during the same tick of the event loop, then runs one batch function with all the ids, and hands each caller its own result. It also remembers results for the rest of the request, so asking for the same author twice costs nothing.

sequenceDiagram
    participant R as Resolvers (5 books)
    participant L as Loader
    participant D as Database
    R->>L: load(1)
    R->>L: load(2)
    R->>L: load(1)
    R->>L: load(3)
    R->>L: load(2)
    Note over L: end of the tick: dedupe keys
    L->>D: one query for ids 1, 2, 3
    D-->>L: three rows
    L-->>R: each caller gets its own value

Five load calls become one database query. The loader waits until the current round of resolvers has run.

The core of a loader is small enough to read in one sitting. Here it is, used on its own. The trick is setImmediate: it runs after all promise callbacks from the current round have finished, so every resolver that was going to call load has done so by then.

Node.js A DataLoader in 25 lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two rules make loaders correct. The batch function must return an array of the same length and order as the keys (use null for a missing row). And create the loaders per request: a loader that lives across requests would cache one user's data and show it to another, which is both a stale-data bug and a security hole.

A mini GraphQL server

The next example is the centerpiece. In about 150 lines it contains everything described above: a tokenizer and parser for the query language (fields, nested selections, arguments, aliases, query and mutation), a schema description, an executor that calls resolvers, partial errors, a per-request context with loaders, and an HTTP endpoint at /graphql.

It is deliberately smaller than the real thing: no variables, fragments, directives, interfaces or non-null enforcement, and it runs the fields of a mutation in parallel instead of in order. Read it top to bottom; the comments mark the stages.

Node.js A GraphQL-style server from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at result 4. The client asked for a field that does not exist (age) and one that throws (secret). A real server would catch the unknown field earlier, in its validation step, and refuse to run the query at all; our mini server has no separate validation, so it shows the more interesting runtime case. Instead of failing the whole request, the server returned null for those two places, listed the problems in errors with their path, and still answered everything else. This is how GraphQL behaves with real libraries as well: partial data plus an errors array, with HTTP status 200. Clients must check errors, not just the status code. (Real GraphQL also lets the schema declare fields non-null, in which case a failure bubbles up to the nearest nullable parent.)

Look at result 6. The second query reaches the author of every book of every author, so without loaders it needs 1 + 3 + 5 = 9 queries, while with loaders the same answer needs 3: one for the authors, one batch for all their books, one batch for the authors of those books.

Writing resolvers well

  • Keep resolvers thin. They should translate GraphQL into calls to your own service layer. Business rules live in services that REST endpoints and background jobs can also use.
  • Authorize in the layer below. Put the current user into context and check permissions in the service functions, not only at the top-level fields. Because clients can reach one object by many paths (book { author { books { ... } } }), a check done in one resolver is easy to bypass through another.
  • Return plain objects. Resolvers may return promises, and a field can be computed (fullName) without any storage behind it.
  • Use input validation. Arguments are typed, but values still need business validation (see Validating Input).
  • Use mutations for writes and make them return the changed object, so the client can refresh its screen from the reply.

Protecting a GraphQL endpoint

Because the client writes the query, a malicious or careless client can ask for something enormous: deeply nested relations, thousands of aliases of an expensive field, or a huge page of results. Standard defenses:

  • Limit depth and cost. Reject queries nested deeper than a fixed level, or that exceed a computed "cost" budget.
  • Limit page sizes. A first: 100000 argument must be capped on the server.
  • Limit request size and rate (see Request Bodies, JSON and Forms and Concurrency Control and Queues).
  • Use persisted queries in production: clients send a hash of a pre-approved query instead of arbitrary text.
  • Hide internals. Mask unexpected error messages (a database error should not reach the client), and consider turning introspection off for public APIs that you do not want others to explore.
  • Cache wisely. All queries are POSTs to one URL, so HTTP caches do not help by default. Cache at the data layer, or use persisted queries sent as GET.

A depth limit is easy to understand. Real libraries walk the parsed tree; this simplified version counts brace nesting, which is enough to see the idea.

Node.js Rejecting over-deep queries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice why a depth limit is needed at all: the schema contains a cycle (Author.books and Book.author point at each other), so it allows queries of unlimited depth. Each level may multiply the work.

GraphQL or REST?

GraphQL shines when many different clients (web, mobile, partners) need different slices of the same data, when screens combine several resources, and when a typed contract is valuable. REST stays simpler for small APIs, file transfer, and anything that benefits from plain HTTP caching and tooling. They can coexist, and many teams put GraphQL in front of existing REST services. Whichever you choose, the habits from this course apply: validate input, limit work, handle errors in one place, and test with real requests (see Testing HTTP Servers).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a resolver?

    The executor calls a resolver for each selected field. A default resolver just reads the property with the same name from the parent.
  2. 2. A query asks for a field that does not exist, plus other valid fields. What does a typical GraphQL server return?

    GraphQL reports partial results. Clients must inspect the errors array because the HTTP status is usually 200.
  3. 3. How does a DataLoader remove the N+1 problem?

    Resolvers keep calling load() one key at a time, but the loader sends them to the database together.
  4. 4. Why must DataLoader instances be created per request rather than once at startup?

    The loader's cache is only valid for one request, and often for one user's permissions.
  5. 5. Which is a good defense against abusive queries?

    The client controls the shape of the query, so the server must cap how expensive a query can be.

Summary

  • GraphQL exposes a typed schema; clients send a query naming the fields they need and get a JSON reply of the same shape, usually through one POST /graphql endpoint.
  • Execution parses and validates the query, then calls a resolver (parent, args, context) per field. Errors are reported next to partial data.
  • Naive resolvers cause N+1 queries. A per-request DataLoader batches and caches lookups, turning dozens of queries into a handful.
  • Put the user and loaders in the per-request context, keep resolvers thin, and enforce authorization in the service layer.
  • Limit depth, cost, page size and request size, and hide internal error details.

Next: The Built-in Test Runner