Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Transactions

Transactions in TypeORM and Sequelize

Compare managed and manual transactions in TypeORM (EntityManager, QueryRunner) and Sequelize, pass the transaction correctly and run code after commit.

Both libraries offer two styles of transaction. A managed style takes a callback: the library opens a transaction, runs your function, commits if it returns and rolls back if it throws. A manual style gives you an object and you call commit and rollback yourself. Managed is shorter and safer; manual is for cases where the transaction must outlive one function.

TypeORM and Sequelize are npm packages, so their code in this lesson is read-only. The runnable blocks build a small stand-in transaction() helper on node:sqlite so you can see exactly the control flow the libraries implement.

TypeORM: managed

dataSource.transaction() gives your callback an EntityManager bound to one connection and one open transaction. Everything you do through that manager is inside the transaction.

TypeScript
await dataSource.transaction(async (manager) => {
  const from = await manager.findOneByOrFail(Account, { id: 1 });
  const to = await manager.findOneByOrFail(Account, { id: 2 });

  from.balance -= 30;
  to.balance += 30;

  await manager.save([from, to]);
}); // commit here; a thrown error rolls back and rethrows

The key rule: use the manager argument, not a repository you got from the data source earlier. A repository from dataSource.getRepository() uses a different connection and would run outside the transaction. To get a repository inside it, call manager.getRepository(Account).

TypeORM: manual with QueryRunner

A QueryRunner is one dedicated connection. You start, commit and release it yourself.

TypeScript
const qr = dataSource.createQueryRunner();
await qr.connect();
await qr.startTransaction('SERIALIZABLE'); // isolation level is optional
try {
  await qr.manager.update(Account, 1, { balance: () => 'balance - 30' });
  await qr.manager.update(Account, 2, { balance: () => 'balance + 30' });
  await qr.commitTransaction();
} catch (err) {
  await qr.rollbackTransaction();
  throw err;
} finally {
  await qr.release(); // always give the connection back to the pool
}

Forgetting release() leaks a connection; after enough leaks the pool is empty and every request hangs. The finally block is not optional.

Sequelize: managed

JavaScript
const result = await sequelize.transaction(async (t) => {
  const from = await Account.findByPk(1, { transaction: t });
  const to = await Account.findByPk(2, { transaction: t });

  await from.update({ balance: from.balance - 30 }, { transaction: t });
  await to.update({ balance: to.balance + 30 }, { transaction: t });

  return 'done';
});

Here the transaction must be passed to every call through the transaction option. Forget one and that query runs outside the transaction on a different connection, a bug that tests rarely catch.

Sequelize can remove that risk with CLS (continuation-local storage): install cls-hooked, call Sequelize.useCLS(namespace), and every query inside the callback uses the active transaction automatically. It is convenient, but it is global magic, so many teams keep passing t explicitly.

Sequelize: unmanaged

JavaScript
const t = await sequelize.transaction({ isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ });
try {
  await Order.create({ total: 90 }, { transaction: t });
  await t.commit();
} catch (e) {
  await t.rollback();
  throw e;
}

The same control flow, runnable

This stand-in transaction(fn) mirrors what both libraries do: begin, call your function with a handle, commit on success, roll back and rethrow on failure. It also supports an afterCommit hook, which both libraries offer for side effects such as sending an email.

Node.js A managed transaction helper (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second transaction credited account 2 first, then failed. The rollback restored account 2, and the afterCommit callback never ran, which is exactly why you register side effects there instead of calling them inline.

Transaction pitfalls

  1. Using the wrong handle. TypeORM: the repository from the data source. Sequelize: a call missing { transaction: t }.
  2. Long transactions. A transaction holds locks. Do not call an HTTP API or wait for a user inside one.
  3. Swallowing errors. If you catch an error inside the managed callback and do not rethrow, the library thinks everything went fine and commits.
  4. Leaked connections. Manual style needs release() or commit/rollback on every path.
  5. Side effects before commit. Sending an email, then rolling back, leaves a lie in someone's inbox.
Node.js Swallowed errors still commit (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Inside dataSource.transaction(async (manager) => ...), which should you use for queries?

    Only the manager is bound to the transaction's connection.
  2. 2. What happens in Sequelize if one query inside the callback lacks { transaction: t }?

    Without CLS, the transaction is passed explicitly, and a forgotten option silently escapes it.
  3. 3. Why must a QueryRunner be released in a finally block?

    A runner holds one pooled connection until release() is called.
  4. 4. You catch an error inside a managed transaction callback and do not rethrow. What happens?

    Managed helpers only roll back when the callback throws or rejects.

Summary

  • Managed transactions (callback) commit on return and roll back on throw; manual ones need commit, rollback and release.
  • Always use the transaction-bound handle: manager in TypeORM, { transaction: t } (or CLS) in Sequelize.
  • Keep transactions short and rethrow errors.
  • Run side effects after commit.

Next: Locking and Isolation Levels