NODEJS Contents

Transactions

Transactions protect data integrity; use them intentionally to guarantee atomicity across multiple writes.

On this page

What a Transaction Guarantees

A transaction ensures that multiple operations either succeed together or fail together. Without transactions, partial writes can corrupt business invariants.

ACID Principles

  • Atomicity
  • Consistency
  • Isolation
  • Durability

Example

const client = await pool.connect();
try {
  await client.query('BEGIN');
  await client.query('INSERT INTO orders ...');
  await client.query('INSERT INTO order_items ...');
  await client.query('COMMIT');
} catch (e) {
  await client.query('ROLLBACK');
  throw e;
} finally {
  client.release();
}

Production Guidance

Keep transactions short. Long transactions increase lock contention and reduce concurrency.