How to manage NestJS and TypeORM transactions without passing EntityManager manually
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 operate on separate connections outside the transaction. Manually threading the EntityManager through every repository method pollutes domain interfaces with ORM-specific dependencies, breaking clean architecture principles. The article proposes a solution using AsyncLocalStorage — roughly 60 lines of code — that lets repositories automatically enlist in the active transaction without requiring any parameter to be passed. Beyond the core fix, the author identifies three practical pitfalls: network calls inside transactions holding database connections too long, failure-logging writes being rolled back alongside the errors they document, and nested transaction calls accidentally creating independent transactions that can deadlock. The goal is to make an entire class of silent correctness failures structurally impossible at the architecture level.
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