Skip to content

Support "nested" transactions in interactive transactions #15212

Open

Description

@aniravi24

Problem

Handle nested transaction blocks in an interactive transaction (or in transactions in general). This allows for writing transactions in a more composable manner without having to think about it all the time, but at the risk of allowing too much nesting.

Suggested solution

I'm not sure what the best solution would be, but here are some examples of how this is implemented in other libraries as well as tools in other languages.

  1. Ecto. Another article about Ecto (Ecto, Elixir's ORM collapses transactions into a single transaction, I think they use SAVEPOINTS).
  2. Ecto's Multi is a supercharged version of Prisma's interactive transactions API, allowing you to cleanly write database interactions almost like a workflow, and these can be nested too. If you're familiar with monads from functional programming, Multi's are like a database transaction monad.
  3. pg-promise transactions
  4. Sequelize transactions / https://sequelize.org/docs/v6/other-topics/transactions/

Alternatives

The alternative is to not nest transactions, but I'm not sure if that's the best alternative.

Additional context

Initially suggested here

Activity

  1. yasaichi commented on Oct 30, 2022

    @yasaichi

    This feature is just what I want! I expect it to be written and work as follows:

    prisma.transaction(async (t1) => {
      await t1.transaction(async (t2) => {
        ...
      });
    });
    BEGIN; # t1
    SAVEPOINT t2; # t2
    ...
    RELEASE SAVEPOINT t2; # or `ROLLBACK TO SAVEPOINT t2;` if the inner async function is rejected.
    COMMIT;
  2. MichaelrMentele commented on Dec 11, 2022

    @MichaelrMentele

    It's very confusing how prisma handles nested transactions and leads to surprising and non-obvious bugs. A transaction should be able to exist in a transaction -- at a minimum you could gracefully handle nested calls. Its unacceptable that it doesn't in my view. In any robust ORM I've ever used i.e. ActiveRecord, psycopg -- I don't have these issues.

    It's important because you don't always know what the code you are calling is going to do and it should "behave". IIUC right now if you have a transaction in a transaction it will close the containing transaction because you just redefined it.

    Personally I don't want to have to pass a transaction around. I'd rather not have to think about it like:
    image

    Or:
    https://www.psycopg.org/psycopg3/docs/basic/transactions.html#nested-transactions

  3. qsona commented on Mar 25, 2023

    @qsona

    Hello! I'm a big fan of prisma.

    I really hope that the issue will be resolved. I believe that nested transactions are important not only in production code but also in test code.

    RSpec (testing framework in Ruby) has a feature called "transactional fixtures" which rolls back the database state after each test suite is completed.
    A Prisma version of this feature is available at https://github.com/Quramy/jest-prisma. It follows the same approach as RSpec by starting a transaction before the test begins and rolling it back after it ends.
    However, this approach has its limitations, I mean, if transactions are applied in actual code, it causes errors. Therefore, nested transactions are necessary to achieve this.

    Do you have any plans to develop this feature in the near future? Thank you.

  4. YutaUra commented on May 31, 2023

    @YutaUra

    Hi @qsona . Transaction rollback feature released in @quramy/jest-prisma

    You can try it if you want!

    see Quramy/jest-prisma#88

  5. janpio commented on Oct 28, 2023

    @janpio
    Contributor

    Duplicate / related: #19346

  6. codepunkt commented on Dec 14, 2023

    @codepunkt

    @YutaUra Transaction rollback feature of @quramy/jest-prisma does not work with MySQL as MySQL doesn't allow sending SAVEPOINT queries as prepared statements and everything prisma allows is sending exactly those.

  7. janpio commented on Feb 16, 2024

    @janpio
    Contributor

    Thanks for mentioning that, interesting information when we tackle that. The open community PR at https://github.com/prisma/prisma-engines/pull/4375/files#diff-c5e77351c247c1ac7308813370f9cb540e917f529bafd63612c85fd0ed2d7bb3R304 seems to tackle that in some way, but of course that might also just be misleading - we currently unfortunately do not have the capacity to look into that.

  8. aseemk commented on Mar 14, 2024

    @aseemk

    (I'm aware there are duplicate issues here, but not sure which one(s) the Prisma team is paying most attention to, so sharing this comment I wrote in another issue too. Apologies if that's not what I should do!)

    Strong +1. Just hit & discovered this limitation, and it's a major bummer. Hard to have modular application code (e.g. helper functions that can do things atomically, creating and committing their own transactions to do so) and decouple higher-level transactions from lower-level ones.

    Besides the testing use case, another use case for higher-level transactions is for robust idempotency across your whole application. Brandur Leach describes this technique really well in this article:

    https://brandur.org/idempotency-keys

    And ironically, I was thinking of going this way in part because Prisma also doesn't support SELECT ... FOR UPDATE! (#8580) 😕

    Please consider supporting nested transactions via savepoints. Thank you!

  9. self-assigned this
    on Mar 14, 2024
  10. changed the title [-]Support "Nested" transactions in interactive transactions[/-] [+]Support "nested" transactions in interactive transactions[/+] on Mar 14, 2024
  11. removed their assignment
    on Nov 1, 2024
  12. jrista commented on Aug 22, 2025

    @jrista

    Just wanted to throw my support behind Prisma getting nested transaction support. There are quite often requirements for nesting transactions in even moderately complex systems, where a subset of operations within an existing transaction, must execute atomically as well as with a specific isolation level. Perhaps more than one subset of operations, within an existing higher level transaction. Most databases support nested transactions in one way or another (even MySql, which I think supports them through savepoints).

    I don't know specifically how the implementation would need to be designed, nor the specifics of driver integration, however...intuitively, it would be nice to be able to just do something like this:

    prisma.$transaction(async tx1 => {
        // ...do some initial work...
    
        tx1.$transaction(async tx2 => {
            // to some nested work with a tight isolation level
        }, {
            maxWait: 1000,
            timeout: 2000,
            isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
        });
    
        // ...to more work in original transaction...
    }, {
        maxWait: 5000,
        timeout: 30000,
        isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead,
    });

    Something else that I think goes hand in hand with this: The ability to manage rollback and commit directly. Something I did not realize with Prisma transactions until recently, is that if any exception occurs within a transaction, Prisma rolls it back immediately, before control after the exception even reaches the developer's own code. Even if an error is potentially expected under certain circumstances, because Prisma is in total control over rollback or commit, the user is allowed no option to recover or otherwise handle the error on their own. The transaction aborts instantly and there is no room for alternative handling. Would be nice to have the OPTION, when setting up a transaction, to have control over when rollback and commit occur. Say:

    prisma.$transaction(async tx => {
        try {
            try {
                tx.create(...);
            } catch {
                tx.update(...);
            }
            tx.commit();
        } catch (err) { 
            tx.rollback();    
        }
    }, {
        ownCommitRollback: true,
        isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
    });

    Perhaps support an automatic rollback even, when the dev is owning the commit/rollback process, if tx.commit() (at the very least, or also tx.rollback()) has not been called before the transaction scope terminates, to ensure things remain consistent. Further, if the ownCommitRollback option was not set, then trying to call those methods would result in an exception.

  13. mu-bay1971 commented on Mar 11, 2026

    @mu-bay1971

    Real-world use case: Audit logging in a DORA-regulated fintech SaaS
    We're building a B2B financial advisory platform (NestJS + Prisma + PostgreSQL) that processes sensitive financial and health data (GDPR Art. 9). We're pursuing DORA certification this year, which requires provably atomic audit trails for all data mutations.

    The problem:
    We need to write audit log entries in the same transaction as the mutation that triggers them. With Prisma Client Extensions ($allOperations hook), there is currently no way to access the transaction context of the calling code. The extension always operates on the base client, meaning any auditLog.create() inside the extension runs in a separate transaction — breaking atomicity.

    What we tried:

    • $extends query hook with auditLog.create() → runs on base client, not in the caller's transaction (confirmed bug #17948)
    • PostgreSQL triggers with set_config() for context → works atomically but forces all business logic (customer ID resolution, field diffing, sensitive field hashing) into PL/pgSQL, creating a maintenance nightmare
    • Internal APIs (__internalParams.transaction, _createItxClient) → works but undocumented and may break on any update

    What we ended up building:
    An Outbox Pattern where the extension only collects events in-memory (via AsyncLocalStorage), and a withAudit() wrapper flushes them into an outbox table within the same interactive transaction. A separate async worker then enriches the outbox entries into final audit logs. This works, but it's a significant workaround for what should be a first-class ORM capability.

    What would solve this:
    If the query extension callback received transaction context information (as mentioned in the audit-log-context example: "In a future version of Prisma Client, query extensions will have access to information about whether they are run inside a transaction"), we could write audit entries atomically without any of these workarounds.

    This has been promised since 2023. For regulated industries (fintech, healthtech, insurance), this is not a nice-to-have — it's a certification blocker that forces teams into complex architectural workarounds or away from Prisma entirely.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions