You need to mass the query manager to the services, and use it to execute operations, instead of the injected repository. See https://orkhan.gitbook.io/typeorm/docs/transactions#using-queryrunner-to-create-and-control-state-of-single-database-connection for an example of using the manager. Answer from ccb621 on reddit.com
🌐
Medium
medium.com › @dev.muhammet.ozen › advanced-transaction-management-with-nestjs-typeorm-43a839363491
Advanced Transaction Management with NestJS & TypeORM | by Muhammet Özen | Medium
September 17, 2023 - As I stated above, this is a simple approach where we create a query runner, get a connection, start a transaction, and execute all queries over that query runner. Imagine we have two TypeORM entities as Order and Item .
🌐
Reddit
reddit.com › r/nestjs › how can i use transactions with typeorm across multiple services
r/nestjs on Reddit: How can I use transactions with typeorm across multiple services
January 21, 2024 -

This is my current code, it supposed to start a transaction in the update method that used other services.

  async update(authContext: AuthContext, id: string, updatePortfolioDto: UpdatePortfolioDto, isSaved = false): Promise<Portfolio> {

    const queryRunner = this.dataSource.createQueryRunner();

  await queryRunner.connect();
  await queryRunner.startTransaction();
  try{
    await this.sleeveService.deleteForPortfolio(authContext, id);
    const updatedPortfolio = this.portfoliosRepository.update(id, portfolio);
    await queryRunner.commitTransaction();
    return updatedPortfolio

  }catch(err){
    await queryRunner.rollbackTransaction();
  }finally{
    await queryRunner.release();
  }
  }

As you can see, I am calling a method from another sevice and repository.

For example deleteForPortfolio method in the sleeveservice is

export class TypeOrmSleeveRepository implements ISleevesRepository {
  private readonly logger = new Logger(TypeOrmSleeveRepository.name);

  constructor(@InjectRepository(Sleeve) private readonly sleeveRepository: Repository<Sleeve>) {}

  deleteForPortfolio(authContext: AuthContext, portfolioId: string) {
    this.sleeveRepository
      .createQueryBuilder('sleeve')
      .delete()
      .where('sleeve.portfolioId = :portfolioId', { portfolioId })
      .andWhere('sleeve.tenantId = :tenantId', { tenantId: authContext.tenantId })
      .execute();
  }
}

and the portfolio update method is

  async update(id: string, portfolio: Portfolio): Promise<Portfolio> {
    try {
      const updatedPortfolio = await this.portfolioRepository.preload({
        id,
        ...portfolio
      });

      if (!updatedPortfolio) {
        this.logger.warn(`Portfolio with ID ${id} not found`);
        throw new NotFoundException(`Portfolio with ID ${id} not found`);
      }
      const savedPortfolio = await this.portfolioRepository.save(updatedPortfolio);
      this.logger.log(`Updated Portfolio with ID ${id}`);
      return savedPortfolio;
    } catch (error) {
      if (error instanceof NotFoundException) {
        throw error;
      }
      this.logger.error(`Error updating portfolio with ID ${id}: ${error.message}`, error.stack);
      throw error;
    }
  }

Currently my code does not work. How can I fix this please ?

Discussions

how to use transaction across service in nestjs with typeorm - Stack Overflow
How can I have a transaction across different service in my project? I try my code as below but the transaction doesn't rollback while exception threw. The following code will rollback as expected... More on stackoverflow.com
🌐 stackoverflow.com
To migrate or not to migrate - is TypeORM really dying?
It's not done. Yes, alternatives like Prisma, drizzle got super popular and I too feel that these are superior in terms of developer experience. But... Is it worth,in terms of cost,time,effort to migrate to the new orm? Are you having any severe problems, which cannot be solved? More on reddit.com
🌐 r/node
60
60
April 2, 2024
TypeOrm transaction [Help]
the entities in foodFxStore have to be created by the entity manager within the transaction. You cannot create them from outside the transaction and expect a successful rollback. More on reddit.com
🌐 r/Nestjs_framework
10
2
September 18, 2023
How do you handle database transactions in your NestJs project with TypeORM?
There used to be a `@Transaction()` decorator in TypeOrm, but it's gone since version 3.0.0. Since then I pass around repositories. public async someFunction({ _userRepository }: { _userRepository?: Repository }): Promise { const userRepository = _userRepository || this.userRespository; // do some stuff with userRepository } More on reddit.com
🌐 r/Nestjs_framework
5
1
March 6, 2023
🌐
Better Programming
betterprogramming.pub › handling-transactions-in-typeorm-and-nest-js-with-ease-3a417e6ab5
Handling Transactions in TypeORM and Nest.js With Ease | by Dmitry Shamshurin | Better Programming
April 6, 2022 - Inside of the main transaction we first call the runWithinTransaction method of our CreateBasicUserTransaction, passing the manager that was created by the outer transaction. This is very important because this manager will be that one piece that holds everything together. Then we call our database abstraction layer classes such as DbUserService, DbBalanceService that handle everything that we need (in relation to entities), be it a simple call to the TypeORM repository, several of such calls, some fetching and transforming data, or virtually anything that you see fit in this layer.
🌐
Aaron Boman
aaronboman.com › programming › 2020 › 05 › 15 › per-request-database-transactions-with-nestjs-and-typeorm
Per-Request Database Transactions with NestJS and TypeORM – Aaron Boman
July 12, 2024 - NestJS provides a very powerful dependency injection mechanism that allows us to create a new transaction, scoped by request and then allow for other services to create repositories using the current transaction EntityManager if set so that large blocks of business logic can be executed atomically. Thanks very much for posting this. I had been looking for a solution to transactions with Nest & TypeORM for ages.
🌐
DEV Community
dev.to › alphamikle › the-easiest-way-to-use-transactions-in-nest-js-41h0
The easiest way to use transactions in Nest.js - DEV Community
February 13, 2021 - Thus, we come to the conclusion that in order to be able to use transactions in Nest when using TypeORM, it is necessary to pass the connection class into the controller / service constructor, for now we just remember this.
Find elsewhere
🌐
PROGRESSIVE CODER
progressivecoder.com › home › blog › how to perform a nestjs typeorm transaction using queryrunner?
How to perform a NestJS TypeORM Transaction using QueryRunner?
February 10, 2023 - Then, we save all the books (in this case 2 books) as part of the same transaction. If something goes wrong, we rollback everything. Else, we commit the transaction and release the connection. With this, we are done with NestJS TypeORM Transaction using QueryRunner.
🌐
Medium
medium.com › @jsankit99 › transaction-management-in-nestjs-typeorm-2-3-clean-repository-layer-e904b9146800
Transaction Management in NestJS + TypeORM (2/3): Clean Repository Layer | by Ankit Pradhan | Medium
January 28, 2026 - Full TypeORM API access - All methods work automatically · Transaction-aware by default - Respects active transactions seamlessly · Custom methods supported - Add business logic without friction · Type-safe - Full IDE autocomplete and type checking ... Combined with Part 1’s DbTransactionService and DbTransactionContext, you now have a complete, production-ready transaction management solution for NestJS + TypeORM.
🌐
GitHub
github.com › alphamikle › nest_transact
GitHub - alphamikle/nest_transact: Simplest transactions support for Nestjs with Typeorm · GitHub
It can be, for example, some cache services, or anything, which you don't want to recreate and which is not a part of transaction logic: // ./example/src/transfer/info.controller.ts import { Controller, Get } from '@nestjs/common'; import { DataSource } from 'typeorm'; import { InfoService } from './info.service'; import { CacheService } from './cache.service'; @Controller('info') export class InfoController { constructor( private readonly infoService: InfoService, private readonly dataSource: DataSource, ) { } @Get() async getInfo() { return this.dataSource.transaction(manager => { return this.infoService.withTransaction(manager, { excluded: [CacheService] }).getInfo(); }); } }
Starred by 119 users
Forked by 20 users
Languages   TypeScript 94.9% | Shell 3.1% | JavaScript 1.9% | Dockerfile 0.1%
🌐
Medium
medium.com › @neerajsonii › ninja-way-of-handling-database-transactions-with-typeorm-in-nestjs-be95241b24d9
Ninja way of handling Database Transactions with Typeorm in NestJs. | by Neeraj Soni | Medium
December 19, 2022 - A transaction class will create a transaction object and return. import { DataSource } from 'typeorm'; export class DbTransaction { private queryRunner = DataSource.createQueryRunner(); constructor() {} async start(): Promise<TransactionRunner> { return this.queryRunner.connect(); } async commitTransaction(): Promise<void> { return this.queryRunner.commitTransaction(); } async rollbackTransaction(): Promise<void> { return this.queryRunner.rollbackTransaction(); } async release(): Promise<void> { return this.queryRunner.release(); } }
🌐
DZone
dzone.com › data engineering › databases › how to perform a nestjs typeorm transaction using queryrunner?
NestJS TypeORM Transaction Using QueryRunner
October 31, 2021 - The Connection class resides in the typeorm package. The below import statement will be needed. ... The Connection object does not represent a single database connection. It basically points to a pool of connections. To refer to a single database collection, we use the QueryRunner class. Basically, every instance of the QueryRunner is a connection. We can now use the Connection object to create a transaction.
🌐
Medium
medium.com › @testjokerqwerty › integrating-typeorm-transactional-in-your-nest-js-project-a-step-by-step-guide-26d2093ef1b5
Integrating TypeORM-Transactional in Your Nest.js Project: A Step-by-Step Guide | by Eugene Moskalenko | Medium
November 27, 2024 - 3. Configure TypeORM Using @nestjs/config: Create a configuration file (e.g., typeorm.config.ts) to register the TypeORM configuration with @nestjs/config:
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-i-harnessed-transactions-in-nestjs-with-typeorm-without-a-headache-e901aee7aff7
How I Harnessed Transactions in NestJS with TypeORM Without a Headache | JavaScript in Plain English
March 24, 2024 - A big challenge came up when I looked into using NestJS's interceptor layer, which only works for the Controller layer. This meant that every time a request was made, a transaction would start. This wasn't efficient and added too many restrictions.
🌐
HackerNoon
hackernoon.com › the-most-convenient-ways-of-writing-transactions-within-the-nestjs-typeorm-stack-3q3q33jd
The Most Convenient Ways of Writing Transactions Within the Nest.js + TypeORM Stack | HackerNoon
February 28, 2021 - // ... SELECT "User"."id" AS "User_id", "User"."name" AS "User_name", "User"."defaultPurseId" AS "User_defaultPurseId" FROM "user" "User" WHERE "User"."id" IN ($1) START TRANSACTION UPDATE "purse" SET "balance" = $2 WHERE "id" IN ($1) COMMIT SELECT "Purse"."id" AS "Purse_id", "Purse"."balance" AS "Purse_balance", "Purse"."userId" AS "Purse_userId" FROM "purse" "Purse" WHERE "Purse"."id" IN ($1) START TRANSACTION UPDATE "purse" SET "balance" = $2 WHERE "id" IN ($1) COMMIT · By the way - I did not write this request by hand, but pulled it out of the ORM logs, but it reflects the essence. Everything is pretty simple and straightforward. To build the queries, TypeORM was used, which we will return to a little later.
🌐
Medium
medium.com › @jsankit99 › transaction-management-in-nestjs-typeorm-3-3-the-transactional-decorator-7fd60466b8a4
Transaction Management in NestJS + TypeORM (3/3): The @Transactional Decorator | by Ankit Pradhan | Medium
January 28, 2026 - @Injectable() export class OrderService { @Transactional() async createOrder(userId: string, items: OrderItem[]) { const order = await this.orderRepo.save({ userId, items }); await this.inventoryService.reserveItems(items); return order; } } Much cleaner! That’s what we’re building. import { SetMetadata } from '@nestjs/common'; import { IsolationLevel } from 'typeorm/driver/types/IsolationLevel'; // Metadata key used to identify transactional methods export const TRANSACTIONAL_KEY = Symbol('TRANSACTIONAL_METHOD'); /** * Marks a method as transactional.
🌐
Medium
medium.com › @alperenergul49 › understanding-typeorm-transactions-a-step-by-step-guide-with-nest-js-f682b63b514a
Understanding TypeORM Transactions: A Step-by-Step Guide with Nest.js | by Alperen Ergul | Oct, 2024 | Medium | Medium
March 21, 2025 - Transaction ensures that a series of database operations (e.g. inserts, deletes, updates) are completed successfully or undone as if none of them had been done. It is used to maintain integrity…
🌐
NestJS
docs.nestjs.com › techniques › database
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).
🌐
Bytesmith
bytesmith.dev › blog › 20240320-nestjs-transactions
How I Harnessed Transactions in NestJS with TypeORM ...
March 19, 2024 - AI Engineering Studio. Senior engineers ship your product in weeks — production-grade from day one, no rebuild in six months.