Back to results for “Error Handling”
Node.js › Databases & ORMs (MongoDB/Mongoose, SQL/Sequelize)

How do you implement database transactions in Node.js using Sequelize to ensure multiple related writes succeed or fail together?

Intermediate

Answer

Sequelize's transaction() method wraps multiple operations so that either all of them commit together or, if any operation throws, all of them are automatically rolled back -- essential for maintaining data consistency in multi-step operations like transferring funds between two accounts, where partially applying only one side of the transfer would leave the data in an invalid, inconsistent state.
const transaction = await sequelize.transaction();
try {
  await Account.decrement('balance', { by: 100, where: { id: fromId }, transaction });
  await Account.increment('balance', { by: 100, where: { id: toId }, transaction });
  await transaction.commit();
} catch (err) {
  await transaction.rollback();
  throw err;
}
Real-world example A banking application wraps a funds transfer between two accounts in a Sequelize transaction, guaranteeing that if the increment on the receiving account fails for any reason after the decrement on the sending account already succeeded, the entire operation rolls back automatically rather than leaving money 'lost' from one account without arriving in the other.

Common follow-ups: How does MongoDB's multi-document transaction support (available since v4.0) compare in usage to Sequelize's transactions for a similar all-or-nothing operation?;What's the performance and locking implication of holding a transaction open for a long time?