Skip to content

Prisma connection doesn't recover from idle in transaction state #9584

Closed

Description

@avallete

Bug description

Hi there,

As the title mention it, I encountered a bug when using both interactives and non-interactives transactions with prisma.

Sometimes, the prisma client get stuck into a 'idle in transaction' mode, this mainly happens under loads (eg: truncate all tables in a database) when postgres is allowed little ressources (eg: in CI, 1 CPU for postgres container).

From my preliminary investigation:

  1. This bug is random and ressources related (with 4 CPU allowed to postgres it doesn't appears), with less query load it doesn't appears. And when it does, it doesn't appears at the same point.
  2. It seems to be postgres "lock" related. For us, this show up during our "integrations testing" in which we truncate all the tables, then seed them with controlled data. Sometimes it's one of the "flush" (TRUNCATE) query who get stuck in the 'idle in transaction' mode, sometimes it's one of the "seed" (INSERT INTO). The common denominator seems to be the fact that some locks aren't unlocked by postgres.

The main issue is that, once it get into this state, the prisma client never get out of it. In our case, requiring to restart the webserver to instantiate a new connection to the database.

It's not very clear for me how to make a MRE from my issue since it's heavily related our code and only appears under loads.

How to reproduce

Here is a MRE reproducing this issue: https://github.com/avallete/prisma-9584-MRE

Expected behavior

Prisma could throw a "transaction timeout" error after X seconds passed in a transaction which doesn't end.

Prisma information

nothing specific

Environment & setup

  • OS: OSX/Debian
  • Database: postgres:12
  • Node.js version: v14.17.1

Prisma Version

prisma                : 2.30.3
@prisma/client        : 2.30.3
Current platform      : darwin
Query Engine (Binary) : query-engine b8c35d44de987a9691890b3ddf3e2e7effb9bf20 (at ../../node_modules/@prisma/engines/query-engine-darwin)
Migration Engine      : migration-engine-cli b8c35d44de987a9691890b3ddf3e2e7effb9bf20 (at ../../node_modules/@prisma/engines/migration-engine-darwin)
Introspection Engine  : introspection-core b8c35d44de987a9691890b3ddf3e2e7effb9bf20 (at ../../node_modules/@prisma/engines/introspection-engine-darwin)
Format Binary         : prisma-fmt b8c35d44de987a9691890b3ddf3e2e7effb9bf20 (at ../../node_modules/@prisma/engines/prisma-fmt-darwin)
Default Engines Hash  : b8c35d44de987a9691890b3ddf3e2e7effb9bf20
Studio                : 0.423.0
Preview Features      : interactiveTransactions, nApi, referentialActions

Also tried with the latest 3.X version, the issue is the same.

Activity

  1. added
    kind/bug
    on Oct 4, 2021
  2. awinograd commented on Oct 4, 2021

    @awinograd

    i've been debugging a similar issue with long running transactions the past few days. I think it's likely the same root cause as this report. We wrap our unit tests in database transactions to isolate/reset state between tests. Fairly regularly, our test suite will have several tests fail due to timeouts. After adding logging, it appears the tests get stuck after we throw inside a long running transaction but the $transactions promise never rejects, instead it hangs.

    I wasn't really having much luck debugging the underlying issue, but after seeing this report, I ran select * from pg_stat_activity where state='idle'; in psql. There are idle rows returned consistently with query=ROLLBACK when a test fails due to timeouts and they don't go away until the jest process ends.

  3. avallete commented on Oct 4, 2021

    @avallete
    ContributorAuthor

    i've been debugging a similar issue with long running transactions the past few days. I think it's likely the same root cause as this report. We wrap our unit tests in database transactions to isolate/reset state between tests. Fairly regularly, our test suite will have several tests fail due to timeouts. After adding logging, it appears the tests get stuck after we throw inside a long running transaction but the $transactions promise never rejects, instead it hangs.

    I wasn't really having much luck debugging the underlying issue, but after seeing this report, I ran select * from pg_stat_activity where state='idle'; in psql. There are idle rows returned consistently with query=ROLLBACK when a test fails due to timeouts and they don't go away until the jest process ends.

    I'm using "pgAdmin" to monitor both ressources usages / numbers of locks / opened sessions on my DB. And I have quite the same result.

    However, I did try to extract that from jest environment by only running "lock intensives" operations in an infinite loop (no tests, only running code). And after a while ~(120 iterations but it's random between the run 90-150), the same error show up. Basically, one of the transaction take some locks on the database, then, the session get stuck into an "idle in transaction" infinite hanging state, prisma doesn't throw an error, the session is never killed (blocking all subsequents queries who may need the locks acquired).

    Here is the pseudo code I run in the loop:

    async function flush() {
        const results = await prisma.$executeRaw(SELECT_ALL_DB_TABLES_QUERY);
        await prisma.$transaction(results.map((result) => prisma.$executeRaw(`TRUNCATE TABLE ${result.table_name} CASCADE`)));
    }
    
    async function seed() {
        const insert_intos = await readfile("./myseed.sql");
        await prisma.$transaction(insert_intos.map((sql) => prisma.$executeRaw(sql)));
    }
    
    async function main() {
       while (true) {
           await flush();
           await seed();
       }
    }

    I'm actually trying to create a MRE on another repo re-using this concept to be able to investigate further on this outside my application specific context.

    ATM the only mitigation I found is to refactor the prisma.$transaction, into a for of + await loop. I do loose both the rollback ability and transaction/database integrity. But it does allow my code not to hang forever.

  4. avallete commented on Oct 5, 2021

    @avallete
    ContributorAuthor

    Possibly related: #8707

    Edit:

    I've created a MRE here: https://github.com/avallete/prisma-9584-MRE

    To facilitate investigations.

  5. ssukienn commented on Nov 3, 2021

    @ssukienn

    Hi. I will add my bits to it.

    I am facing a similar problem in MySql 8. This works locally (or at least I didn't encounter the problem yet) on 4-core 32GB device but hangs (promise do not return) in i.e. preemptible GCE server with 1 core and low amount of RAM.
    Seems like the database is not locked afterwards just the Prisma promise does not return, nor throw/rejects.

    In my scenario that prevents ack'ing broker messages at some point which creates the service unresponsive (15 is its prefetch/concurrent limit):
    image

    Code:

       //called by message broker consumer for each message
        async saveMessage(input: MessageWithoutOrderInput, order?: number) {
            const uuid = randomUUID();
            const promise = this._prismaSaveMessage([input], order, uuid);
    
            const interval = this.checkForPending(promise, uuid);
            intervals.set(uuid, interval);
    
            const debug = (await promise)[0];
            this.logger.debug(debug);
            return debug;
        }
        
        //for logging pending promises
        private checkForPending(promise: Promise<any>, uuid: string) {
            return setInterval(() => {
                const isPending = util.inspect(promise) === 'Promise { <pending> }';
                this.logger.debug(`isPending: ${isPending}`, uuid);
                if (!isPending) {
                    intervals.get(uuid)();
                }
            }, 2000);
        }
    
        private _prismaSaveMessage(inputArray: MessageWithoutOrderInput[], explicitOrder?: number) {
            return this.db.$transaction(async (prisma) => {
                let lastMessageOrder =
                    explicitOrder ||
                    ((
                        await prisma.assistantMessage.aggregate(...)
                    )._max.order || 0) + 1;
    
                return Promise.all(
                    inputArray.map((input) => {
                        return prisma.assistantMessage.upsert({
                            where: { uuid: input.uuid || '' },
                            create: {
                                ...input,
                                order: lastMessageOrder++,
                            },
                            update: input,
                        });
                    }),
                );
            });
        }

    output: 15 lines of pending promise output each 2 seconds indefinitely

    Changing from interactive to array-based transaction method does not change the outcome.

    Creating my own timeout over this to prevent it, seems like overkill and it should be rather taken care of by the framework. It would not fix the problem though just prevent zombie service.

    Prisma:

    prisma : 3.3.0
    @prisma/client : 3.3.0
    Current platform : debian-openssl-1.1.x
    Query Engine (Node-API) : libquery-engine 33838b0f78f1fe9052cf9a00e9761c9dc097a63c (at node_modules/prisma/node_modules/@prisma/engines/libquery_engine-debian-openssl-1.1.x.so.node)
    Migration Engine : migration-engine-cli 33838b0f78f1fe9052cf9a00e9761c9dc097a63c (at node_modules/prisma/node_modules/@prisma/engines/migration-engine-debian-openssl-1.1.x)
    Introspection Engine : introspection-core 33838b0f78f1fe9052cf9a00e9761c9dc097a63c (at node_modules/prisma/node_modules/@prisma/engines/introspection-engine-debian-openssl-1.1.x)
    Format Binary : prisma-fmt 33838b0f78f1fe9052cf9a00e9761c9dc097a63c (at node_modules/prisma/node_modules/@prisma/engines/prisma-fmt-debian-openssl-1.1.x)
    Default Engines Hash : 33838b0f78f1fe9052cf9a00e9761c9dc097a63c
    Studio : 0.437.0
    Preview Features : interactiveTransactions

  6. added
    bug/0-unknown
    bug/1-unconfirmed
    and removed
    bug/0-unknown
    on Nov 4, 2021
  7. janpio commented on Nov 5, 2021

    @janpio
    Contributor

    Thanks for the reproduction @avallete - this will make it much easier for us to observe what is going on here.

  8. garrensmith commented on Feb 2, 2022

    @garrensmith
    Contributor

    With the release of 3.9.0 we have reworked interactive transactions and it should solve this issue. Could you test with the latest version.

    I'm going to close this ticket and we can reopen if the issue is not resolved.

  9. janpio commented on Feb 9, 2022

    @janpio
    Contributor

    Ping @awinograd @avallete @ssukienn - could you please have a look? Thanks.

  10. avallete commented on Feb 9, 2022

    @avallete
    ContributorAuthor

    @janpio Just tried to upgrade on my MRE, and it seems indeed that the "hanging forever" issue is resolved, I now see this as an error, then Prisma properly recover and continue my script:

    ...
    app_1       | iteration number: 751
    app_1       | an error:  {
    app_1       |   is_panic: false,
    app_1       |   message: 'Transaction API error: Unable to start a transaction in the given time.',
    app_1       |   meta: { error: 'Unable to start a transaction in the given time.' },
    app_1       |   error_code: 'P2028'
    app_1       | }
    

    However, the "timeout" time of the transaction lock doesn't seem to be affected by this command on postgresql:
    SET idle_in_transaction_session_timeout TO XXX

    IDK if it's expected behavior and that we have to configure the "timeout time" elsewhere instead.

    Anyway, thank's everyone for your work and the time you spent on this issue!

  11. awinograd commented on Feb 9, 2022

    @awinograd

    @janpio The issue in my MRE is resolved as of 3.9.x! Thanks

  12. adri1wald commented on Sep 3, 2023

    @adri1wald

    We had a similar issue occur in our production system just today. getting Unable to start a transaction in the given time errors on all prisma queries and which could only be recovered by restarting the affected instance. @janpio

  13. janpio commented on Sep 5, 2023

    @janpio
    Contributor

    Please don't comment on two year old issues, but open a new one and supply all the information it asks for - optimally including a reproduction of your problem. Then we can better help you. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug/1-unconfirmedkind/bugstatus/needs-repro-confirmationtopic: interactiveTransactionstopic: transaction

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions