Batching mutations

API mutations are designed to be very small and atomic on purpose - thanks to that design, you don't have to prefetch data to send it back to the server and worry only about the actual change you want to perform.

On the other hand, occasionally your intention is to create or change resources with data that a single mutation does not handle. GraphQL comes in handy here - thanks to its design you can batch mutations(and queries) which means that multiple operations can be performed in one, single request - this not only makes it easier to make updates but also speeds up operations.

mutation {
  create: productCreateSimple(input: {sku: "new_product", templateCode: "template"}) {
    __typename
  }
  assignDescription: productAddAttributeValueTranslationsTextarea(
    input: {
      sku: "new_product"
      attributeCode: "description"
      translations: [{ value: "Long description", language: "en_GB" }]
    }
  ) {
    __typename
  }
  assignShortDescription: productAddAttributeValueTranslationsTextarea(
    input: {
      sku: "new_product"
      attributeCode: "short_description"
      translations: [{ value: "Short description", language: "en_GB" }]
    }
  ) {
    __typename
  }
}

Batch mutations are executed synchronously which also means their order does matter. You need to create the product first in order to assign values to it.

All mutations in the batch are performed one after another and if one or more fails all the others will still be tried to execute. The batch result will contain requested data from each mutation as well as specific errors which occurred for those which failed.

Note that each mutation has an alias (create: (...)) - which means a custom name is assigned to it. Aliasing is required if there are at least two same mutations in one batch - productAddAttributeValueTranslationsTextarea in this case - this behavior allows differentiation of the data in the result which in another case would not be possible.

In the above example for simplicity, all mutations have been aliased in the example but it'd also suffice to only alias duplicates.

As tempting as it may sound to make one update of all data in the system bear in mind the fact of synchronicity of the batch process - it means that the process will last as long as there are some mutations left to be executed.

In practice, it means that too-long running processes are usually more faulty and also it's harder to handle potential errors. In most extreme cases, you can even reach timeout from your HTTP client or the server can drop the handling of the request as it takes too long to process.

A usually recommended approach would be to limit the batch to a single resource(product, attribute, multimedia) or with a similar intention in mind.

Last updated