GraphQL Basics: Schema, Queries and Resolvers
GraphQL lets the client ask for exactly what it needs. Learn the schema, the query, the resolver, and the N+1 problem in practice.
By Velloreth
The schema
type Post {
id: ID!
title: String!
body: String!
author: User!
comments: [Comment!]!
}
type User {
id: ID!
name: String!
posts: [Post!]!
}
type Query {
post(id: ID!): Post
posts(limit: Int = 10): [Post!]!
}
The schema defines the types and the fields.
! means non-null.
[Comment!]! is a non-null list of non-null comments.
The query
query {
post(id: "1") {
title
author {
name
}
comments {
body
}
}
}
The client asks for the fields it needs, and the server returns exactly those.
No over-fetching, and no under-fetching.
The resolver
const resolvers = {
Query: {
post: (_, { id }, ctx) => ctx.db.post.findById(id),
},
Post: {
author: (post, _, ctx) => ctx.db.user.findById(post.authorId),
comments: (post, _, ctx) => ctx.db.comment.findByPostId(post.id),
},
};
A resolver returns the data for one field.
It receives the parent value, the arguments and the context.
It can return a promise, and the runtime awaits it.
The N+1 problem
A query for 10 posts triggers 10 author queries and 10 comment queries.
1 query for the posts
10 queries for the authors
10 queries for the comments
= 21 queries
The fix: a batching loader.
const authorLoader = new DataLoader(async (ids) => {
const users = await db.user.findByIds(ids);
return ids.map((id) => users.find((u) => u.id === id));
});
The loader collects the keys in a tick and issues one query.
The result: 3 queries instead of 21.
The operations
| Operation | Purpose |
|---|---|
| Query | read |
| Mutation | write |
| Subscription | a real-time stream |
A mutation is executed serially, so two mutations do not run in parallel.
A subscription uses a WebSocket and pushes an event.
The variables
query GetPost($id: ID!) {
post(id: $id) {
title
}
}
{ "id": "1" }
A variable is passed separately, which avoids a string interpolation and enables a cache.
The fragments
fragment PostFields on Post {
id
title
}
query {
posts {
...PostFields
}
}
A fragment is a reusable field set.
A fragment on an interface is used with an inline fragment.
The security
Limit the query depth.
depthLimit(10)
Limit the query cost. Assign a cost per field and reject a query over a budget.
Disable introspection in production.
Require authentication, and authorise per field.
Rate limit by the cost, not by the request count.
A deeply nested query can be a denial of service, so the limits are not optional.
GraphQL versus REST
| GraphQL | REST | |
|---|---|---|
| Endpoint | one | many |
| Over-fetching | no | possible |
| Under-fetching | no | possible |
| HTTP caching | hard | easy |
| Schema | required | optional |
| Complexity | higher | lower |
| Best for | a varied client | a fixed resource |
GraphQL is better for a varied client, such as a web and a mobile app with different needs.
REST is simpler for a fixed resource, and it benefits from HTTP caching.
Common mistakes
No depth limit. A denial of service.
No cost limit. A heavy query.
Introspection in production. The schema is exposed.
The N+1 problem. A slow query.
No authorisation per field. A data leak.
A resolver that returns a promise without awaiting. A wrong value.
A mutation that is not idempotent. A retry duplicates.
No error handling. A partial result is not communicated.
A schema that changes without a version. A breaking change.
A cache that ignores the query. A wrong result.
A quotable summary
A GraphQL schema defines the types and the fields, the client asks for exactly the fields it needs, and a resolver fetches the data for one field. The N+1 problem is the main performance trap, and a batching loader such as DataLoader fixes it by collecting the keys and issuing one query. Limit the query depth and cost, disable introspection in production, and authorise per field, because a deeply nested query can be a denial of service.
Related reading
For the related topics, see rest-api-design-principles and api-error-responses-guide. For the broader context, rest-api-rate-limiting and api-authentication-methods.