Skip to content

$transaction is not atomic on timeout: a statement can commit after the rollback #29762

Open

Description

@wakfi

Bug description

When a $transaction reaches its timeout, it is not rolled back atomically. A statement whose dispatch is delayed past the timeout is written to the connection after the ROLLBACK the timeout triggers, so it autocommits while other statements in the same transaction are rolled back. The result is a partial commit of a transaction the client reports as failed (P2028): some writes persist and some are rolled back, leaving data in a state the transaction was meant to make impossible.

Severity

🚨 Critical: Data loss/integrity

Reproduction

Minimal, deterministic reproduction: https://github.com/wakfi/prisma-tx-atomicity-repro

git clone https://github.com/wakfi/prisma-tx-atomicity-repro
cd prisma-tx-atomicity-repro
./setup.sh    # starts a throwaway MySQL 8.0 in Docker, installs, generates, runs. Included for convenience, the steps can be run manually if preferred

The table starts empty and the transaction is rolled back, so an atomic implementation must leave it empty. One row survives.

The repro wraps the driver adapter (a supported public API) to delay one statement's dispatch, which makes the race deterministic. The same delay occurs naturally under load: in a separate no-injection test (many concurrent transactions on a small connection pool, no adapter delay), the identical corruption appears in ~10–15% of timed-out transactions, and it disappears entirely when the timeout is generous, confirming the timeout, not concurrency, is the cause.

Expected vs. Actual Behavior

Expected: a transaction that times out is rolled back entirely, all statements or none.

Actual: one statement commits while others in the same transaction are rolled back. The client throws P2028 (reporting the transaction as rolled back), yet a write persists.

Frequency

Consistently reproducible. The minimal repro is deterministic; in production, it is intermittent.

Does this occur in development or production?

Both development and production. The defect is in the runtime client / query engine, so it occurs anywhere the client executes queries.

Is this a regression?

Unverified. Reproduces on every version I tested: 7.8.0, 7.9.0 (latest stable), and 7.10.0-dev.23 (latest dev) — so it is not fixed in any current release or pre-release. I did not test the legacy Rust query-engine client; the affected code (the TypeScript transaction manager in @prisma/client-engine-runtime) is part of the driver-adapter / query-compiler architecture and may not exist in the same form there, so I can't say whether it's a regression. We recently upgraded to Prisma 7 and had not seen this before, so I speculate it's likely a regression introduced in Prisma 7.

Workaround

No reliable workaround. The likelihood is reduced by keeping transactions well under their timeout (fewer statements, lower per-statement latency, less event-loop contention) so no statement's dispatch is delayed past the deadline. Raising timeout reduces but does not eliminate it.

Prisma Schema & Queries

datasource db {
  provider     = "mysql"
  relationMode = "prisma"
}

model Item {
  id Int @id
}
// Empty table. This transaction times out (P2028) and reports itself rolled back,
// but one of the two inserts survives.
await prisma.$transaction(
  [
    prisma.$executeRawUnsafe('INSERT INTO Item VALUES (1)'),
    prisma.$executeRawUnsafe('INSERT INTO Item VALUES (2)'),
  ],
  { timeout: 10 },
)

Full harness (driver-adapter wrapper that induces the delay) is in the linked repo's repro.ts.

Prisma Config

import { defineConfig } from 'prisma/config'

export default defineConfig({
  schema: 'prisma/schema.prisma',
  datasource: { url: process.env.DATABASE_URL },
})

Logs & Debug Info

Server-side statement order on the transaction's connection, captured from the MySQL general log:

BEGIN
Execute   INSERT INTO Item VALUES (1)     -- inside the transaction
ROLLBACK                                   -- timeout fires -> row 1 undone
Execute   INSERT INTO Item VALUES (2)     -- dispatched after ROLLBACK -> autocommits

The timeout's ROLLBACK lands between the two statements. Statement 1 (dispatched before it) is rolled back; statement 2 (dispatched after it) runs with no active transaction and commits. The timeout-triggered rollback is not serialized against statement dispatch on the connection, so a delayed statement can reach the wire after the transaction has already been rolled back.

Environment & Setup

  • OS: macOS (darwin arm64)
  • Database: MySQL 8.0, via @prisma/adapter-mariadb
  • Node.js version: v24.14.1

Prisma Version

prisma               : 7.9.0
@prisma/client       : 7.9.0
Query Compiler       : enabled
Node.js              : v24.14.1
OS / Arch            : darwin / arm64

Also reproduces on 7.8.0 and 7.10.0-dev.23.

Activity

  1. changed the title [-]$transaction is not atomic on timeout: a statement can commit after the rollback (partial commit, P2028)[/-] [+]$transaction is not atomic on timeout: a statement can commit after the rollback[/+] on Jul 23, 2026
  2. added 2 commits that reference this issue on Oct 8, 2026
    4f86d68
    137600e
  3. kensac commented on Oct 9, 2026

    @kensac

    I opened #30650 to fix this.

    The cause: when the transaction times out, a query that's still running keeps sending its remaining statements on the transaction it was given. With adapters like @prisma/adapter-pg, the manager sends ROLLBACK and then releases the connection, so those statements run outside the transaction and each one commits on its own. A nested write is enough to hit it.

    The fix makes TransactionManager.getTransaction return a transaction that refuses statements once it starts closing, with the same error a new query on that transaction already gets (P2028 after a timeout). The guard has to live in the manager, not in rollback(): the manager sends ROLLBACK through executeRaw first, so a guard in rollback() comes too late. That's why #29769 on its own still fails the regression test.

    It includes unit tests and a PostgreSQL functional test that reproduces the leak. Happy to adjust the approach if you'd prefer it done differently.

  4. rnovitskyi commented on Oct 28, 2026

    @rnovitskyi

    Same bug on PostgreSQL with @prisma/adapter-pg, 7.8.0, 7.10.0 and 7.10.1, with no delay injected.

    A single nested create (one parent, ~40 children with their own nested children) takes longer than the interactive transaction timeout under load. The caller gets P2028, but the statements of the query plan after the timeout commit: children without their parent. With the foreign keys in place, the same run fails with P2003 instead, which made it look like Prisma inserted children before parents. That is how we found it: we had dropped foreign keys to "fix" the P2003, and without them the same timeout leaves orphan rows.

    Postgres log (log_line_prefix = '%c %v %x'): after the ROLLBACK, the next INSERT on the same backend runs with a new transaction ID and no BEGIN.

    We patched PgTransaction locally to reject statements after COMMIT/ROLLBACK were sent. That is the same idea as #30650, one layer lower. After it, a timed-out create commits 0 rows (345 without the patch, same test). We would like to drop the patch, so a review of #30650 would help.

  5. ktmouk commented on Nov 13, 2026

    @ktmouk

    We're blocked on upgrading from Prisma 6 to 7 by this issue.
    We independently reproduced it on MySQL 8.0 with @prisma/adapter-mariadb (7.9.1), using the same approach as the linked repro (wrapping the driver adapter to delay one statement). Explicit rollbacks stayed atomic in our tests; only the timeout path leaks writes.
    Since this can leave partially committed data, we can't adopt v7 in production until it's fixed. Could this issue be triaged?

  6. abby-absentify commented on Dec 1, 2026

    @abby-absentify

    Same bug on MySQL 8.4.13 with @prisma/adapter-mariadb 7.10.1 and mariadb 3.5.4, reproduced without wrapping the adapter. A delete whose cascades relationMode = "prisma" emulates runs in an interactive transaction with a 300 ms timeout, while another connection holds a row lock on one of the children. After the timeout's ROLLBACK, the rest of the cascade commits in autocommit:

    model Parent {
      id     String   @id
      first  First[]
      second Second[]
    }
    
    model First {
      id        String @id
      parent_id String
      parent    Parent @relation(fields: [parent_id], references: [id], onDelete: Cascade)
    
      @@index([parent_id])
    }
    
    model Second {
      id        String @id
      parent_id String
      parent    Parent @relation(fields: [parent_id], references: [id], onDelete: Cascade)
    
      @@index([parent_id])
    }
    // Parent p1 with one First (f1) and one Second (s1); another connection locks f1.
    const locker = await createConnection(config);
    await locker.beginTransaction();
    await locker.query("SELECT id FROM `First` WHERE id = 'f1' FOR UPDATE");
    setTimeout(() => locker.rollback(), 1_000);
    
    await prisma.$transaction((tx) => tx.parent.delete({ where: { id: "p1" } }), {
      timeout: 300,
    });
    query: SELECT `Parent`.`id` FROM `Parent` WHERE (`Parent`.`id` = ? AND 1=1) LIMIT ? OFFSET ?
    query: SELECT `First`.`id`, `First`.`parent_id` FROM `First` WHERE (1=1 AND `First`.`parent_id` IN (?))
    query: DELETE FROM `First` WHERE (`First`.`id` IN (?) AND 1=1)
    query: -- Implicit "ROLLBACK" query via underlying driver
    query: SELECT `Second`.`id`, `Second`.`parent_id` FROM `Second` WHERE (1=1 AND `Second`.`parent_id` IN (?))
    query: DELETE FROM `Second` WHERE (`Second`.`id` IN (?) AND 1=1)
    query: DELETE FROM `Parent` WHERE (`Parent`.`id` = ? AND 1=1)
    caller got: P2028 - Transaction API error: A commit cannot be executed on an expired transaction. The timeout for this transaction was 300 ms, however 1010 ms passed since the start of the transaction. ...
    rows left: { parent: 0, first: 1, second: 0 }
    

    A gap in #30650 for @prisma/adapter-mariadb against MySQL. Refusing statements once the transaction starts closing does not cover the statement that is already running. The adapter uses execute() (binary protocol, prepareCacheLength: 0). Against MySQL, mariadb 3.5.4 queues only the PREPARE when execute() is called, and queues the EXECUTE once the PREPARE reply arrives (prepareExecute pipelines both only for MariaDB >= 10.2.4). A ROLLBACK queued during that round trip gives the wire order PREPARE, ROLLBACK, EXECUTE, and the EXECUTE autocommits.

    So "statements sent before closing began still run inside the transaction" does not hold for this adapter. The close also has to wait for statements already handed to the driver before it sends ROLLBACK or COMMIT. We confirmed the ordering from the driver source, and with a fake connection that queues commands the way the driver does against MySQL, driving the real MariaDbTransaction. Without the wait the wire order is BEGIN, PREPARE, ROLLBACK, <release>, EXECUTE; with it, BEGIN, PREPARE, EXECUTE, ROLLBACK, <release>. MySQL 8.4 takes no blocking metadata lock for DML at PREPARE, so we could not hold a PREPARE open against a live server.

    The workaround we run until a fix ships. Each transaction rejects statements once commit() or rollback() is called, and waits for statements already sent before forwarding the close. @prisma/adapter-mariadb uses usePhantomQuery: true, so the transaction manager calls rollback() directly and a guard there is in time. Simplified (ours also guards the savepoint methods and logs the rejected statement):

    import { PrismaMariaDb } from "@prisma/adapter-mariadb";
    
    class GuardedPrismaMariaDb extends PrismaMariaDb {
      override async connect() {
        const adapter = await super.connect();
        const startTransaction = adapter.startTransaction.bind(adapter);
        adapter.startTransaction = async (isolationLevel) => {
          const tx = await startTransaction(isolationLevel);
          const { queryRaw, executeRaw, commit, rollback } = tx;
          const inFlight = new Set<Promise<unknown>>();
          let closed = false;
          const rejectClosed = () =>
            Promise.reject(
              Object.assign(
                new Error("Transaction API error: Transaction already closed"),
                { code: "P2028" }
              )
            );
          const track = <T>(promise: Promise<T>) => {
            inFlight.add(promise);
            const settled = () => inFlight.delete(promise);
            promise.then(settled, settled);
            return promise;
          };
          const close = async (finish: () => Promise<void>) => {
            if (closed) return rejectClosed();
            closed = true;
            await Promise.allSettled([...inFlight]);
            return finish();
          };
          tx.queryRaw = (query) =>
            closed ? rejectClosed() : track(queryRaw.call(tx, query));
          tx.executeRaw = (query) =>
            closed ? rejectClosed() : track(executeRaw.call(tx, query));
          tx.commit = () => close(() => commit.call(tx));
          tx.rollback = () => close(() => rollback.call(tx));
          return tx;
        };
        return adapter;
      }
    }

    With it, the reproduction above keeps all three rows ({ parent: 1, first: 1, second: 1 }) and the caller gets P2028.

  7. salpers commented on Dec 2, 2026

    @salpers

    Same bug on PostgreSQL 16 with @prisma/adapter-pg 7.10.1 in production, with no delay injected. A relation findMany in an interactive transaction (10 s timeout) slowed down under concurrent load. After the timeout's ROLLBACK, the plan's next statement (the relation read) ran on the released connection, outside the transaction.

    We caught it only because our row-level security fails closed. The tenant context is set with set_config(..., is_local => true) inside the transaction, and the policies call a function that raises when it's empty. The stray statement therefore failed with 42501 (surfacing as P2039) instead of quietly reading or writing outside the transaction. If you use transaction-local session settings, a burst of "setting is empty" errors that line up with P2028 timeouts is a cheap way to spot this bug in your logs.

    Deterministic Postgres repro, no adapter wrapping, only a table lock held by a second connection: https://gist.github.com/salpers/3cd8228d1ecc23867c52a8fec56e4331

    Version Caller sees Database afterwards
    7.10.1 P2028 parent update rolled back, child insert committed
    7.11.0-dev.17 P2028 nothing committed

    So #30995 fixes it on pg as well. Two asks:

    1. Could fix(client): a statement can no longer run after its transaction has closed #30995 ship in a release, or be backported to a 7.10.x patch? Until then, every timed-out multi-statement write can partly commit.
    2. Should this issue be closed as fixed by fix(client): a statement can no longer run after its transaction has closed #30995? fix(client-engine-runtime): refuse statements on a transaction once it starts closing #30650 and fix(client): enforce transaction state guard on timeout rollback to guarantee atomicity #29769 are still open against it.

    Until a release, we use the interim guard from the gist (guard.ts, which wraps the adapter factory and refuses statements once COMMIT/ROLLBACK has been sent), in case it helps others stuck on 7.10.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions