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
Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired' P2028 #13713
{"is_panic":false,"message":"Transaction API error: Transaction already closed: Transaction is no longer valid. Last state: 'Expired'.","meta":{"error":"Transaction already closed: Transaction is no longer valid. Last state: 'Expired'."},"error_code":"P2028","clientVersion":"3.14.0"}
This error is causing me a lot of trouble, I'm happy to try to get more information. Is there anything I can do to get some more useful data for debugging it? Would really like to get this resolved one way or another.
I wonder if this could be related. Could prisma be keeping the transaction open when this error is triggered? I don't know why there are so many processes idle in transaction.
Yes this bug keeps troubling and blocks the development. Have tried killing idle processes, disconnecting all open connections, stopping database server but nothing works. Somehow it finds that some transaction was not closed properly.
This issue was closed with #9584 in version 3.9
I have version 3.14 but the issue still exists.
Reacted by Nils Lundquist, Esdras Amora, Chuya Guo, Abdulrahman Elheyb, Jacob Goh Chuan Ching, David Mello and hijikix
Ran into this issue today as well – turns out the fix was to convert my arr.forEach(...) loop into a good old for (let i = 0; i < arr.length; i++) and everything worked like a charm!
Why does this work? Man I've been breaking my head about this issue, it's also only an issue on a Windows machine, on my mac it's working fine using for...of
For anyone trying add a LOT of data (for example, during seeding, more than 10,000 rows, Prisma will still timeout even with Promise.all)
In that case, you can split up the data into chunks of transactions
✅ Works under 500ms to add over 10k rows..
constchunkSize=100;// I found 100 to work the fastestconstchunks=[];for(leti=0;i<seed_data.length;i+=chunkSize){chunks.push(seed_data.slice(i,i+chunkSize));}awaitPromise.all(chunks.map(async(chunk)=>{awaitdb.$transaction(async(tx)=>{awaitPromise.all(chunk.map((chunkData)=>{returntx.YOUR_TABLE_HERE.create({data: chunkData,});}),);});}),);
I actually suspect the issue could be that people are running async calls in parallel with both of them updating the database at some point in their call cycle. A suspicion I have for why I see this issue is that I am using Promise.all([doAction1, doAction2]) and at some point action1 is timing out but action2 has not yet operated on the database. When it attempts to then operate on the database it tries to use the same transaction as action1 but action1 closed that transaction after it hit the timeout error.
@raymondKelly I was having the same error as you where i had two actions within a Promise.all(). I ended up making the two actions sequential and the problem was fixed.
This is an old comment but I'll respond since the issue surfaced again in my notifications and I don't believe there was an explicit explanation to this specific problem given in this thread before:
@erdinc: after reading provided solutions and comments, I didn't understand why it works with good old for loop but not with Array.forEach or Array.map and also some people mentioned that using Promise.all solved the issue for their use cases. Can someone clarify the reason and work around for that case? it will be nice for people coming afterwards.
Because Array.prototype.forEach accepts a regular function, not an async function. If you provide an async function as an argument, it will execute it as a normal function without awaiting, which will spawn it concurrently.
// DO NOT DO THISdeal.activities.forEach(async(activity)=>{constdealActivity=awaittx.crmDealActivity.create()// ...}
is just plainly wrong and doesn't do what you think it does. The transaction callback will finish and commit the transaction before the operations have a chance to execute. You need to await the operations inside the transaction callback and not outside of it.
In other words, if you really want sequential execution, you should use the for ... of loop:
Don't forget await before Promise.all or you will ultimately run into the same issue as with forEach.
When querying databases, accessing network or doing any other kind of I/O, you definitely want concurrent execution when you don't have dependencies between the operations, especially in the context of interactive transactions, where sequential execution can lead to timeouts.
A naive Promise.all might be an oversimplification in general case: if you have a lot of items to process, you should also take care to handle backpressure appropriately and consider throttling the maximum number of concurrent tasks in-flight. But for most use cases involving interactive transactions in Prisma, a simple Promise.all should be just fine (remember that interactive transactions must be as small and quick as possible).
In contrast, using forEach with async functions is almost always a bug in your code, except a specific use case where the following four conditions are true:
You want to spawn concurrent tasks
You don't care about their results
You don't care when they will finish
They can never throw an error (as otherwise you won't be able to catch it and it will crash your application)
It is unfortunately accepted by TypeScript (as functions returning whatever are assignable to the functions returning void as long as the parameters match) but you can set up ESLint to reject code like this.
This is not specific to Prisma or transactions in Prisma in any way, this is just how JavaScript works.
Reacted by ayadav42, Keng Ye, Skylar Bolton, Owen Haiber, Ben Kirby, maaz and Meng Xu
Ran into this issue today as well – turns out the fix was to convert my arr.forEach(...) loop into a good old for (let i = 0; i < arr.length; i++) and everything worked like a charm!
Ran into this issue today as well – turns out the fix was to convert my arr.forEach(...) loop into a good old for (let i = 0; i < arr.length; i++) and everything worked like a charm!
Thank you. This saved the day for me.
Just to add some more context - I faced this in prod and not in dev, where I was connecting to the prod DB from my local box for a migration, so network latency was definitely higher.
When dealing with promises, the behavior of for, map(), and forEach() loops differ significantly due to how they handle asynchronous operations:
1. for Loop
Synchronous Execution: The for loop handles asynchronous code more flexibly because you can use async/await directly within the loop.
Sequential Execution: When using await inside a for loop, each iteration waits for the promise to resolve before moving to the next one, enabling sequential execution of asynchronous tasks.
Example:
for(constitemofitems){awaitdoSomethingAsync(item);// Runs one by one}
2. map()
Creates an Array of Promises: When using map() with an asynchronous function, it does not wait for each promise to resolve. Instead, it immediately returns an array of promises.
Use with Promise.all(): If you want to run all the promises concurrently and wait for all of them to complete, you typically wrap it in Promise.all().
No await Handling: The forEach() method doesn’t work with await directly. If you try to use await inside forEach(), it won’t pause the loop execution, and all iterations will start their asynchronous operations almost simultaneously.
Less Control: Because it doesn’t handle await, it’s generally not suitable for controlling the flow of asynchronous tasks.
Example:
items.forEach(async(item)=>{awaitdoSomethingAsync(item);// Won't wait for each iteration});
Summary
Use for for sequential, controlled execution.
Use map() with Promise.all() for concurrent execution.
Avoid forEach() with promises, as it doesn't handle await properly.
Reacted by Martin Adams, Juan Navas and Harry Baines
Activity
Abdulrahmanelheyb commentedon Jun 10, 2022
I get the same error. Any resolve ?
revmischa commentedon Jun 11, 2022
This error is causing me a lot of trouble, I'm happy to try to get more information. Is there anything I can do to get some more useful data for debugging it? Would really like to get this resolved one way or another.
Abdulrahmanelheyb commentedon Jun 13, 2022
I tried add max options is work fine and I changing the value based on NODE_ENV
revmischa commentedon Jun 17, 2022
I wonder if this could be related. Could prisma be keeping the transaction open when this error is triggered? I don't know why there are so many processes idle in transaction.
manojmpc91 commentedon Jun 30, 2022
Yes this bug keeps troubling and blocks the development. Have tried killing idle processes, disconnecting all open connections, stopping database server but nothing works. Somehow it finds that some transaction was not closed properly.
This issue was closed with #9584 in version 3.9
I have version 3.14 but the issue still exists.
cesarvspr commentedon Aug 10, 2022
Still exists on 4.0.0
52 remaining items
notflip commentedon Jun 23, 2023
Why does this work? Man I've been breaking my head about this issue, it's also only an issue on a Windows machine, on my mac it's working fine using for...of
shadoath commentedon Aug 13, 2023
I also found that this error would come up when I had a transaction that called an awaited promise to Prisma that was NOT using the transaction.
m1212e commentedon Sep 6, 2023
In my case this error appeared because I fired but did not await a promise from inside the async transaction callback
Eh-haque commentedon Sep 7, 2023
c-andrey commentedon Oct 9, 2023
I solved using tthe promise.all as @Eh-haque commented above
matthewjerome commentedon Nov 28, 2023
ran into the same issue - if you need to run transactions inside a loop, consider using a generator function.
avarayr commentedon Feb 8, 2024
For anyone trying add a LOT of data (for example, during seeding, more than 10,000 rows, Prisma will still timeout even with Promise.all)
In that case, you can split up the data into chunks of transactions
✅ Works under 500ms to add over 10k rows..
raymondKelly commentedon May 2, 2024
I actually suspect the issue could be that people are running async calls in parallel with both of them updating the database at some point in their call cycle. A suspicion I have for why I see this issue is that I am using Promise.all([doAction1, doAction2]) and at some point action1 is timing out but action2 has not yet operated on the database. When it attempts to then operate on the database it tries to use the same transaction as action1 but action1 closed that transaction after it hit the timeout error.
RahulBirCodes commentedon May 17, 2024
@raymondKelly I was having the same error as you where i had two actions within a Promise.all(). I ended up making the two actions sequential and the problem was fixed.
aqrln commentedon Jun 11, 2024
This is an old comment but I'll respond since the issue surfaced again in my notifications and I don't believe there was an explicit explanation to this specific problem given in this thread before:
Because
Array.prototype.forEachaccepts a regular function, not an async function. If you provide an async function as an argument, it will execute it as a normal function without awaiting, which will spawn it concurrently.Code like this in one of the comments above (by @patriciorasquetti):
is just plainly wrong and doesn't do what you think it does. The transaction callback will finish and commit the transaction before the operations have a chance to execute. You need to await the operations inside the transaction callback and not outside of it.
In other words, if you really want sequential execution, you should use the
for ... ofloop:and if you want concurrent execution (better), you should use
Promise.all:Don't forget
awaitbeforePromise.allor you will ultimately run into the same issue as withforEach.When querying databases, accessing network or doing any other kind of I/O, you definitely want concurrent execution when you don't have dependencies between the operations, especially in the context of interactive transactions, where sequential execution can lead to timeouts.
A naive
Promise.allmight be an oversimplification in general case: if you have a lot of items to process, you should also take care to handle backpressure appropriately and consider throttling the maximum number of concurrent tasks in-flight. But for most use cases involving interactive transactions in Prisma, a simplePromise.allshould be just fine (remember that interactive transactions must be as small and quick as possible).In contrast, using
forEachwith async functions is almost always a bug in your code, except a specific use case where the following four conditions are true:It is unfortunately accepted by TypeScript (as functions returning whatever are assignable to the functions returning
voidas long as the parameters match) but you can set up ESLint to reject code like this.This is not specific to Prisma or transactions in Prisma in any way, this is just how JavaScript works.
patriciorasquetti commentedon Jun 11, 2024
Alexey answer is correct (Promise.all) , I was implementing it wrong at that time and fixed last year.
Regards.
talonx commentedon Jul 3, 2024
Thank you. This saved the day for me.
talonx commentedon Jul 3, 2024
Just to add some more context - I faced this in prod and not in dev, where I was connecting to the prod DB from my local box for a migration, so network latency was definitely higher.
shadoath commentedon Sep 25, 2024
When dealing with promises, the behavior of
for,map(), andforEach()loops differ significantly due to how they handle asynchronous operations:1.
forLoopforloop handles asynchronous code more flexibly because you can useasync/awaitdirectly within the loop.awaitinside aforloop, each iteration waits for the promise to resolve before moving to the next one, enabling sequential execution of asynchronous tasks.Example:
2.
map()map()with an asynchronous function, it does not wait for each promise to resolve. Instead, it immediately returns an array of promises.Promise.all(): If you want to run all the promises concurrently and wait for all of them to complete, you typically wrap it inPromise.all().Example:
3.
forEach()awaitHandling: TheforEach()method doesn’t work withawaitdirectly. If you try to useawaitinsideforEach(), it won’t pause the loop execution, and all iterations will start their asynchronous operations almost simultaneously.await, it’s generally not suitable for controlling the flow of asynchronous tasks.Example:
Summary
forfor sequential, controlled execution.map()withPromise.all()for concurrent execution.forEach()with promises, as it doesn't handleawaitproperly.