In Prisma 7, how does the batch prisma.$transaction([...]) differ from the interactive prisma.$transaction(async (tx) => ...), and when do you need each?
answer
- built before any of it runs
- results come back as a tuple
- a client scoped to the transaction
- throw to roll back
basics
~20 sThe batch form runs an array of un-awaited queries in order inside one transaction, so no query can use another's result. The interactive form hands an async callback a transaction client, tx, for logic between queries; throwing rolls back.
solid answer
~40 s`prisma.$transaction([q1, q2])` takes un-awaited Prisma Client queries, runs them in array order inside one transaction and resolves to a tuple of their results; any failure rolls all of them back. Because every query is built up front, none can depend on another's result. `prisma.$transaction(async (tx) => { ... })` hands you `tx`, a client bound to one open transaction: you can read, branch and write, Prisma commits when the callback resolves and rolls back when it throws, rethrowing your error. Every call inside must go through `tx`; a call on the outer `prisma` runs outside the transaction. Use the batch form for independent writes across models, the interactive form for read-decide-write logic such as a money transfer, and keep the callback short, because it holds a connection until it finishes.
code
typescript · 22 linesimport { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "./generated/prisma/client";
const prisma = new PrismaClient({
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
});
export async function transfer(from: string, to: string, amount: number) {
return prisma.$transaction(async (tx) => {
const sender = await tx.account.update({
where: { email: from },
data: { balance: { decrement: amount } },
});
if (sender.balance < 0) {
throw new Error(`${from} cannot send ${amount}`); // rolls back the decrement
}
return tx.account.update({
where: { email: to },
data: { balance: { increment: amount } },
});
});
}go deeper
Recall the two call shapes: an array of un-awaited queries, or an async callback that receives tx. Know that throwing inside the callback rolls everything back.
Explain why the batch form cannot do dependent writes, why every call in the callback must use tx, and the maxWait and timeout defaults of 2000 and 5000 ms.
Show you keep interactive callbacks short and free of network calls, pass tx through helpers, and know that a stray outer-client call silently escapes the transaction.
Weigh setting team defaults: which writes must use nested writes or conditional updates instead of interactive transactions, and whether transactionOptions defaults belong in the shared client.
## Two shapes of one method Prisma Client exposes transactions through a single method, `$transaction`, with two very different call shapes. A **transaction** here means a group of SQL statements that the database commits together or rolls back together. Interviewers ask about the two shapes because choosing the wrong one produces code that looks transactional and is not. | | Batch: `$transaction([...])` | Interactive: `$transaction(async (tx) => ...)` | |---|---|---| | Input | an array of un-awaited Prisma Client queries | an async callback receiving `tx` | | Order | array order, one after another | whatever your code does | | Logic between queries | none | any JavaScript | | Use one result in the next query | no | yes | | Commit | after the last query succeeds | when the callback's promise resolves | | Rollback | when any query fails | when the callback throws or a query fails | | Returns | a tuple of every query's result | the callback's return value | ## The batch form Prisma Client queries are **lazy**: `prisma.post.count()` returns a `PrismaPromise` that does nothing until it is awaited or handed to `$transaction`. The batch form exploits that: ```ts const [deletedPosts, deletedMessages, user] = await prisma.$transaction([ prisma.post.deleteMany({ where: { authorId: 9 } }), prisma.privateMessage.deleteMany({ where: { userId: 9 } }), prisma.user.delete({ where: { id: 9 } }), ]); ``` Prisma starts one transaction, runs the three statements in array order on the same connection, and commits; if any fails it rolls back the ones already run and the `await` rejects. Two consequences follow: - **Await nothing inside the array.** An awaited query has already run and committed on its own; Prisma then rejects with "All elements of the array need to be Prisma Client promises." - **No dependent writes.** Every query is built before any runs, so you cannot use the id returned by the first in the second. Use a nested write, an interactive transaction, or ids generated in code. ## The interactive form The callback receives `tx`, a Prisma Client bound to one open transaction. It has every model and raw-query method but not `$connect`, `$disconnect`, `$on` or `$extends`. ```ts await prisma.$transaction(async (tx) => { const sender = await tx.account.update({ where: { email: from }, data: { balance: { decrement: amount } }, }); if (sender.balance < 0) throw new Error("Insufficient funds"); await tx.account.update({ where: { email: to }, data: { balance: { increment: amount } } }); }); ``` The rules that matter in an interview: 1. **Every call goes through `tx`.** A call on the outer `prisma` inside the callback runs on another connection, outside the transaction, and stays committed if the callback later throws. 2. **Throwing is how you roll back.** Prisma catches the error, rolls back and rethrows the same error to the caller of `$transaction`. Returning normally commits. 3. **Awaits inside it are serial.** One transaction uses one connection, so even `Promise.all` over `tx` queries runs them one after another. 4. **It holds a connection for its whole life**, including any time spent awaiting non-database work. That is why it has a `timeout`. ## Options and defaults Both shapes accept a second argument with `maxWait`, `timeout` and `isolationLevel`: - `maxWait`: how long Prisma waits to start the transaction; default 2000 ms. - `timeout`: how long the transaction may run before Prisma rolls it back; default 5000 ms. - `isolationLevel`: a `Prisma.TransactionIsolationLevel` value such as `Serializable`; by default the database's own level. The same three can be set for every transaction through the `transactionOptions` option of the `PrismaClient` constructor and overridden per call. ## Nesting Since Prisma ORM 7.5.0, calling `tx.$transaction(async (inner) => ...)` inside an interactive transaction does not open a second transaction. On SQL databases whose driver adapter supports savepoints, PostgreSQL through `PrismaPg` among them, Prisma reuses the outer transaction and sets a **savepoint**: if the inner callback throws, only its work is rolled back and the error reaches the outer callback, which may catch it and continue. ## Choosing - Independent writes across models that must land together: the batch form. - Read, decide in code, then write: the interactive form, kept short. - Related records created together: neither; a nested write is already atomic.
- What happens if you write prisma.account.update instead of tx.account.update inside the callback?That call does not join the transaction. It takes another connection from the adapter's pool, runs and commits on its own, so a later throw in the callback rolls back the `tx` work but not this write. It can also wait for a free connection while the transaction itself is holding one. Pass `tx` into every helper the callback calls.
- Can the batch form take maxWait, timeout and isolationLevel too?Yes. In Prisma 7 both shapes accept the same options object, and both fall back to the constructor's `transactionOptions` and then to the defaults of 2000 ms for `maxWait` and 5000 ms for `timeout`. The batch form is usually short enough that only `isolationLevel` matters in practice.
- How does a nested tx.$transaction behave in Prisma 7.10 on PostgreSQL?Since 7.5.0 it reuses the outer transaction and creates a savepoint. If the inner callback throws, Prisma rolls back to that savepoint and rethrows into the outer callback; if the outer callback catches it, the outer work can still commit. Nested scopes must finish in order, and starting two nested ones concurrently is rejected.
- The batch form runs the array's queries in parallel, so their order is not guaranteed.
- Queries in a $transaction array should be awaited before being passed in.
- A batch $transaction can create a user and use its new id in a later array element.
- Inside the callback the outer prisma client is automatically enlisted in the transaction.
- Throwing inside the interactive callback still commits the writes made before the throw.
- Promise.all over tx queries runs them in parallel on several connections.
Assumes Prisma ORM 7; calling tx.$transaction inside an interactive transaction to get a savepoint arrived in Prisma ORM 7.5.0.