Repository navigation
Description
Bug description
When an interactive transaction's maxWait expires while adapter.startTransaction() is still in flight, the client-engine TransactionManager discards the late-arriving transaction with a bare tx.rollback(). For usePhantomQuery: false adapters (@prisma/adapter-pg, @prisma/adapter-neon), rollback() sends no SQL — it only releases the client back to the pool — while BEGIN has already been executed on the wire. The pooled connection therefore re-enters pg.Pool inside an open transaction.
Consequences on the next checkouts of that connection:
- Postgres logs
WARNING: there is already a transaction in progresswhen the next transaction BEGINs on it. - The next
COMMITon that connection commits the leaked transaction's work along with its own (atomicity violation), or — if the leaked transaction had errored — every subsequent statement fails with25P02 current transaction is aborteduntil something sends ROLLBACK/COMMIT. - Until reuse,
pg_stat_activityshows the backendidle in transactionwithquery = 'BEGIN'.
We hit this in production (Prisma 7.8.0, Next.js, node-postgres): host CPU-stall episodes froze the event loop past maxWait (default 2000 ms), producing exactly this triad — client-side P2028 Unable to start a transaction in the given time, an idle in transaction backend stuck on BEGIN, the postgres warning on reuse, and one real casualty: an INSERT that ran inside a leaked aborted transaction and failed with 25P02. Note the trigger doesn't require a stall: pool exhaustion alone (all slots busy for longer than maxWait, so pool.connect() resolves late) takes the same code path.
Where it happens
packages/client-engine-runtime/src/transaction-manager/transaction-manager.ts (7.8.0), #startTransactionImpl:
const startTransactionPromise = this.driverAdapter
.startTransaction(options.isolationLevel)
.catch(rethrowAsUserFacing)
transaction.transaction = await Promise.race([
startTransactionPromise.finally(() => clearTimeout(startTimer)),
once(abortController.signal, 'abort').then(() => undefined),
])
...
if (abortController.signal.aborted) {
// The startTransaction promise may still be running in the background.
// If it eventually succeeds, we need to release the connection to avoid
// leaking it and exhausting the connection pool. ...
void startTransactionPromise
.then((tx) => tx.rollback()) // <-- releases WITHOUT sending ROLLBACK
.catch((e) => debug('error in discarded transaction:', e))
await this.#closeTransaction(transaction, 'timed_out') // transaction.transaction === undefined, sends nothing
throw new TransactionStartTimeoutError()
}The manager's own #closeTransaction knows the contract for usePhantomQuery: false adapters — it sends the explicit ROLLBACK query and only then calls tx.rollback():
} else if (tx.transaction) {
if (tx.transaction.options.usePhantomQuery) {
...
} else {
const query = ROLLBACK_QUERY()
try {
await this.#withQuerySpanAndEvent(query, tx.transaction, () => tx.transaction!.executeRaw(query))
} finally {
await tx.transaction.rollback()
}
}
}…but the discard path above skips that and calls rollback() bare. And @prisma/adapter-pg's PgTransaction.rollback() (packages/adapter-pg/src/pg.ts, 7.8.0) is a pure resource release:
async rollback(): Promise<void> {
debug(`[js::rollback]`)
this.cleanup?.()
this.client.release() // no ROLLBACK statement; BEGIN already ran in startTransaction()
}client.release() with no error argument returns the client to pg-pool's idle list with no session reset — mid-transaction.
The existing unit test encodes the bug: transaction-manager.test.ts ("transaction start timeout cleans up connection if transaction eventually starts") builds a usePhantomQuery: false mock but asserts only expect(rollbackMock).toHaveBeenCalled() — it never asserts that a ROLLBACK statement was executed on the discarded transaction.
History
- 7.1.0 (fix(client-engine-runtime): abort transaction on
maxWaittimeout #28723) introduced the prompt maxWait abort; the raced-away promise had no continuation at all (connection never released — pool exhaustion). - 7.2.0 (fix: don't leak connections in timed out transactions #28831, "don't leak connections in timed out transactions") added
.then((tx) => tx.rollback()), fixing the pool-slot leak but introducing this release-without-ROLLBACK corruption forusePhantomQuery: falseadapters. - Affected: 7.2.0 → 7.8.0 inclusive;
transaction-manager.tsandadapter-pg/src/pg.tsare unchanged onmainas of 2026-07-13. - Likely the mechanism behind at least some reports in Spike in
Unable to start a transaction in the given time.for newprisma-client#27990 (P2028 spikes on the new client engine). - The stalled refactor fix(client-engine-runtime): cancel transactions that are still starting #28768 (abortable
startTransaction) would structurally fix this; fix(client-engine-runtime): handle rejections when timeout expires after backend termination #29611 touches the adjacent execution-timeout rollback path.
How to reproduce
Deterministic, no database needed — an in-memory pg.Pool subclass stands in for the server and records what happens to the connection (a real Postgres shows the same thing, just less deterministically; hold the event loop or saturate the pool instead of gating BEGIN):
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '@prisma/client' // any generated client with a postgresql datasource
import { EventEmitter } from 'node:events'
import { Pool } from 'pg'
const emptyResult = (command: string) => ({ rows: [], fields: [], rowCount: 0, command })
class FakeClient extends EventEmitter {
sql: string[] = []
inTx = false
beginWhileInTx = 0
releasedInTx = 0
holdBegin: Promise<void> | null = null
query(cfg: any): Promise<any> {
const text: string = typeof cfg === 'string' ? cfg : (cfg.text ?? '')
this.sql.push(text)
const kw = text.trim().split(/\s+/)[0]?.toUpperCase()
const settle = () => {
if (kw === 'BEGIN') {
if (this.inTx) this.beginWhileInTx++ // = postgres "already a transaction in progress"
this.inTx = true
} else if (kw === 'COMMIT' || (kw === 'ROLLBACK' && !/^ROLLBACK\s+TO/i.test(text))) this.inTx = false
return emptyResult(kw)
}
if (kw === 'BEGIN' && this.holdBegin) {
const gate = this.holdBegin
this.holdBegin = null
return gate.then(settle)
}
return Promise.resolve().then(settle)
}
release(err?: Error | boolean) {
if (this.inTx) this.releasedInTx++
if (!err) pool.free.push(this) // reuse, like pg-pool's idle list
}
}
class FakePool extends Pool {
clients: FakeClient[] = []
free: FakeClient[] = []
nextHold: Promise<void> | null = null
override connect(): Promise<any> {
const c = this.free.pop() ?? (this.clients.push(new FakeClient()), this.clients.at(-1)!)
if (this.nextHold) { c.holdBegin = this.nextHold; this.nextHold = null }
return Promise.resolve(c)
}
}
const pool = new FakePool()
const prisma = new PrismaClient({ adapter: new PrismaPg(pool) })
let thaw!: () => void
pool.nextHold = new Promise<void>((r) => (thaw = r)) // BEGIN reply delayed past maxWait — like an event-loop stall / slow server
await prisma.$transaction(async () => {}, { maxWait: 100, timeout: 2000 }).catch((e) => console.log(e.code)) // P2028
thaw() // the stall ends; TransactionManager's discard cleanup runs now
await new Promise((r) => setTimeout(r, 50))
const c = pool.clients[0]
console.log('SQL sent:', c.sql) // [ 'BEGIN' ] — no ROLLBACK, ever
console.log('released in-tx:', c.releasedInTx) // 1 — pool got a mid-transaction connection
await prisma.$transaction(async () => {}, { maxWait: 1000, timeout: 2000 }) // reuses the connection
console.log('BEGIN on in-tx conn:', c.beginWhileInTx) // 1 — the postgres WARNING; this COMMIT adopts the leaked txObserved output with @prisma/client / @prisma/adapter-pg 7.8.0:
P2028
SQL sent: [ 'BEGIN' ]
released in-tx: 1
BEGIN on in-tx conn: 1
Expected behavior
The discarded-start path should honor the same contract as #closeTransaction: for usePhantomQuery: false adapters, execute ROLLBACK on the transaction before rollback() releases the connection, e.g.
void startTransactionPromise
.then((tx) =>
tx.options.usePhantomQuery
? tx.rollback()
: tx.executeRaw(ROLLBACK_QUERY()).finally(() => tx.rollback()),
)
.catch((e) => debug('error in discarded transaction:', e))(or give adapters a dispose-with-rollback primitive / land #28768). A connection must never re-enter the pool with an open transaction: the current behavior silently merges unrelated queries into a stale transaction, which is data-corruption grade, not just noise.
Prisma information
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
}const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
// any interactive transaction whose start outlives maxWait:
await prisma.$transaction(async (tx) => { ... }) // default maxWait 2000msEnvironment & setup
- OS: Linux (Ubuntu 22.04 VM, prod) / Windows 11 (repro)
- Database: PostgreSQL 16 (mechanism is server-version-independent; also shown with the fake pool above)
- Node.js version: v20.x (prod), v24.16 (repro)
- pg: 8.13.x
Prisma version
prisma : 7.8.0
@prisma/client : 7.8.0
@prisma/adapter-pg: 7.8.0
Also applies to @prisma/adapter-neon (same release-only rollback(), usePhantomQuery: false). 7.1.0 has the older never-released variant of the leak; ≤ 7.0.x waited for startTransaction to finish and closed via the full path, so it is not affected this way.
Activity
fix(client-engine-runtime): send ROLLBACK when discarding a timed-out…
fix(client-engine-runtime): send ROLLBACK when discarding a timed-out…