How to Manage NestJS Transactions Without Passing EntityManager Through Every Layer
A common but silent bug in NestJS applications causes database rows to persist even after a transaction rollback, because some repositories never receive the EntityManager and run queries on a separate connection outside the transaction. Manually threading the EntityManager through every service method and repository interface forces TypeORM-specific code into the domain layer, breaking clean architecture principles. The article proposes a roughly 60-line solution using Node.js AsyncLocalStorage, allowing the transaction to open once at the controller level while repositories automatically enlist themselves without receiving any parameters. The author also addresses three side-effects of this transaction boundary design: external network calls holding database connections too long, failure-logging records being rolled back alongside the errors they document, and nested execute calls creating independent transactions rather than true nested ones. Each problem is presented alongside a concrete fix, making the overall approach suitable for production-grade NestJS applications with a repository pattern.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in