1. Concept library
  2. Backend with Node.js
  3. Module 6: Data access layers

Concept

Transactions

A transaction makes several statements succeed or fail together. Use one whenever two writes must agree, such as moving money between rows, and keep it short so it does not hold locks.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what a transaction guarantees and when to use one
  2. Move money between two rows inside one transaction
  3. Spot the network call inside a transaction

In practice

A few lines that show Transactions doing its job.

JavaScript
await sql.begin(async (tx) => {
  const [from] = await tx`
    UPDATE accounts SET balance = balance - ${cents}
    WHERE id = ${fromId} AND balance >= ${cents} RETURNING id`;
  if (!from) throw new Error("insufficient funds");     // rolls back
  await tx`UPDATE accounts SET balance = balance + ${cents} WHERE id = ${toId}`;
});

The common mistake

Watch for

Doing a network call, such as charging a card, inside a database transaction. The transaction holds locks for the whole call, and a timeout leaves you unsure whether the charge happened.

What to know first

Your roadmap puts these before Transactions, unless you already know them.

How it stays learned

Once a session shows you understand Transactions, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← Migrations