Back to results for “SQL/Sequelize)”
Node.js › Databases

What is a database transaction, and how would you implement one in Node.js to ensure multiple related writes either all succeed or all fail together?

Advanced

Answer

A transaction groups multiple database operations so they're treated as a single atomic unit -- either every operation within it commits successfully, or if any fails, the entire transaction is rolled back, leaving the database in its original consistent state, essential whenever multiple related writes (like debiting one account and crediting another) must never be left partially applied.
const client = await pool.connect();
try {
  await client.query('BEGIN');
  await client.query('UPDATE accounts SET balance = balance - 100 WHERE id = $1', [fromId]);
  await client.query('UPDATE accounts SET balance = balance + 100 WHERE id = $1', [toId]);
  await client.query('COMMIT');
} catch (err) {
  await client.query('ROLLBACK');
  throw err;
} finally {
  client.release();
}
Real-world example A money-transfer feature wraps both the debit and credit operations in a single database transaction, guaranteeing that if the credit operation fails for any reason after the debit already succeeded, the entire transfer rolls back rather than leaving money deducted from one account without appearing in the other.

Common follow-ups: What are the ACID properties, and which one specifically does a transaction most directly guarantee?;How do transactions behave differently in a NoSQL database like MongoDB compared to a traditional relational database?