Bird
Raised Fist0
GraphQLquery~5 mins

Transaction handling in GraphQL

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using transactions in a database when working with GraphQL?
easy
A. To group multiple actions so they all succeed or fail together
B. To speed up query execution by caching results
C. To automatically generate GraphQL schemas
D. To encrypt data sent over the network

Solution

  1. Step 1: Understand what transactions do

    Transactions ensure that a set of database operations are treated as a single unit.
  2. Step 2: Identify the purpose in GraphQL context

    This means either all changes succeed or none do, keeping data consistent.
  3. Final Answer:

    To group multiple actions so they all succeed or fail together -> Option A
  4. Quick Check:

    Transactions = atomic group actions [OK]
Hint: Transactions keep multiple changes safe together [OK]
Common Mistakes:
  • Thinking transactions speed up queries
  • Confusing transactions with schema generation
  • Assuming transactions encrypt data
2. Which of the following is the correct way to start a transaction in a GraphQL resolver using a typical backend?
easy
A. const transaction = await db.rollback();
B. const transaction = db.commit();
C. const transaction = await db.startTransaction();
D. const transaction = db.query('BEGIN');

Solution

  1. Step 1: Identify how to start a transaction

    Starting a transaction usually involves calling a method like startTransaction() asynchronously.
  2. Step 2: Check options for correctness

    const transaction = await db.startTransaction(); correctly uses await and startTransaction(), while others are commit, rollback, or raw query.
  3. Final Answer:

    const transaction = await db.startTransaction(); -> Option C
  4. Quick Check:

    Start transaction = startTransaction() [OK]
Hint: Start transactions with async startTransaction() method [OK]
Common Mistakes:
  • Using commit or rollback to start a transaction
  • Using raw query strings instead of methods
  • Missing await for async calls
3. Given this GraphQL resolver snippet, what will be the output if an error occurs during updateUser()?
async function updateProfile(parent, args, context) {
  const trx = await context.db.startTransaction();
  try {
    await trx.updateUser(args.userId, args.data);
    await trx.commit();
    return 'Success';
  } catch (e) {
    await trx.rollback();
    return 'Failed';
  }
}
medium
A. 'Success'
B. 'Failed'
C. Throws an unhandled exception
D. Returns null

Solution

  1. Step 1: Analyze the try block

    The code tries to update the user and commit the transaction.
  2. Step 2: Understand error handling

    If updateUser throws an error, the catch block rolls back and returns 'Failed'.
  3. Final Answer:

    'Failed' -> Option B
  4. Quick Check:

    Error during update = rollback + 'Failed' [OK]
Hint: Errors trigger rollback and return 'Failed' [OK]
Common Mistakes:
  • Assuming commit runs even on error
  • Expecting unhandled exceptions instead of catch
  • Thinking it returns 'Success' always
4. Identify the error in this GraphQL resolver transaction handling code:
async function saveOrder(parent, args, context) {
  const trx = context.db.startTransaction();
  try {
    await trx.insertOrder(args.order);
    await trx.commit();
    return 'Order saved';
  } catch (error) {
    await trx.rollback();
    return 'Error saving order';
  }
}
medium
A. Missing await before startTransaction()
B. No rollback in catch block
C. commit() should be called before insertOrder()
D. Returning string instead of object

Solution

  1. Step 1: Check transaction start syntax

    startTransaction() is asynchronous and must be awaited.
  2. Step 2: Identify missing await impact

    Without await, trx is a Promise, causing errors on trx.insertOrder().
  3. Final Answer:

    Missing await before startTransaction() -> Option A
  4. Quick Check:

    Async startTransaction() needs await [OK]
Hint: Always await async transaction start calls [OK]
Common Mistakes:
  • Forgetting await on async calls
  • Calling commit before operations
  • Ignoring rollback on errors
5. You want to update a user's profile and their related settings in one transaction using GraphQL. Which approach ensures both updates succeed or fail together?
async function updateUserAndSettings(parent, args, context) {
  const trx = await context.db.startTransaction();
  try {
    await trx.updateUser(args.userId, args.userData);
    await trx.updateSettings(args.userId, args.settingsData);
    await trx.commit();
    return 'Update successful';
  } catch (error) {
    await trx.rollback();
    return 'Update failed';
  }
}
hard
A. Use separate transactions for user and settings updates
B. Do not use transactions for related updates
C. Commit after each update separately
D. Wrap both updates in a single transaction as shown

Solution

  1. Step 1: Understand transaction grouping

    Both updates must be inside one transaction to succeed or fail together.
  2. Step 2: Analyze the code approach

    The code wraps both updates in one transaction, committing only if both succeed.
  3. Final Answer:

    Wrap both updates in a single transaction as shown -> Option D
  4. Quick Check:

    Single transaction = atomic multi-update [OK]
Hint: Group related updates in one transaction [OK]
Common Mistakes:
  • Using separate transactions causing partial updates
  • Committing too early after first update
  • Skipping transactions for multi-step changes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard