Multiple Fields in a Mutation
A shop admin runs a weekend sale: drop the price of The Quiet Ledger, then post a staff review to promote it. Both changes can go in one mutation request. But when one request does two writes, you need to know which happens first and what happens if the second fails.
The rule
Mutation fields run in order, each finishing before the next begins.
A mutation can list several top-level fields:
mutation WeekendSale {
updatePrice(bookId: "b2", price: 299) {
title
price
}
addReview(input: { bookId: "b2", rating: 5, text: "Staff pick for the sale." }) {
id
book { price }
}
}GraphQL runs the top-level fields of a mutation serially: updatePrice runs completely, including its selected fields, and only then does addReview start. So the review's book { price } is guaranteed to show the new price, 299.
Queries are different. Their top-level fields have no side effects, so a server is free to resolve them in parallel. Only the top level of a mutation is serial; the fields nested inside each result resolve the normal way.
Two more rules follow from what you already know:
- Same field twice needs aliases. Posting two reviews means two
addReviewfields with different arguments, so name them:first: addReview(...)andsecond: addReview(...). - Order is not a transaction. If
addReviewfails, the price change has already happened and stays. The response carries an error for the failed field. If two changes must succeed or fail together, give the schema one field, such asstartSale, whose resolver does both inside a database transaction.