AlgoViz

GraphQL

medium 27 min

GraphQL is a query language for APIs with a typed schema.

Video lesson · Chapter 1 of 5

Ask for one profile, follow three sources

0:00 / 3:58

Theory

Read or listen first. About 2 min.

What it is

GraphQL is a language for asking an API for data, and the rules a server follows to answer. The server publishes a schema: types, their fields, and how types are connected. A client sends a query that names the fields it wants. The answer has the same shape as the query.

For each field the server has a small function called a resolver, which gets the value from a database, another service or a calculation. GraphQL does not store anything and does not care where the data lives.

Why it exists

A phone screen often needs a little from many places: a name, five titles, a few counts. With fixed endpoints it receives too much from each and must call several. GraphQL sends one request that names exactly those fields, and each screen can ask for something else without a new endpoint.

The price is that clients now decide what work the server does. Servers must batch lookups, limit deep or wide queries, check permissions in every place a value can be reached, and cache by object and not only by URL.

A short history

  1. 2012

    Engineers at Facebook start GraphQL while they rebuild the native mobile apps, and use it for the News Feed on iOS.

  2. September 2015

    Facebook's engineering blog presents GraphQL in public, with a draft specification.

  3. September 2016

    GitHub announces a public GraphQL API beside its REST API.

  4. June 2018

    An edition of the specification adds the schema definition language.

  5. September 2025

    The next edition adds OneOf input objects and schema coordinates.

  6. November 2026

    The September 2026 edition is released and becomes the latest.

Words to know

Schema
All types and fields an API offers: the contract.
Operation
A query (read), a mutation (write) or a subscription (events).
Resolver
The function that gives one field its value.
Selection set
The fields in braces that a client asks for.
Fragment
A named set of fields to use again.
N+1
One lookup for a list, then one more for each item in it.
DataLoader
A helper that collects keys for a moment and loads them in one batch.
Trusted document
A query that was approved in advance and is sent by its id.

Understand it

Start here

The salad bar slip

Most counters sell fixed plates. This salad bar gives you a slip with every bowl on it. You tick what you want, hand in one slip, and get one tray with exactly that.

Tick what you want
tomatocorneggbreadsoupjuiceThe slip

The guest chooses, so the kitchen needs batching and a limit.

The idea

One question, same shaped answer

graphql
query GetUser($id: ID!) {  user(id: $id) {    name    followerCount    posts(limit: 2) { title likeCount }  }}
JSON
{  "data": {    "user": {      "name": "Asha",      "followerCount": 120,      "posts": [        { "title": "Seeds", "likeCount": 4 },        { "title": "Soil", "likeCount": 9 }      ]    }  }}
Variables travel beside the query as JSON. Never build the query text from user input.

Why teams choose it

  • No over-fetching

    A widget that needs a name asks for a name, not for fifty fields.

  • No under-fetching

    A user, their posts and the comments come in one request.

  • It documents itself

    Tools read the schema by introspection and give documentation and completion.

  • Live data

    Subscriptions push events, often over WebSockets or server-sent events.

  • Typed

    Each field has a type, so clients can generate code and catch errors at build time.

  • Faster screens

    Frontend teams combine existing fields without a new endpoint.

Contract

The schema

graphql
scalar DateTimeenum Role { USER ADMIN MODERATOR }enum PostOrder { NEWEST LIKES }type User {  id: ID!  email: String!            # only the user and admins, see Authorization  name: String!  avatar: String  role: Role!  createdAt: DateTime!  posts(limit: Int = 10, offset: Int = 0): [Post!]!  followers(first: Int = 20): [User!]!  following(first: Int = 20): [User!]!  followerCount: Int!       # computed}type Post {  id: ID!  title: String!  content: String!  published: Boolean!  createdAt: DateTime!  author: User!  comments(limit: Int = 20): [Comment!]!  likes(first: Int = 20): [User!]!  likeCount: Int!  isLikedByMe: Boolean!}type Comment {  id: ID!  content: String!  createdAt: DateTime!  author: User!  post: Post!}input CreatePostInput { title: String! content: String! published: Boolean = false }input UpdatePostInput { title: String content: String published: Boolean }type Query {  me: User  user(id: ID!): User  users(search: String, limit: Int = 20): [User!]!  post(id: ID!): Post  posts(orderBy: PostOrder = NEWEST, limit: Int = 20): [Post!]!  feed(limit: Int = 20, cursor: ID): PostConnection!}type NotifyResult { notifiedCount: Int! }type Mutation {  updateProfile(name: String, avatar: String): User!  createPost(input: CreatePostInput!): Post!  updatePost(id: ID!, input: UpdatePostInput!): Post!  deletePost(id: ID!): Boolean!  notifyFollowers(postId: ID!): NotifyResult!  likePost(postId: ID!): Post!  unlikePost(postId: ID!): Post!  followUser(userId: ID!): User!  unfollowUser(userId: ID!): User!  addComment(postId: ID!, content: String!): Comment!  deleteComment(id: ID!): Boolean!}type Subscription {  newPost: Post!  commentAdded(postId: ID!): Comment!  postLiked(postId: ID!): User!  newFollower: User!}# Pages in the style of the Relay connection specificationtype PostConnection { edges: [PostEdge!]! pageInfo: PageInfo! }type PostEdge { node: Post! cursor: String! }type PageInfo {  hasNextPage: Boolean!  hasPreviousPage: Boolean!  startCursor: String  endCursor: String}

Kinds of type

KindWhat it isExample
ScalarA single valueString, Int, Float, Boolean, ID
ObjectFieldstype User { id: ID! }
EnumOne of a setenum Status { PENDING DONE }
InputAn argument with fieldsinput CreateUserInput { name: String! }
InterfaceFields shared by typesinterface Node { id: ID! }
UnionOne of several typesunion Result = User | Post
String!Never nullrequired
[User]A listmay be null, may hold nulls
[User!]!A list, never null, no null itemsmay be empty
Int is a signed 32 bit number. Use a custom scalar or a string for larger ones.

Schema first means writing the schema and then the code, which helps teams agree. Code first makes the schema from code, so the two cannot drift. Either works. Review the schema like an API.

Language

Three operations, fragments and directives

OperationForExample
QueryReading. Top-level fields may run in parallelquery { user(id: "1") { name } }
MutationWriting. Top-level fields run one after anothermutation { deletePost(id: "9") }
SubscriptionA stream of eventssubscription { newPost { title } }
In order does not mean in one transaction: the first mutation field stays done if the second fails.
graphql
fragment UserFields on User { id name avatar followerCount }query GetFeed($limit: Int!, $cursor: ID) {  feed(limit: $limit, cursor: $cursor) {    edges {      node { id title createdAt likeCount author { ...UserFields } }      cursor    }    pageInfo { hasNextPage endCursor }  }}query GetDashboard {            # several roots, and an alias  me { id name followerCount }  feed(limit: 10) { edges { node { id title } } }  trending: posts(orderBy: LIKES, limit: 5) { id title likeCount }}query GetPostDetails($postId: ID!) {  post(id: $postId) {    id title content createdAt likeCount    author { id name avatar }    comments(limit: 20) { id content createdAt author { id name avatar } }  }}mutation Publish($id: ID!, $tell: Boolean!) {  published: updatePost(id: $id, input: { published: true }) { id published }  notify: notifyFollowers(postId: $id) @include(if: $tell) { notifiedCount }}mutation CreatePost($input: CreatePostInput!) {  createPost(input: $input) { id title published author { id name } }}subscription OnCommentAdded($postId: ID!) {  commentAdded(postId: $postId) { id content createdAt author { id name } }}
A mutation returns the changed object, so the client needs no second read. Name operations so that logs can group them.

Built-in directives

DirectiveDoesExample
@includeKeep the field if truename @include(if: $showName)
@skipLeave it out if trueemail @skip(if: $hide)
@deprecatedMark a field as on its way outold: Int @deprecated(reason: "Use new")
@specifiedByLink a scalar to its definitionscalar UUID @specifiedBy(url: "...")
@oneOfExactly one input field must be setinput UserBy @oneOf { id: ID email: String }
Servers may add their own, for example for authorization, cost or caching.

Execution

From text to answer

Inside a GraphQL server

A client outside our system sends a query to a gateway inside, which checks the token and limits. The GraphQL server machine holds the steps parse and validate, then resolvers, then loaders. Loaders ask PostgreSQL in batches, and resolvers call other services.
GraphQL is a layer in front of your data, not a database.
  1. 1

    The client sends one request

    Usually POST to /graphql with the query, variables and an operation name. GET is allowed for queries, never for mutations.

  2. 2

    The gateway checks the caller

    Token or session, a rate limit, and a log line.

  3. 3

    Parse and validate

    Is it valid GraphQL? Do the fields exist? Do types fit? Cost rules run here too, before any work.

  4. 4

    Run the resolvers

    From the root down. A child gets its parent's result. Fields that only read a property need no code.

  5. 5

    Loaders batch

    Keys asked for in the same moment become one database query.

  6. 6

    Assemble

    Values are put in the shape of the query. A field that fails becomes null, with an entry in errors.

One query through the server

The classic trap

N+1 and the DataLoader

A list of users, and the posts of each. The resolver for posts runs once per user, and each run asks the database. Twenty users make 21 queries. A hundred make 101.

Queries sent

1+N=1+20=21batched: 1+1=21 + N = 1 + 20 = 21 \qquad \text{batched: } 1 + 1 = 2
With another list level the plain count grows as 1 + N + N times M. Batched it is one for each level.
TypeScript
import DataLoader from "dataloader";// Called once for EACH request: never share loaders between users.export function createLoaders(db: Db) {  return {    user: new DataLoader<string, User | Error>(async (ids) => {      const rows = await db.usersByIds([...ids]);       // WHERE id IN (...)      const byId = new Map(rows.map((u) => [u.id, u]));      // Same length and same order as the keys.      return ids.map((id) => byId.get(id) ?? new Error("No user " + id));    }),    // One to many, with the limit inside the database.    postsByUser: new DataLoader<{ id: string; limit: number }, Post[], string>(      async (keys) => {        const limit = Math.max(...keys.map((k) => k.limit));        const rows = await db.topPostsPerAuthor(keys.map((k) => k.id), limit);        return keys.map((k) => rows.filter((p) => p.authorId === k.id).slice(0, k.limit));      },      { cacheKeyFn: (k) => k.id + ":" + k.limit },    ),    likedByMe: new DataLoader<string, boolean>(async (keys) => {      const liked = new Set(await db.likesAmong([...keys]));  // "userId:postId"      return keys.map((k) => liked.has(k));    }),    likeCount: new DataLoader<string, number>(async (ids) => {      const counts = await db.likeCounts([...ids]);           // GROUP BY post      return ids.map((id) => counts.get(id) ?? 0);    }),  };}export const resolvers = {  Query: {    users: (_: unknown, a: { limit: number }, { db }: Ctx) => db.users(Math.min(a.limit, 100)),  },  User: {    posts: (u: User, a: { limit: number }, { loaders }: Ctx) =>      loaders.postsByUser.load({ id: u.id, limit: Math.min(a.limit, 50) }),  },  Post: {    author: (p: Post, _: unknown, { loaders }: Ctx) => loaders.user.load(p.authorId),    likeCount: (p: Post, _: unknown, { loaders }: Ctx) => loaders.likeCount.load(p.id),    isLikedByMe: (p: Post, _: unknown, { loaders, user }: Ctx) =>      user ? loaders.likedByMe.load(user.id + ":" + p.id) : false,  },};
A window function can fetch the newest few posts for each author, so the database does not send posts that nobody asked for. Counts need batching as well.

How a loader waits

It also remembers a key for the rest of the request, so a user who wrote ten posts is loaded once.

Protection

Limit what a query may cost

A short query can ask for a great deal: friends of friends of friends, or one field under fifty aliases. Counting requests is not enough. Refuse by shape before running anything.

Count the nodes

50+50×10=55050 + 50 \times 10 = 550
50 repositories with 10 issues each. This is how GitHub counts nodes: no call may ask for more than 500,000, and each list must say first or last between 1 and 100.
GuardStopsNote
Page size maximumHuge listsMake first required
Depth limitCircles such as friend, friend, friendSet it from real queries
Breadth, alias and batch limitsOne field fifty times, many operations in a requestCounts root fields too
Cost pointsExpensive mixesRate limit by points, not by requests
Trusted documentsEverything unknownFor your own apps. Public APIs cannot use it
TimeoutsWhat slipped throughPass them to the loaders
GitHub allows a user 5,000 points an hour. Shopify's Admin API also limits by calculated query cost.

May it run?

Turning off introspection in production hides the menu. It is no access control, so never rely on it alone. See rate limiting.

Access

Authorization and errors

The same user can be reached through me, through a comment's author, or through a follower list. So check where the object is loaded, in the business layer, and not at the entry point. Check sensitive fields, such as an email, on the field.

TypeScript
import { GraphQLError } from "graphql";import { z } from "zod";const fail = (message: string, code: string, extra: object = {}) =>  new GraphQLError(message, { extensions: { code, ...extra } });const NewPost = z.object({  title: z.string().min(1).max(200),  content: z.string().min(1).max(10_000),  published: z.boolean().default(false),});export const mutations = {  createPost: (_: unknown, { input }: { input: unknown }, { user, db }: Ctx) => {    if (!user) throw fail("Sign in first", "UNAUTHENTICATED");    const parsed = NewPost.safeParse(input);    if (!parsed.success)      throw fail("Check the fields", "BAD_USER_INPUT", { fields: z.flattenError(parsed.error).fieldErrors });    return db.createPost({ ...parsed.data, authorId: user.id });  },  deletePost: async (_: unknown, { id }: { id: string }, { user, db }: Ctx) => {    if (!user) throw fail("Sign in first", "UNAUTHENTICATED");    const post = await db.post(id);    if (!post) throw fail("No such post", "NOT_FOUND");    if (post.authorId !== user.id) throw fail("Not your post", "FORBIDDEN");    await db.deletePost(id);    return true;  },};
JSON
{  "data": { "me": { "name": "Asha", "points": null } },  "errors": [{    "message": "Points are not available now",    "path": ["me", "points"],    "extensions": { "code": "UPSTREAM_DOWN" }  }]}
A partial answer. The status is 2xx when data is not null, so monitoring must read errors. Other error codes: RATE_LIMITED is a name of your own, not part of the language.

For expected outcomes, such as a name already taken, many schemas return a union of success and problem types, so that clients must handle both. Keep errors for what should not happen.

Caching

Three places to cache

Most requests are POSTs to one URL, so shared HTTP caches cannot help by themselves. That does not mean HTTP caching is impossible.

WhereKeyHow
ClientType and id, such as Post:9Apollo Client and Relay store objects once and update every view
CDNHash of the query and the variablesSend the hash with GET, and set Cache-Control
ServerObject or fieldLoaders for a request, Redis for longer
Automatic persisted queries send a SHA-256 hash first, and the full text only if the server does not know it. They save bytes. They are not a list of allowed queries.

An automatic persisted query

Public answers and answers for one user must not be mixed in a shared cache. The rules are in API caching.

Transport

HTTP, live events and files

The GraphQL over HTTP specification is still a draft. It asks servers to support the media type application/graphql-response+json, and forbids mutations over GET. Subscriptions have no fixed transport: graphql-ws uses a WebSocket and graphql-sse uses server-sent events. Each subscriber keeps a connection open, so plan limits, cleanup, and a pub/sub system that reaches every server. See real-time APIs.

Subscriptions, done well

  • Check access at subscribe and at each event
  • Filter on the server: only this post's comments
  • Share events between servers with Redis or a queue
  • Reload the state after a reconnect

Trouble

  • In-memory PubSub with two servers
  • A subscription where a poll each minute would do
  • Filtering in the client
  • No limit on connections for each user

Files. A signed upload URL from a mutation, then a direct upload, is the simple way: see file upload APIs. A community multipart request specification exists. It opens the door to cross-site requests unless the server demands a header that forces a preflight.

Growing

Evolve the schema, split the graph

Add fields freely: nobody receives what they did not ask for. To remove one, mark it @deprecated, measure who still selects it, then drop it. Changing a type, or making a nullable input required, still breaks clients. So "no versions" is a habit, not magic.

One graph, three teams

A client outside sends a query to a router inside our system. The router calls three subgraphs, users, posts and reviews, each a machine owned by a team with its own database.
With federation each team owns part of the schema, and a router plans which subgraphs to ask.

Lists deserve cursors from the first day: the connection shape above is the Relay convention. Compare the choices in API pagination.

Operate

Run it in production

WatchBecause
Time and errors by operation nameAll traffic has one URL
Resolver time and database queries per requestN+1 comes back quietly
Cost points by clientFind the expensive ones
Use of each fieldYou can remove what nobody selects
errors in 200 answersHTTP status hides them
Open subscriptionsMemory and file handles
Apollo Server 4 reached its end of life in January 2026. Version 5 needs Node.js 20 or later, and its Express middleware lives in separate packages.

Good

  • No over-fetching: only the chosen fields.
  • Single request: related data together.
  • Self-documenting: the schema is the reference.
  • Type safety: generated client types.

Costs

  • Caching: needs design.
  • N+1: every list is a risk.
  • Limits: by cost, not by request.
  • Learning: schema design takes practice.

Decide

When to use it

Choose GraphQL for

  • Mobile apps that must save bytes and trips
  • Many screens with different needs
  • Frontend teams that move faster than the backend
  • One entrance to several services
  • A dashboard, a phone and a widget on the same data
  • Live updates beside queries

Choose another for

  • Simple CRUD: REST
  • Mostly files and binary data
  • Public reads that live from CDN caching
  • Teams that cannot invest in limits and batching
  • Third parties who expect plain HTTP
  • Service to service calls: gRPC

Beside its neighbours

GraphQLRESTgRPCtRPC
Who shapes the answerThe clientThe serverThe contractThe server's function
AddressOne endpointMany URLsService methodsProcedures
ContractSchemaOften OpenAPI.protoTypeScript types
LanguagesAnyAnyManyTypeScript
Code generationCommon, not requiredOptionalYesNone
Live dataSubscriptionsNot part of itStreamsSubscriptions
ChangeAdd and deprecateOften versionsNew field numbersBoth sides together
Good forVaried clientsPublic APIs, cachingInternal callsOne TypeScript codebase
GraphQL types and gRPC messages are both strict. GraphQL text and JSON are read more easily, Protocol Buffers are smaller.

All three styles in depth: REST, GraphQL and gRPC.

Summary

The whole topic in one minute.

GraphQL gives clients one typed schema and lets them pick fields across related objects in one request. Three operations exist: query, mutation and subscription. The answer has the shape of the question, and errors can be partial.

What you save in round trips and endpoints you spend on the server: batch with a DataLoader for each request, limit depth, width and cost, allow only known queries for your own apps, authorize where data is loaded, and cache by object id or by the hash of the query. Change the schema by adding and deprecating.

  • The client selects fields; the answer has the same shape.
  • Every list needs a loader for each request and a maximum.
  • Limit by cost, and use trusted documents for your own apps.
  • Authorize where the object is loaded.
  • Cache by object id, or by query hash over GET.
  • Add, deprecate, measure, remove.

Sources