Mutations

Beginner · 12 min

Write data with the Mutation root type, send variables, return the changed object, and see why mutation fields run serially while queries run in parallel.

Before thisFields and selection setsVariables and operation namesInput types

Net Ninja · 12 min

Mutations

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Net NinjaReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A mutation is an operation that changes data. It starts at the `Mutation` root type the same way a query starts at `Query`, and its fields are verbs such as `createPost`.
  • Mutations return a selection set like any other field, so the client can ask for the changed object in the same round trip instead of refetching.
  • Top-level mutation fields run serially in the order written; top-level query fields may run in parallel. Nested fields under a mutation are not serial.
  • Servers accept mutations only over POST, because a GET request must be safe to repeat and cache.
  • Mutation arguments should come from variables, not string-built documents.

The problem mutations solve

A query reads. Most apps also need to write: publish a post, rename an author, delete a comment. REST gives you the HTTP verbs for that, POST, PATCH and DELETE, and the server routes on them. A GraphQL endpoint has one URL and usually one HTTP method, so the verb has to live somewhere else. It lives in the schema, on a root type called Mutation.

The separation is more than a naming habit. A server, a CDN, a client cache and your own tooling all want to know whether running an operation twice is harmless. Reads are. Writes are not. By putting writes under their own root, the schema labels them.

The shape of a mutation

Here is a small schema, run against Yoga with a SQLite database behind it:

type Query {
  post(id: ID!): Post
}

type Mutation {
  createPost(authorId: ID!, title: String!): Post!
  deletePost(id: ID!): Boolean!
}

And the operation:

mutation CreatePost($authorId: ID!, $title: String!) {
  createPost(authorId: $authorId, title: $title) {
    id
    title
    author { name }
  }
}

The variables travel in a separate JSON object, {"authorId": "2", "title": "Hello"}. Do not build the document by pasting user input into a string. Variables are typed and validated by the server, and a stray quote cannot change the operation.

Notice the selection set. createPost returns a Post!, so you must pick fields from it, and the response carries the new row:

{ "data": { "createPost": { "id": "11", "title": "Hello", "author": { "name": "Grace" } } } }

That is the second job of a mutation: write, then hand back the new state. It saves a follow-up query, and it is how a client library learns that post 11 now exists. The next lesson, designing mutation inputs and payloads, covers what the return type should look like once you have more than one outcome.

Mutations run in order

Queries and mutations execute differently. The spec says top-level query fields may be resolved in parallel, and top-level mutation fields must be resolved one after another. I checked this with graphql-js 17.1.0. Three fields take 150, 50 and 50 milliseconds, each logging when it starts and ends:

query     start a, start b, start c, end b, end c, end a   ~154 ms
mutation  start a, end a, start b, end b, start c, end c   ~254 ms

Think of the mutation as a checkout queue and the query as a buffet. If a client sends mutation { a: debit(...) b: credit(...) }, b never starts until a has finished, so a request can depend on the one before it.

Two limits. The rule covers only the top-level fields; resolvers nested beneath each mutation field run like any others. And it orders fields inside one request, not across requests. Two browsers sending mutations at once still race, which is a database concern: use transactions and constraints.

Where mutations go over HTTP

A GET must be safe to repeat, so servers refuse mutations over it. Yoga answers a GET carrying a mutation with 405 and the message Can only perform a mutation operation from a POST request. Send mutations as a POST with a JSON body. The GraphQL over HTTP lesson has the full request format.

A mutation resolver

A mutation resolver is an ordinary resolver that happens to write:

const resolvers = {
  Mutation: {
    createPost: (_parent, { authorId, title }, { db }) => {
      const r = db
        .prepare('INSERT INTO posts (author_id, title, body, created_at) VALUES (?, ?, ?, ?)')
        .run(authorId, title.trim(), '', Date.now());
      return db.prepare('SELECT * FROM posts WHERE id = ?').get(r.lastInsertRowid);
    },
  },
};

It returns the row, and the Post type’s own resolvers fill in author and the rest. Resolvers get a full lesson in resolvers.

Name mutations as verb plus noun: createPost, publishPost, archiveAuthor. Prefer domain verbs over a generic updatePost that takes any combination of fields, because publishPost says what it does and can enforce its own rules.

What the video covers

Net Ninja’s crash course episode 8 adds and deletes data with Apollo Server. The description gives only links to the course files and Apollo docs, so this lesson rests on the title: adding and deleting data through mutations. It is a 2023 video on Apollo Server, while this lesson’s code uses Yoga, but the schema and the operations are identical across servers. The video does not discuss execution order, which is why that section is here.

Where this fits

You can now write data with a typed operation. A one-field mutation is the simplest case; real ones need structured arguments and a predictable result. Next: designing mutation inputs and payloads.

Check yourself

  1. 01Why does a GraphQL schema need a separate Mutation type when a query field could also change data?

    The spec makes no guarantee that a query field is safe or ordered, and servers, caches and tools treat queries as repeatable reads. The Mutation root tells everyone that these fields have side effects and must run in order.

  2. 02What order do the fields in mutation { a b c } run in?

    a finishes before b starts, and b finishes before c starts. Fields in a query would start together.

  3. 03Why should a mutation return the thing it changed?

    The client gets the new state in the response without a second request, and a normalized client cache can update every screen that shows that object.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark