LESSON 13 / 18·2 min readIntermediate

How should a TypeORM transaction work?

Try code in the playground
01 Understand02 Recall03 Prepare

Understand the concept

A transaction groups database changes so they can commit together or roll back together. In TypeORM, the transaction callback receives a manager tied to that transaction's connection. Queries issued through an unrelated global repository may not participate, even if they appear inside the same JavaScript callback.

Important ideas

  • Put related writes inside one transaction.

  • Use the provided transaction manager for every query in that transaction.

  • Let failures roll back; avoid slow external API calls while holding locks.

  • Choose a concurrency strategy as well as a transaction boundary; atomicity alone does not prevent every race.

Example — transaction context:

TypeScript
// dataSource, Order and OrderAudit are configured application objects.
await dataSource.transaction(async manager => {
  const order = await manager.save(Order, { status: 'created' });
  await manager.save(OrderAudit, { orderId: order.id, action: 'created' });
});
  • Both writes use the supplied manager. An uncaught failure prevents the transaction from committing either write.
PAUSE & RECALL

Can you explain it without the notes?

How should a TypeORM transaction work?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

A transaction groups database changes so they can commit together or roll back together. In TypeORM, the transaction callback receives a manager tied to that transaction's connection. Queries issued through an unrelated global repository may not participate, even if they appear inside the same JavaScript callback.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Explain which exact writes belong together and demonstrate that each uses the transaction manager.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: What are N+1, eager loading and lazy loading?

Adapted from 03_NESTJS.md · “How should a TypeORM transaction work?”. Examples are study fragments; framework behavior can depend on your version.