How should a TypeORM transaction work?
Try code in the playgroundUnderstand 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:
// 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.
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.
Turn this concept into a clear answer.
- Explain which exact writes belong together and demonstrate that each uses the transaction manager.
Adapted from 03_NESTJS.md · “How should a TypeORM transaction work?”. Examples are study fragments; framework behavior can depend on your version.