In Prisma 7, which Prisma Client calls already run atomically on their own, so that wrapping them in prisma.$transaction adds nothing?
answer
- think per call, not per line
- writes that reach related records
- the *Many family
- arithmetic the database does
basics
~20 sEach single Prisma Client call is atomic: a nested write runs its parent and related writes in one transaction, the bulk *Many operations run as transactions, and a lone update is one statement. prisma.$transaction is for several separate calls.
solid answer
~40 sIn Prisma 7 the unit of atomicity is one client call. A nested write such as `order.create` with `items: { create: [...] }` opens a transaction, inserts the parent and every child, and commits only if all of them succeed. `createMany`, `updateMany` and `deleteMany` (and the `AndReturn` forms) are documented to run as transactions, and a plain `update` with `{ decrement: 2 }` is a single UPDATE in which the database does the arithmetic. What is **not** atomic is two separate calls: creating an order and then decrementing a product's stock, or two updates under `Promise.all`. Those need `prisma.$transaction`, or a redesign into one call.
code
typescript · 20 linesimport { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "./generated/prisma/client";
const prisma = new PrismaClient({
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
});
// One call, one transaction: the order and both lines commit together.
await prisma.order.create({
data: { customerId: 42, items: { create: [{ productId: 7, qty: 1 }, { productId: 9, qty: 2 }] } },
});
// One statement: SET stock = stock - $1, computed by the database.
await prisma.product.update({ where: { id: 7 }, data: { stock: { decrement: 1 } } });
// Two calls: NOT atomic together. If one rejects, the other can still commit.
await Promise.all([
prisma.product.update({ where: { id: 9 }, data: { stock: { decrement: 2 } } }),
prisma.order.update({ where: { id: 1 }, data: { status: "PAID" } }),
]);go deeper
Recall that one Prisma call is all-or-nothing: a nested create, a *Many bulk call, or a single update. Two separate calls are not, even inside one function.
Explain why a nested write needs no $transaction (Prisma opens one for the parent and child statements) and why decrement beats read-then-write: the database computes the value in one UPDATE.
Show you can spot the hidden two-call write in a code review, such as an order create followed by a stock update, and choose between a nested write, a conditional update and a transaction.
Frame it as a convention: prefer designs where one client call carries the invariant, and reserve explicit transactions for the cases that cannot be expressed that way.
## What atomic means for one Prisma call A **transaction** is a group of database writes that either all take effect or none do. In Prisma ORM 7 you rarely open one by hand, because the client already groups the work of a **single call**. The question an interviewer is probing is whether you know where that boundary sits: at the call, not at the function or the HTTP request that contains it. Three kinds of call are already atomic: - **Nested writes**: one `create` or `update` that also creates, connects or updates related records. - **Bulk operations**: `createMany`, `createManyAndReturn`, `updateMany`, `updateManyAndReturn` and `deleteMany`. - **Single-record writes**: one `create`, `update` or `delete` with no nested part, each sent as a single statement. ## Nested writes: one call, one transaction When a call reaches related records, Prisma has to send several SQL statements: the parent insert, then each child insert that needs the parent's generated key. Prisma wraps them in a transaction on its own. The documentation states it directly: if any operation fails, Prisma Client rolls back the entire transaction. ```ts // Checkout: the order and its lines land together or not at all const order = await prisma.order.create({ data: { customerId: 42, items: { create: [{ productId: 7, qty: 1 }, { productId: 9, qty: 2 }] }, }, }); ``` If the second item violates a constraint, the order row and the first item are rolled back as well, and the `create` call rejects with the database error. This is also the documented answer to **dependent writes**, where the second insert needs an id the first one generated: the batch `$transaction([...])` form cannot pass a result from one query to the next, and a nested write can. ## Bulk operations The `*Many` operations act on a whole set of rows in one call, and the Prisma 7 transactions page lists them as operations that run as transactions. A `deleteMany` that matches 500 rows does not leave 250 deleted if something fails; you get a count when it succeeds and an error when it does not. The limit is that `updateMany` and `deleteMany` take no nested writes, so they cannot reach into a related model. ## Single-row writes and atomic number operations A plain `update` is one UPDATE statement, which the database applies atomically. The part people miss is **where the arithmetic happens**: 1. `data: { stock: { decrement: 2 } }` makes Prisma emit `SET stock = stock - $1`, so the database computes the new value from the current row. 2. Reading the row with `findUnique`, subtracting in JavaScript and writing the result back with `update` is **two calls**. Another request can change the row between them, and wrapping both in a transaction at the default isolation level does not by itself stop that. The atomic number operations are `increment`, `decrement`, `multiply` and `divide` (with `set` as a plain assignment); one is allowed per field per query, and a `null` field is left unchanged by the arithmetic ones. They are the cheapest way to keep a counter, balance or stock level correct, and they need no transaction at all. ## When you do need `prisma.$transaction` | Situation | Atomic without `$transaction`? | Tool | |---|---|---| | Order plus its order lines | Yes | nested `create` | | Mark 300 notifications read | Yes | `updateMany` | | Add 1 to a counter | Yes | `update` with `increment` | | Create an order, then decrement stock on a product | No | `$transaction` (either form) | | Delete a user's posts, messages and the user, across models without cascades | No | `$transaction([...])` | | Read a balance, decide in code, then write two accounts | No | interactive `$transaction` | The rule of thumb: count the client calls. One call is already all-or-nothing. Two or more calls that must succeed together need a transaction, or a redesign that turns them into one call. ## Common mistakes - Wrapping every single `create` in `$transaction` "to be safe": it adds a BEGIN and COMMIT and buys nothing. - Assuming `Promise.all([a, b])` over two writes is atomic: each call commits independently, so one can succeed while the other fails. - Believing a nested create commits the parent first, so a failed child leaves an orphaned parent: it does not. - Treating "inside one service function" as "inside one transaction": the boundary is the client call, not your code's structure.
- Two independent updates are run with Promise.all in Prisma 7. Are they atomic together?No. Each `update` is its own statement and commits on its own; `Promise.all` only waits for both promises. If one rejects, the other may already be committed. To make them succeed or fail together, pass the un-awaited queries to `prisma.$transaction([...])`, or run them through `tx` inside an interactive `$transaction`.
- A nested create needs an id generated by its parent insert. Why does that work in one Prisma call but not in a batch $transaction([...])?A nested write is planned as one operation: Prisma inserts the parent, reads back its key and uses it for the children, all inside one transaction. In the batch form every query is built before any of them runs, so no query can use another's result. Use the nested write, an interactive transaction, or ids you generate up front.
- Wrap every single Prisma create or update in $transaction to be safe.
- A nested create commits the parent row before inserting the children.
- Running two updates with Promise.all makes them succeed or fail together.
- Reading stock with findUnique and writing stock minus one with update is atomic.
- updateMany may leave half of the matched rows changed if it fails.