You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Suggestion: using AsyncLocalStorage for transactions #5729
First, a disclaimer: AsyncLocalStorage is not available in all supported versions of Node.js yet but this can either be discussed for the future or there are ways of having similar APIs in older version sof Node.js depending on the choices made.
Right now (if I understand the doc well), to build a transaction, one must keep a list of writes and commit all of them at once at the end. So let's imagine in a web server, when the user wants all the db writes linked with the HTTP requests to be in the same transaction, they would have to do something like attaching an array to a request object or something like that, add all the writes to it and commit before the response with prisma.$transaction(...).
Suggested solution
Using an API like AsyncLocalStorage can give the following UX:
prisma.$openTransaction()
...
write_1
...
write_n
prisma.$commitTransaction() <- all the writes are automatically linked with the current transaction
This has a few shortcomings:
how do you do when you have multiple transactions at once?
So I am mostly trying the water to see if there would be interest and what would be the feedback over here on such feature :)
Reacted by Philipp Steinrötter, Bertholet Damien, Toni Villena, zerozelta, Carlo Corradini, Renan Modenese, Antoine Kleinpeter, Vladislav, Rami Theeb, Yevhenii Hyzyla and 6 more
@vdeturckheim - I don't think you would need AsyncLocalStorage for something like this. As Node is single-threaded, it is safe to create a singleton array per request and append db actions to it. You could then execute them all in a transaction when the request ends. Does that make sense?
@steinroe - When Prisma introduces support for long-running transactions, it should be possible to create a third-party library like cls-hooked. I don't think it is likely that this functionality will be included directly in Prisma. Does that make sense?
@sorenbs this forces you to always have access to this singleton array, meaning you need to pass a context with all function calls. The point of AsyncLocalStorage is to be able not to do that and provide a UX where the code would be the same inside and outside transactions.
Reacted by Søren Bramer Schmidt, Bertholet Damien, Fahad Aijaz and Janvario
I agree with the proposition. Without that, it will be impossible for us to migrate or even used Prisma in any production application. It's an essential feature to manage transactions correctly without programmation overhead.
Other than that, Prisma fixes a lot of ORMs commons problems. I'm in love with what you've built, it's just amazing.
Let me know if I can help you to provide this feature, it is really essential for all large applications.
And Prisma deserves to be used by large applications.
Reacted by Mikhaël Aubut, Toni Villena, Dominic Bou-Samra, pierre, Vladislav and Dino Bettini
It would be awesome to have this feature, it wouldn't be actually so hard to implement. At the time being, you can use cls-hooked or pure AsyncLocalStorage to leverage async context with transactions (similarly how Sequelize does it) (if you use NestJS, you can use nestjs-cls to do the same)
/* some service that initiates the transaction */// ...awaitthis.prisma.$transaction(async(prisma)=>{// store the transaction prisma client inside the contexttransactionContext.set('prisma',prisma);constresult=awaitserviceThatSouldUseTransaction.doTheThing('something');// ... more code})
/* service that should use transaction */// ...doTheThing(input: string){// either reuse prisma client from context or use the default oneconstprisma=transactionContext.get('prisma')??this.prisma;// if the prisma client was retrieved form the context, the call will be run within the transactionreturnprisma.thing.findMany({where: {what: input}})}
In real application, you could of course abstract it and make it more type safe, but this is the gist.
P.S. You need to enable interactive transactions to be able to pass a callback function to $transaction.
Reacted by Mahee Gamage, Vitor Aderaldo, Charles Bodman and Yuu
You can now pass a function to prisma.$transaction:
awaitprisma.$transaction(async(prisma)=>{// 1. Decrement amount from the sender.constsender=awaitprisma.account.update({data: {balance: {decrement: amount,},},where: {email: from,},})// 2. Verify that the sender's balance didn't go below zero.if(sender.balance<0){thrownewError(`${from} doesn't have enough to send ${amount}`)}// 3. Increment the recipient's balance by amountconstrecipient=prisma.account.update({data: {balance: {increment: amount,},},where: {email: to,},})returnrecipient})
Use it wisely 😉
If you have any feedback on this feature, please let us know in this issue. Now's a good time to give it a go, since we're actively resolving issues in preparation for making it Generally Available.
Hey @renatoaraujoc, I believe I have most of it working. I need to finish a few remaining details. Once those are done and rigorous testing validates the solution, I'll share what I can. 😉
Reacted by Renato Araujo Carneiro and Vivek Bhargav
In the meantime (if you use NestJS), I released a new version of nestjs-cls with support for plugins together with a Transactional plugin and a Prisma adapter for it.
The important part is that it does not try to monkey-patch the internals of any library, but still makes propagating the Prisma transaction as easy as:
@Injectable()classUserService{constructor(
@InjectTransaction()privatereadonlyprismaTx: Transaction<TransactionalAdapterPrisma>,privatereadonlyaccountService: AccountService,){}
@Transactional()asynccreateUser(name: string): Promise<User>{constuser=awaitthis.prismaTx.user.create({data: { name }});awaitthis.accountService.createAccountForUser(user.id);returnuser;}}
@Injectable()classAccountService{constructor(
@InjectTransaction()privatereadonlyprismaTx: Transaction<TransactionalAdapterPrisma>,){}asynccreateAccountForUser(id: number): Promise<Account>{// if called within a transaction, `prismaTx` will reference the same transactional clientreturnthis.prismaTx.user.create({data: {userId: id,number: Math.random()},});}}
Reacted by Charles Bodman, Mohammad Jawad (Kasir) Barati, Jacques Germishuys and Cheeshian Chuah
Hi @renatoaraujoc, @codechikbhoka, @nitedani and everybody else! Let me share our current working version. If you find any issues, please leave a comment! 🙇♂️
Summary
We achieve seamless tx propagation by
monkey-patching Prisma's $transaction(). On the top-level, we wrap the execution into an ALS context. Otherwise, we keep reusing the tx client from the ALS
creating a Proxy around PrismaClient. This ensures that an arbitrary this.prisma.todo.findFirst() uses the active tx client if available
The @Transactional decorator only needs to check if it's being executed in an already running transaction context. To open a new transaction, it defers this responsibility to the patched and proxied Prisma.
The Prisma Patch
We can create a function that receives a PrismaClient, patches it and returns it.
import{Prisma,PrismaClient}from'@prisma/client';import{ClsService,ClsServiceManager}from'nestjs-cls';exportconstTX_CLIENT_KEY='txClient';exportfunctionpatchPrismaTx<TextendsPrismaClient>(prisma: T){constoriginal$transaction=prisma.$transaction;prisma.$transaction=(...args: unknown[])=>{if(typeofargs[0]==='function'){constfn=args[0]as(txClient: Prisma.TransactionClient)=>Promise<unknown>;args[0]=async(txClient: Prisma.TransactionClient)=>{constclsService=ClsServiceManager.getClsService();constmaybeExistingTxClient=clsService.get<Prisma.TransactionClient|undefined>(TX_CLIENT_KEY);if(maybeExistingTxClient){console.log(`Return txClient from ALS`);returnfn(maybeExistingTxClient);}if(clsService.isActive()){// covering this for completeness, should rarely happenconsole.warn(`Context active without txClient`);returnexecuteInContext({context: clsService,
txClient,
fn,});}// this occurs on the top-levelreturnclsService.run(async()=>executeInContext({context: clsService,
txClient,
fn,}));};}returnoriginal$transaction.apply(prisma,argsasany)asany;};returnprisma;}typeExecutionParams={context: ClsService;txClient: Prisma.TransactionClient;fn: (txClient: Prisma.TransactionClient)=>Promise<unknown>;};asyncfunctionexecuteInContext({ context, txClient, fn }: ExecutionParams){context.set(TX_CLIENT_KEY,txClient);console.log(`Top-level: open context, store txClient and propagate`);try{returnawaitfn(txClient);}finally{context.set(TX_CLIENT_KEY,undefined);console.log(`Top-level: ALS context reset`);}}
The Prisma Proxy
We're essentially making sure that
this.prisma.todo.findFirst() uses the active tx client if available
no matter how deep you nest prisma.$transaction() calls, they all receive the same client.
exportfunctioncreatePrismaProxy<TextendsPrismaClient>(target: T){returnnewProxy(target,{get(_,prop,receiver){// provide an undocumented escape hatch to access the root PrismaClient and start top-level transactionsif(prop==='$root'){console.log(`[Proxy] Accessing root Prisma`);returntarget;}constmaybeExistingTxClient=ClsServiceManager.getClsService().get<Prisma.TransactionClient|undefined>(TX_CLIENT_KEY);constprisma=maybeExistingTxClient??target;if(prop==='$transaction'&&maybeExistingTxClient&&typeoftarget[prop]==='function'){console.log(`[Proxy] $transaction called on a txClient, continue nesting it`);returnfunction(...args: unknown[]){// grab the callback of the native "prisma.$transaction(callback, options)" invocation and invoke it with the txClient from the ALSif(typeofargs[0]==='function'){returnargs[0](maybeExistingTxClient);}else{thrownewError('prisma.$transaction called with a non-function argument');}};}returnReflect.get(prisma,prop,receiver);},// following traps needed to make the Proxy work with jest.spyOn()set(_,prop,newValue,receiver){if(prop==='$transaction'){console.log(`Please don't spy on $transaction.`);returnfalse;}constmaybeExistingTxClient=ClsServiceManager.getClsService().get<Prisma.TransactionClient|undefined>(TX_CLIENT_KEY);constprisma=maybeExistingTxClient??target;returnReflect.set(prisma,prop,newValue,receiver);},defineProperty(_,prop,attributes){constmaybeExistingTxClient=ClsServiceManager.getClsService().get<Prisma.TransactionClient|undefined>(TX_CLIENT_KEY);constprisma=maybeExistingTxClient??target;returnReflect.defineProperty(prisma,prop,attributes);},});}
Putting it together
All we need to do is make sure that the Prisma client we're using in our application is patched and proxied properly. In this example, I assume a Nest PrismaService that is used across the application an a singleton.
With the patched Prisma in place, the decorator's only responsibilities are to:
make sure PrismaService is available (Inject)
check if it's being executed in an active ALS context with a tx client
"request" a real transaction by accessing the $root Prisma. The patch will take care of setting up the ALS context
exportfunctionTransactional(isolationLevel?: Prisma.TransactionIsolationLevel): MethodDecorator{constinjectPrisma=Inject(PrismaService);return(target: any,propertyKey: string|symbol,descriptor: PropertyDescriptor)=>{injectPrisma(target,'prismaClient');constoriginalMethod=descriptor.value;descriptor.value=asyncfunction(...args: unknown[]){constcls=ClsServiceManager.getClsService();if(cls.get(TX_CLIENT_KEY)){// A transaction has already been started. Just call the function.// The top-level wrapper will take care of resetting the context.console.log('Already running in an active transaction');returnoriginalMethod.apply(this,[...args]);}constprisma=(thisasany).prismaClientasPrismaService;// defer the context setup to the patched prismareturn(prisma['$root']asPrismaClient).$transaction(async()=>{returnoriginalMethod.apply(this,[...args]);},{
isolationLevel,});};};}
Limitations
No support for nested, isolated transactions. This version will either wrap everything or nothing. This should already cover the majority of cases. Nested, isolated transactions (preferably via CHECKPOINTs) are future work.
You might notice that the patch does not take the array-based $transaction([]) usage into account. This is a conscious design decision. It's practically a legacy way of serially executing statements, most of us use the interactive transactions (callbacks) anyway. If you still need to support it, you should implement the handling.
Spying on prisma.$transaction() is a no-go. The patch and the proxy are essential to make the propagation work. If you have tests where you change the behavior of $transaction() via Jest, it's going to break it. I'm going to leave it up to you to decide if it's a good practice to spy directly on a low-level operation like prisma.$transaction() on a day-to-day basis. Just be aware of the limitation.
Please leave feedback if you notice anything. 🙇♂️ Have fun! 🥳
Reacted by Ondřej Švanda, Charles Bodman, Alaa Moucharrafie, zoff4ick, Exil, Alexander Requelme, Andrii Khoma and Joshua Jones
Reacted by Alexandre Gaudencio, Charles Bodman, Alaa Moucharrafie, Renato Araujo Carneiro, Andrii Khoma, Joshua Jones and Franzua Plasencia Caballero
@fuvidani Been looking for a solution to handle prisma transactions in a clean way in NestJS, and at the bottom of my rabithole I have found your solution. Thank you for sharing, really awesome of you 💙
Bit new to NestJS still so appoligies if my follow up questions to your suggestion seem basic.
Would I be able to use use the Transactional decorator you have created both at the service level and/or the repository level if I end up splitting my prisma commands out on their own. Or would their be drawbacks to this?
(As I write this I realize their might be numeral design drawbacks to adding the decorator on the repository level).
I am unsure of how to use the decorator, would something like below be correct usage of it?
export class UserService {
constructor(private prismaService: PrismaService){}
@Transactional()
public updateUser(data){
this.prismaService.user.update(...);
this.prismaService.log.create(...);
}
}
If I had a UserRepository would this be a correct usage?
export class UserService {
constructor(
private userRepository: UserRepository,
private logService: LogService
){}
@Transactional()
public updateUser(data){
this.userRepository.update(...);
this.logService.log(...);
}
}
export class UserRepository {
constructor(private prismaService: PrismaService){}
public update(data){
this.prismaService.user.update(...);
}
}
PrismaClient has property with unknown for me Symbol key.
When debugger tries to read that it falls to an infinity loop.
I guess, the same happens when I tring to log value of the property.
After a 1-2 minutes console.log writes an extremely long stack trace.
That part repeates many times:
@fuvidani Been looking for a solution to handle prisma transactions in a clean way in NestJS, and at the bottom of my rabithole I have found your solution. Thank you for sharing, really awesome of you 💙
Bit new to NestJS still so appoligies if my follow up questions to your suggestion seem basic.
Would I be able to use use the Transactional decorator you have created both at the service level and/or the repository level if I end up splitting my prisma commands out on their own. Or would their be drawbacks to this?
(As I write this I realize their might be numeral design drawbacks to adding the decorator on the repository level).
I am unsure of how to use the decorator, would something like below be correct usage of it?
export class UserService {
constructor(private prismaService: PrismaService){}
@Transactional()
public updateUser(data){
this.prismaService.user.update(...);
this.prismaService.log.create(...);
}
}
If I had a UserRepository would this be a correct usage?
export class UserService {
constructor(
private userRepository: UserRepository,
private logService: LogService
){}
@Transactional()
public updateUser(data){
this.userRepository.update(...);
this.logService.log(...);
}
}
export class UserRepository {
constructor(private prismaService: PrismaService){}
public update(data){
this.prismaService.user.update(...);
}
}
Hi @adamlamaa! 👋 Apologies for the delayed response 😔
Would I be able to use use the Transactional decorator you have created both at the service level and/or the repository level if I end up splitting my prisma commands out on their own. Or would their be drawbacks to this?
(As I write this I realize their might be numeral design drawbacks to adding the decorator on the repository level).
Of course! The beauty of the decorator is that it can be freely nested/composed. If you check its implementation you'll see that if the decorator detects an active tx client in the call-chain, it simply executes the decorated method: any prisma command later on will automatically reuse the same tx client.
About where to place the decorators: we have cases where we use it on a repository method. For instance you could have a model backed by 2 tables that are kept in sync: a read-optimized and an append-only one for historization. The double-table approach is abstracted by the repository, and the @Transactional decorator on writing methods ensure atomicity across the two tables.
Nevertheless, you're right that most of the time the decorator finds its usage on the service layer because it is the layer responsible for fulfilling use-cases, orchestrating changes across different models (== tables).
Warning: isolation levels
In case you're familiar with isolation levels and apply them consciously, be aware that the automatic transaction propagation affects them too. If you compose multiple service methods that have the decorator on top but with different isolation levels, the top-level one will be applied, always. This is because in most databases you cannot change the isolation level of a transaction as soon as the first query statement is executed. Note: It can only become an issue if you have an inner method decorated with a stricter isolation level than the top-level one. Let me know if this is not clear and I can provide a deeper explanation. 🙇♂️
I am unsure of how to use the decorator, would something like below be correct usage of it?
Yes, perfect!
If I had a UserRepository would this be a correct usage?
Works too!
Btw., you can test atomicity by calling several repository operations from your updateUser method, but before it returns, add throw new Error(). With a Jest test you can verify that the number of rows in the corresponding tables remained the same before and after the execution (i.e. the tx rolled back everything). 😉
I successfully used that approach with minor changes and fixes in the production project for a site with 2-5k online.
But there are a problems.
Warning: undesired transaction wrapping
In a team of 2+ developers, code is being changed, and there is a case when another developer adds a new prisma query to the service's method that could be executed in the @transactional stack.
For example, I have the method createGame (block 1), which is called by service (block 2).
All seems to be good. But if another developer decides inside of GameService verify that the user isn't blacklisted (just an example). verifyUserOrThrow method can be implicitly executed inside of a transaction,
That call may execute many queries to $transactions that can lead to deadlocks caused by attempts to read/update locked DB rows.
// GameServiceasynccreateGame(game: CreateGameArgs){awaitthis.userService.verifyUserOrThrow(game.user);// Dangerous code!!!. Can be executed inside of transaction.constdata=awaitthis.prismaService.pvpGame.create({data: {
...game,state: GameState.IN_PROGRESS,},});// tslint:disable:no-floating-promisesthis.setCurrentGame(data);returndata;}
I wondering how to use that decorator in a safe way.
Currently, I am thinking about an eslint extension that will highlight prisma calls that are inside of possible transactions or another way to make nested queries forbidden with no special decorator or method's call.
Hey guys, putting my two cents in this topic, here is my current working implementation using NestJS. I used as a reference other implementations mentioned here and in other issues, thanks everyone!
My solution involves
A decorator to create a transactional block
Allow running subtransactions nested or not (I only implemented two types of propagation, which are the ones I need right now)
The possibility to run a callback after the current transaction succeeds, useful for event dispatching.
The interface
exportinterfaceAtomicExecutor{runAtomically<R>(callback: ()=>Promise<R>,propagation?: Propagation): Promise<R>;/** * Run the given callback after the current atomic execution succeeds. */defer(callback: ()=>void): void;}exportabstractclassAtomicExecutor{}exportenumPropagation{/** * If a transaction exists, it executes within that transaction. Otherwise, creates a new transaction. */REQUIRED,/** * If a transaction exists, it creates an inner independent transaction. Otherwise, creates a new transaction. */NESTED,}exportfunctionTransactional(propagation?: Propagation): MethodDecorator{constinjectAtomicExecutor=Inject(AtomicExecutor);return(target: NonNullable<unknown>,_,descriptor: PropertyDescriptor)=>{injectAtomicExecutor(target,'atomicExecutor');constoriginalMethod=descriptor.valueas(...args: unknown[])=>Promise<unknown>;// eslint-disable-next-line no-param-reassign -- Needed for the decoratordescriptor.value=asyncfunctionatomic(...args: unknown[]){const{atomicExecutor}=thisas{atomicExecutor: AtomicExecutor};returnatomicExecutor.runAtomically(()=>originalMethod.apply(this,args),propagation);};};}
The implementation
exporttypeProviderState={transaction: PrismaService;rootPromise: Promise<unknown>;};
@Injectable()exportclassPrismaProviderimplementsAtomicExecutor{constructor(privatereadonlyprisma: PrismaService,privatereadonlycontextStore: AsyncLocalStorage<ProviderState>){}getclient(): PrismaService{returnthis.contextStore.getStore()?.transaction??this.prisma;}/** * Runs the callback within a transaction context. */asyncrunAtomically<R>(callback: ()=>Promise<R>,propagation: Propagation=Propagation.REQUIRED): Promise<R>{constcurrentState=this.contextStore.getStore();if(currentState!=null){if(propagation===Propagation.NESTED){returnrunSubTransaction(currentState.transaction,callback);}returncallback();}constpromise: Promise<R>=this.prisma.$transaction((transaction)=>this.contextStore.run({transaction: createTransactionProxy(transaction),rootPromise: promise,},callback));returnpromise;}defer(callback: ()=>void): void{conststate=this.contextStore.getStore();if(state===undefined){callback();return;}state.rootPromise.then(()=>this.contextStore.exit(callback)).catch(()=>{// Errors should be handled by the root promise or the callback itself});}}exportfunctioncreateTransactionProxy<TextendsPrisma.TransactionClient>(transaction: T): PrismaService{returnnewProxy(transaction,{get(_,prop,receiver){if(prop==='$transaction'){returnasyncfunction$transaction(...args: unknown[]){if(typeofargs[0]==='function'){constcallback=args[0]as(transaction: Prisma.TransactionClient)=>Promise<unknown>;constoptions=args[1]as{propagation?: Propagation};if(options?.propagation===Propagation.NESTED){returnrunSubTransaction(transaction,()=>callback(transaction));}returncallback(transaction);}if(Array.isArray(args[0])){constpromises=args[0]asArray<Prisma.PrismaPromise<unknown>>;constoptions=args[1]as{propagation?: Propagation};if(options?.propagation===Propagation.NESTED){returnrunSubTransaction(transaction,()=>Promise.all(promises));}returnPromise.all(promises);}thrownewError('Unsupported $transaction call');};}if(typeofprop==='string'&&!(propintransaction)){thrownewError(`Method "${prop}" is not allowed within a transaction context`);}returnReflect.get(_,prop,receiver);},})asunknownasPrismaService;}asyncfunctionrunSubTransaction<T>(transaction: Prisma.TransactionClient,callback: ()=>Promise<T>): Promise<T>{constsavepointName=randomUUID();awaittransaction.$executeRawUnsafe(`SAVEPOINT "${savepointName}";`);try{constresult=awaitcallback();awaittransaction.$executeRawUnsafe(`RELEASE SAVEPOINT "${savepointName}";`);returnresult;}catch(e){awaittransaction.$executeRawUnsafe(`ROLLBACK TO "${savepointName}";`);throwe;}}
exportabstractclassPrismaRepository{constructor(protectedreadonlyprismaProvider: PrismaProvider){}protectedgetprisma(): PrismaService{returnthis.prismaProvider.client;}}
@Injectable()exportclassProductPrismaRepositoryextendsPrismaRepositoryimplementsProductRepository{constructor(protectedreadonlyprismaProvider: PrismaProvider){super(prismaProvider);}asyncsave(product: Product): Promise<void>{awaitthis.prisma.product.upsert(...);awaitthis.prisma.$transaction(async(prisma)=>{awaitprisma.saleItem.upsert(...);awaitprisma.productStock.upsert(...);});}asyncsafeDelete(): Promise<void>{constwhere={...};try{/** * A nested transaction is required so that the delete operation, when it fails for a foreign key violation, * does not abort a parent transaction if one exists. */awaitthis.prisma.$transaction(async(prisma)=>{awaitprisma.product.delete(where);},{propagation: Propagation.NESTED,});}catch(e){if(this.checkForeignKeyViolation(e)){awaitprisma.product.update({where: where,data: {deletedAt: newDate(),},});return;}throwe;}}}
Service
@Injectable()exportclassProductService{constructor(privatereadonlyproductRepository: ProductRepository,privatereadonlyatomicExecutor: AtomicExecutor,protectedreadonlyeventDispatcher: EventDispatcher){}
@Transactional()asyncdoStuff(payload): Promise<void>{constproduct=newProduct(payload);awaitthis.productRepository.save(product);awaitthis.doThingsInSameTransaction();awaitthis.doThingsInNestedTransaction();this.atomicExecutor.defer(()=>{// Only will be executed after parent transaction is committed, if the safeDelete below fails, this will not be executed.this.eventDispatcher.dispatch(product.getEvents());});awaitthis.productRepository.safeDelete(product);}
@Transactional()asyncdoThingsInSameTransaction(): Promise<void>{
...
}
@Transactional(Propagation.NESTED)asyncdoThingsInNestedTransaction(): Promise<void>{
...
}}
Activity
psteinroe commentedon Mar 9, 2021
+1
We are currently using TypeORM and really want to migrate to prisma, but are still looking for a lean solution to handle transactions such as https://github.com/odavid/typeorm-transactional-cls-hooked is providing for TypeORM.
sorenbs commentedon Jun 14, 2021
@vdeturckheim - I don't think you would need AsyncLocalStorage for something like this. As Node is single-threaded, it is safe to create a singleton array per request and append db actions to it. You could then execute them all in a transaction when the request ends. Does that make sense?
@steinroe - When Prisma introduces support for long-running transactions, it should be possible to create a third-party library like cls-hooked. I don't think it is likely that this functionality will be included directly in Prisma. Does that make sense?
vdeturckheim commentedon Jun 15, 2021
@sorenbs this forces you to always have access to this singleton array, meaning you need to pass a context with all function calls. The point of AsyncLocalStorage is to be able not to do that and provide a UX where the code would be the same inside and outside transactions.
BertholetDamien commentedon Jul 19, 2021
I agree with the proposition. Without that, it will be impossible for us to migrate or even used Prisma in any production application. It's an essential feature to manage transactions correctly without programmation overhead.
Other than that, Prisma fixes a lot of ORMs commons problems. I'm in love with what you've built, it's just amazing.
Let me know if I can help you to provide this feature, it is really essential for all large applications.
And Prisma deserves to be used by large applications.
Papooch commentedon Nov 3, 2021
It would be awesome to have this feature, it wouldn't be actually so hard to implement. At the time being, you can use cls-hooked or pure AsyncLocalStorage to leverage async context with transactions (similarly how Sequelize does it) (if you use NestJS, you can use nestjs-cls to do the same)
In real application, you could of course abstract it and make it more type safe, but this is the gist.
P.S. You need to enable interactive transactions to be able to pass a callback function to
$transaction.matthewmueller commentedon Feb 4, 2022
Thanks for your suggestions everyone! We solved this issue a few months ago with Interactive Transactions, which is now in Preview.
You can now pass a function to
prisma.$transaction:Use it wisely 😉
If you have any feedback on this feature, please let us know in this issue. Now's a good time to give it a go, since we're actively resolving issues in preparation for making it Generally Available.
13 remaining items
fuvidani commentedon Jan 4, 2024
Hey @renatoaraujoc, I believe I have most of it working. I need to finish a few remaining details. Once those are done and rigorous testing validates the solution, I'll share what I can. 😉
renatoaraujoc commentedon Jan 4, 2024
Hey @fuvidani, looks awesome, can't wait!
codechikbhoka commentedon Jan 7, 2024
Waiting for Spring like magical @transactional :)
Papooch commentedon Jan 22, 2024
In the meantime (if you use NestJS), I released a new version of nestjs-cls with support for plugins together with a Transactional plugin and a Prisma adapter for it.
The important part is that it does not try to monkey-patch the internals of any library, but still makes propagating the Prisma transaction as easy as:
fuvidani commentedon Jan 24, 2024
Hi @renatoaraujoc, @codechikbhoka, @nitedani and everybody else! Let me share our current working version. If you find any issues, please leave a comment! 🙇♂️
Summary
We achieve seamless tx propagation by
$transaction(). On the top-level, we wrap the execution into an ALS context. Otherwise, we keep reusing the tx client from the ALSPrismaClient. This ensures that an arbitrarythis.prisma.todo.findFirst()uses the active tx client if availableThe
@Transactionaldecorator only needs to check if it's being executed in an already running transaction context. To open a new transaction, it defers this responsibility to the patched and proxied Prisma.The Prisma Patch
We can create a function that receives a
PrismaClient, patches it and returns it.The Prisma Proxy
We're essentially making sure that
this.prisma.todo.findFirst()uses the active tx client if availableprisma.$transaction()calls, they all receive the same client.Putting it together
All we need to do is make sure that the Prisma client we're using in our application is patched and proxied properly. In this example, I assume a Nest
PrismaServicethat is used across the application an a singleton.Transactional Decorator
With the patched Prisma in place, the decorator's only responsibilities are to:
PrismaServiceis available (Inject)$rootPrisma. The patch will take care of setting up the ALS contextLimitations
CHECKPOINTs) are future work.$transaction([])usage into account. This is a conscious design decision. It's practically a legacy way of serially executing statements, most of us use the interactive transactions (callbacks) anyway. If you still need to support it, you should implement the handling.prisma.$transaction()is a no-go. The patch and the proxy are essential to make the propagation work. If you have tests where you change the behavior of$transaction()via Jest, it's going to break it. I'm going to leave it up to you to decide if it's a good practice to spy directly on a low-level operation likeprisma.$transaction()on a day-to-day basis. Just be aware of the limitation.Please leave feedback if you notice anything. 🙇♂️ Have fun! 🥳
Shahor commentedon Jan 25, 2024
Wow :O
I had plans to implement exactly that on my nestjs codebase so this comment is an actual godsend!
@fuvidani Thank you so much for sharing with everyone, I'm sure it'll benefit the whole community!
adamlamaa commentedon Mar 7, 2024
@fuvidani Been looking for a solution to handle prisma transactions in a clean way in NestJS, and at the bottom of my rabithole I have found your solution. Thank you for sharing, really awesome of you 💙
Bit new to NestJS still so appoligies if my follow up questions to your suggestion seem basic.
Would I be able to use use the Transactional decorator you have created both at the service level and/or the repository level if I end up splitting my prisma commands out on their own. Or would their be drawbacks to this?
(As I write this I realize their might be numeral design drawbacks to adding the decorator on the repository level).
I am unsure of how to use the decorator, would something like below be correct usage of it?
myfunc commentedon Apr 6, 2024
@fuvidani
Faced with the issue:
When I trying access PrismaClient in debugger (VSCode) - debug server freezes.
As "access". Even "get" reading in "VSCode/Variables" panel makes UI frozen.
My guess, it happens when debugger tries get prisma, and createPrismaProxy returns something that node.js debugger doesn't expcect.
myfunc commentedon Apr 6, 2024
Added console.log and noticed that "Symbol()" is read just before freezing.

myfunc commentedon Apr 6, 2024
PrismaClient has property with unknown for me Symbol key.

When debugger tries to read that it falls to an infinity loop.
I guess, the same happens when I tring to log value of the property.
After a 1-2 minutes console.log writes an extremely long stack trace.

That part repeates many times:
Also related issue: #21615
myfunc commentedon Apr 6, 2024
Updating to "@prisma/client": "^5.12.1", fixed a problem
fuvidani commentedon Apr 23, 2024
Hi @adamlamaa! 👋 Apologies for the delayed response 😔
Of course! The beauty of the decorator is that it can be freely nested/composed. If you check its implementation you'll see that if the decorator detects an active tx client in the call-chain, it simply executes the decorated method: any prisma command later on will automatically reuse the same tx client.
About where to place the decorators: we have cases where we use it on a repository method. For instance you could have a model backed by 2 tables that are kept in sync: a read-optimized and an append-only one for historization. The double-table approach is abstracted by the repository, and the
@Transactionaldecorator on writing methods ensure atomicity across the two tables.Nevertheless, you're right that most of the time the decorator finds its usage on the service layer because it is the layer responsible for fulfilling use-cases, orchestrating changes across different models (== tables).
Warning: isolation levels
In case you're familiar with isolation levels and apply them consciously, be aware that the automatic transaction propagation affects them too. If you compose multiple service methods that have the decorator on top but with different isolation levels, the top-level one will be applied, always. This is because in most databases you cannot change the isolation level of a transaction as soon as the first query statement is executed. Note: It can only become an issue if you have an inner method decorated with a stricter isolation level than the top-level one. Let me know if this is not clear and I can provide a deeper explanation. 🙇♂️
Yes, perfect!
Works too!
Btw., you can test atomicity by calling several repository operations from your
updateUsermethod, but before it returns, addthrow new Error(). With a Jest test you can verify that the number of rows in the corresponding tables remained the same before and after the execution (i.e. the tx rolled back everything). 😉myfunc commentedon May 12, 2024
I successfully used that approach with minor changes and fixes in the production project for a site with 2-5k online.
But there are a problems.
Warning: undesired transaction wrapping
In a team of 2+ developers, code is being changed, and there is a case when another developer adds a new prisma query to the service's method that could be executed in the @transactional stack.
For example, I have the method createGame (block 1), which is called by service (block 2).
All seems to be good. But if another developer decides inside of GameService verify that the user isn't blacklisted (just an example).
verifyUserOrThrow method can be implicitly executed inside of a transaction,
That call may execute many queries to $transactions that can lead to deadlocks caused by attempts to read/update locked DB rows.
I wondering how to use that decorator in a safe way.
Currently, I am thinking about an eslint extension that will highlight prisma calls that are inside of possible transactions or another way to make nested queries forbidden with no special decorator or method's call.
myfunc commentedon Jun 10, 2024
I decided to publish my solution with "@PrismaTransactional" decorator that contains a code from the thread shared by @fuvidani.
Thank you!
That decorator is actively used on production with no issues, but I don't recomment to use it without understanding what happens under the good.
Feel free to try, leave feedback or contribute.
https://github.com/myfunc/prisma-transactional
guipfernandes commentedon Mar 31, 2025
Hey guys, putting my two cents in this topic, here is my current working implementation using NestJS. I used as a reference other implementations mentioned here and in other issues, thanks everyone!
My solution involves
The interface
The implementation
Prisma service
The usage
Repository
Service