Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 37 ยท Writing Queries

Mutations and Subscriptions

Learn the three GraphQL operation types: queries read, mutations change data one after another, and subscriptions stream events. Includes runnable stand-ins.

So far you have only read data. GraphQL has three operation types: query reads, mutation writes, and subscription listens for events over time. They share the same syntax (selection sets, arguments, variables, fragments), so everything you learned in Fields, Arguments and Nested Selections and Variables and Directives still applies.

The real server code for subscriptions needs a long-lived connection, and no GraphQL server runs on this site. So in this lesson the GraphQL documents and schema snippets are read-only code blocks, and the runnable examples are stand-ins: small JavaScript programs that mimic what a server does with a mutation or a subscription. They are not a real GraphQL engine, but they show the rules that matter.

Three operation types

query Read data. Fields may run in parallel.
mutation Change data. Top-level fields run one by one.
subscription Stream events. One result per event.

Same syntax, different execution rules.

1 / 2

A mutation

A mutation looks like a query with the keyword mutation. Its top-level fields are the actions your API offers.

GRAPHQL
mutation AddTodo($input: AddTodoInput!) {
  addTodo(input: $input) {
    todo {
      id
      title
      done
    }
  }
}

Variables travel next to the document:

JSON
{ "input": { "title": "Buy milk" } }

The server runs addTodo, then resolves the selection set against what the mutation returned. That is the key idea: a mutation is not "fire and forget". You choose which fields of the changed object you want back, so the client can update its screen without a second request.

The schema side, in SDL (you will learn the syntax in SDL: Types and Scalars):

GRAPHQL
type Mutation {
  addTodo(input: AddTodoInput!): AddTodoPayload!
  toggleTodo(id: ID!): ToggleTodoPayload!
}

input AddTodoInput {
  title: String!
}

type AddTodoPayload {
  todo: Todo
}

Input objects and payload types

Two conventions make mutations pleasant to evolve:

  • One input argument. Instead of addTodo(title: String!, dueDate: String, ...), take a single input object. Adding an optional field later is not a breaking change, and clients send one variable.
  • A payload type per mutation. Returning a dedicated AddTodoPayload (rather than the bare Todo) leaves room to add more fields later, such as a list of validation errors or the updated parent object. See Modeling Errors and Schema Design Best Practices.

Nothing in the language forces a mutation to write data, and nothing forces a query to be read-only. It is a convention enforced by you: never change data inside a query field. Caches, retries and prefetching all assume queries are safe.

Mutations run serially

This is the one execution rule that differs. Fields of a query may be resolved in any order, often in parallel. The top-level fields of a mutation are executed one after another, in the order written, and each one finishes before the next starts.

GRAPHQL
mutation {
  first: addTodo(input: { title: "Write" }) { todo { id } }
  second: addTodo(input: { title: "Review" }) { todo { id } }
  third: toggleTodo(id: "1") { todo { done } }
}

Here third can safely rely on the todo made by first. Notice the aliases (first, second): without them, two fields named addTodo would collide in the response (see Aliases and Fragments). Only the top level is serial; the selection inside each payload is resolved as usual.

The stand-in below keeps todos in an array and runs the mutation fields in order. Each step is asynchronous with a different delay, to prove that order is kept even when a later step would be faster.

JS A stand-in serial mutation executor

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

No output.

The slow addTodo calls still finish before toggleTodo begins. If you change the for ... await loop to Promise.all(...), you get the query behaviour: the fast field finishes first and toggleTodo runs before todo 1 exists. That is exactly the bug serial execution prevents. A real server does this inside its execution engine; you never write this loop yourself.

Subscriptions

A subscription asks the server to push a result every time an event happens. The document looks familiar, but a subscription must have exactly one top-level field:

GRAPHQL
subscription OnTodoAdded {
  todoAdded {
    id
    title
  }
}

The client sends it once; the server keeps the connection open and sends a separate response (shaped like a normal data payload) for every event. Under the hood a subscription resolver returns an event stream (an async iterator, in most JavaScript servers), and the selection set is executed once per event. The transport is usually WebSockets or Server-Sent Events, covered in GraphQL over HTTP and Subscriptions, Live Updates and File Uploads.

A server-side declaration, read-only here because it needs a running server and a pub/sub backend:

JavaScript
// shape only: details vary by server library
const resolvers = {
  Subscription: {
    todoAdded: {
      subscribe: () => pubsub.asyncIterator("TODO_ADDED"),
    },
  },
  Mutation: {
    async addTodo(_, { input }) {
      const todo = await db.insertTodo(input);
      pubsub.publish("TODO_ADDED", { todoAdded: todo });
      return { todo };
    },
  },
};

Notice the connection between the two halves: the mutation publishes an event, and every subscribed client receives it. The stand-in below does the same with Node-style event handling in plain JavaScript. Each subscriber has its own selection (a list of fields), so two clients get differently shaped payloads from the same event.

JS A stand-in event stream with two subscribers

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

No output.

Both clients get one message per event, and each message contains only the fields that client asked for. A real server also handles connection setup, authentication, filtering and clean-up when a client disconnects.

Several changes in one request, and errors

A request may contain several mutation fields; they run one after another in the order written, so later ones can rely on earlier ones:

GRAPHQL
mutation Setup {
  a: addTodo(input: { title: "Buy milk" }) { id }
  b: addTodo(input: { title: "Call Sam" }) { id }
}

Aliases (a, b) keep both results apart. This is not a database transaction: if b fails, a has already been applied and the response holds partial data plus an errors entry. When several changes must succeed or fail together, expose one bulk mutation (for example addTodos(input: [TodoInput!]!)) and wrap the work in a transaction on the server.

Plan for failure in the schema, too. Expected problems (validation, duplicates, no permission) fit best in the payload as typed errors, as shown in Errors in the Schema, while unexpected ones (database down) belong in the top-level errors list. Make mutations idempotent where you can, or accept a client-generated key, so a retry after a timeout does not create a duplicate.

When to use which

  • Use a query for anything that reads.
  • Use a mutation for every write, and name it after the business action (publishPost, not updatePost with a published flag).
  • Use a subscription only when the client truly needs to be told about changes as they happen (chat, live scores, notifications). Polling a query every few seconds is simpler and often good enough.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How are the top-level fields of a mutation executed?

    The specification requires mutation root fields to run serially, in document order, so later fields can depend on earlier writes. Query fields may run in parallel.
  2. 2. Why do many APIs take a single input object argument in a mutation?

    A single input object can grow with new optional fields without changing the argument list. Clients also pass one variable.
  3. 3. What does a subscription return to the client?

    The selection set is executed for each event the server's stream produces, and each result is pushed to the client.
  4. 4. Why return the changed object from a mutation?

    The client picks the fields it needs from the payload, which usually saves an extra round trip.

Summary

  • GraphQL has three operation types: query, mutation and subscription.
  • Mutation root fields run serially in document order; query fields may run in parallel.
  • Use one input argument and a dedicated payload type per mutation, and return what the client needs to refresh its view.
  • Use aliases when calling the same mutation field twice in one document.
  • A subscription is an event stream: the selection set runs once per event, over a long-lived connection.
  • The runnable examples here are stand-ins; real servers and transports are covered in later lessons.

Next: SDL: Types and Scalars.