0
0
GraphQLquery~5 mins

Transaction handling in GraphQL

Choose your learning style9 modes available
Introduction

Transactions help keep your data safe and correct by making sure a group of actions all finish together or none at all.

When you want to save a new order and update the stock at the same time.
When transferring money between two bank accounts to avoid losing or duplicating money.
When multiple users are editing the same data and you want to avoid conflicts.
When you need to undo changes if something goes wrong during a process.
Syntax
GraphQL
mutation {
  startTransaction {
    id
  }

  performOperations {
    updateData(input: {...}) {
      success
    }
  }

  commitTransaction(id: "transaction_id") {
    success
  }

  rollbackTransaction(id: "transaction_id") {
    success
  }
}

GraphQL itself does not define transactions, but your backend can expose mutations to start, commit, or rollback transactions.

You usually call startTransaction first, then perform your data changes, and finally commit or rollback.

Examples
Starts a new transaction and returns its ID.
GraphQL
mutation {
  startTransaction {
    id
  }
}
Updates user data inside a transaction.
GraphQL
mutation {
  updateUser(id: "123", input: {name: "Alice"}) {
    success
  }
}
Commits the transaction to save all changes.
GraphQL
mutation {
  commitTransaction(id: "tx123") {
    success
  }
}
Rolls back the transaction to undo changes.
GraphQL
mutation {
  rollbackTransaction(id: "tx123") {
    success
  }
}
Sample Program

This example starts a transaction, updates a user inside it, then commits the transaction to save changes.

GraphQL
mutation {
  startTransaction {
    id
  }
}

# Suppose the returned id is "tx1"

mutation {
  updateUser(id: "123", input: {name: "Alice"}, transactionId: "tx1") {
    success
  }
}

mutation {
  commitTransaction(id: "tx1") {
    success
  }
}
OutputSuccess
Important Notes

Not all GraphQL servers support transactions natively; check your backend's documentation.

Always commit or rollback to avoid leaving transactions open.

Use transaction IDs to link your operations together.

Summary

Transactions group multiple actions to keep data safe and consistent.

Start a transaction, do your changes, then commit or rollback.

GraphQL needs backend support to handle transactions.