skip to content

In Prisma 7, concurrent checkouts oversell a product's stock; which Prisma Client tools prevent it, and when do you need a Serializable $transaction with P2034 retries?

level: seniorimportance: should knowfreq 38%

answer

  1. let the WHERE do the checking
  2. a count of zero means something
  3. a version in the filter
  4. an error code that asks for a retry

basics

~20 s

Put the check in the write: updateMany filtering stock gte the quantity with a decrement, where count 0 means sold out, or a version field in where. Reserve a Serializable $transaction, retried on P2034, for invariants spanning reads.

solid answer

~50 s

The oversell comes from reading stock, checking it in JavaScript and writing it back; wrapping that in an interactive `$transaction` at PostgreSQL's default Read Committed level does not stop it. In Prisma the first fix is a conditional write: `updateMany({ where: { id, stock: { gte: qty } }, data: { stock: { decrement: qty } } })` is one UPDATE, and `count === 0` means sold out. When the new value must be computed in code, add a `version` field to the `where` and increment it; `update` then throws P2025 on a conflict and `updateMany` returns 0. When the rule spans rows you only read, pass `isolationLevel: Prisma.TransactionIsolationLevel.Serializable`; PostgreSQL aborts one of the conflicting transactions, Prisma reports P2034, and you retry the whole `$transaction` call a bounded number of times, because Prisma does not retry for you.

code

typescript · 36 lines
typescript
import { PrismaPg } from "@prisma/adapter-pg";
import { Prisma, PrismaClient } from "./generated/prisma/client";

const prisma = new PrismaClient({
  adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
});

// Retry a Serializable transaction when PostgreSQL aborts it (P2034).
export async function withSerializableRetry<T>(
  run: (tx: Prisma.TransactionClient) => Promise<T>,
  attempts = 3,
): Promise<T> {
  for (let i = 1; ; i++) {
    try {
      return await prisma.$transaction(run, {
        isolationLevel: Prisma.TransactionIsolationLevel.Serializable,
      });
    } catch (e) {
      const conflict = e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2034";
      if (!conflict || i >= attempts) throw e;
      await new Promise((r) => setTimeout(r, 20 * i + Math.random() * 30));
    }
  }
}

// Cart checkout: each line decrements only if enough stock remains.
await withSerializableRetry(async (tx) => {
  for (const line of cart) {
    const res = await tx.product.updateMany({
      where: { id: line.productId, stock: { gte: line.qty } },
      data: { stock: { decrement: line.qty } },
    });
    if (res.count === 0) throw new Error(`Product ${line.productId} is sold out`);
  }
  return tx.order.create({ data: { customerId, status: "PENDING" } });
});

go deeper

for a junior

Recall that decrement does the arithmetic in the database and that updateMany returns a count, so 0 can mean the stock check failed.

for a middle

Explain why read-check-write inside an interactive transaction still oversells at Read Committed, and how a gte filter with decrement or a version field in where closes the gap.

for a senior

Choose per write between a conditional update, a version guard and a Serializable transaction, and write a bounded P2034 retry that wraps the whole call and keeps side effects outside.

for a principal

Decide which concurrency pattern the codebase standardises on, whether a shared retry helper is mandatory for Serializable work, and how conflicts are surfaced to users.

## Where the oversell comes from The budget scenario: a product has 1 unit left and two checkouts arrive together. Each runs this inside an interactive transaction: ```ts await prisma.$transaction(async (tx) => { const p = await tx.product.findUniqueOrThrow({ where: { id } }); if (p.stock < qty) throw new Error("Sold out"); await tx.product.update({ where: { id }, data: { stock: p.stock - qty } }); }); ``` Prisma uses the database's own isolation level unless you pass one, and for PostgreSQL that is **Read Committed**. Both transactions read `stock = 1`, both pass the check, both write `0`, and two units are sold. Why that is allowed at this level is covered with relational transaction anomalies; what matters here is which **Prisma Client tools** close the gap. ## Tool 1: a conditional atomic write Move the check into the statement itself: ```ts const res = await tx.product.updateMany({ where: { id, stock: { gte: qty } }, data: { stock: { decrement: qty } }, }); if (res.count === 0) throw new Error("Sold out"); ``` Prisma sends one `UPDATE ... SET stock = stock - $1 WHERE id = $2 AND stock >= $3`. The database applies the condition and the arithmetic to the current row, so the second checkout matches nothing and gets `count: 0`. Points worth stating in an interview: - `updateMany` returns `{ count }`, so "no row matched" is a value you check, not an error. - `update` also accepts non-unique filters next to a unique one in its `where` (the generated `WhereUniqueInput` exposes every field), so `update({ where: { id, stock: { gte: qty } }, ... })` works too and throws **P2025** ("No record was found for an update") instead of returning 0. - For one product no transaction is needed at all. For a cart, run one conditional write per line inside an interactive `$transaction` and throw on the first `count === 0`, so the earlier lines roll back. ## Tool 2: a version field When the new value cannot be written as `increment` or `decrement`, for example a price recomputed from several inputs, use a **version column**: ```ts await prisma.product.update({ where: { id: p.id, version: p.version }, data: { price: newPrice, version: { increment: 1 } }, }); ``` If someone else wrote first, the version no longer matches: `update` throws P2025 and `updateMany` returns 0. Your code reloads and tries again. The general case for version columns belongs to the ORM-concepts material on optimistic versioning; the Prisma-specific part is that the guard lives in `where` and the bump in `data`, and that Prisma maintains neither automatically. ## Tool 3: Serializable with retry on P2034 Some rules depend on rows you only **read**: "a customer may hold at most three reservations in total" or "the sum of allocations may not exceed the budget". No single conditional write expresses them. Here, raise the isolation level for that transaction: ```ts await prisma.$transaction(async (tx) => { /* reads, checks, writes */ }, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable, }); ``` For PostgreSQL the enum offers `ReadUncommitted`, `ReadCommitted`, `RepeatableRead` and `Serializable`. At `Serializable`, PostgreSQL aborts a transaction whenever it cannot guarantee that the concurrent transactions' combined effect matches some serial order. The `PrismaPg` adapter maps PostgreSQL's serialization failure (SQLSTATE 40001) and deadlock (40P01) to **P2034**, "Transaction failed due to a write conflict or a deadlock. Please retry your transaction". Prisma does **not** retry for you. The retry must: 1. Wrap the **whole** `$transaction` call, so the callback re-reads fresh data. 2. Catch only P2034, checked as `e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2034"`, and rethrow anything else. 3. Stop after a few attempts, with a short randomised backoff. 4. Keep side effects out of the callback, because it may run more than once. ## Locking reads Prisma Client has no option that adds `FOR UPDATE` to a `findUnique` or `findMany`. If you truly need a pessimistic lock, run `tx.$queryRaw` with a `SELECT ... FOR UPDATE` inside the interactive transaction; it then holds the row lock, and a pooled connection, until the callback ends. ## Choosing | Need | Prisma tool | Transaction needed? | |---|---|---| | Decrement only if enough stock | `updateMany` with `gte` and `decrement`, check `count` | no, for one row | | Several cart lines, all or nothing | conditional writes inside an interactive `$transaction`, throw on `count === 0` | yes | | Value computed in code from a read | `version` in `where`, `increment` in `data`, retry on 0 or P2025 | no | | Invariant across rows you only read | interactive `$transaction` at `Serializable`, retry on P2034 | yes | | Explicit row lock | `tx.$queryRaw` with `FOR UPDATE` | yes |

  • Why must the P2034 retry wrap the whole prisma.$transaction call rather than the failing query?
    P2034 means PostgreSQL aborted the transaction, so everything it did is gone and the reads it based decisions on are stale. Only a fresh `$transaction` call starts a new transaction and re-runs the callback's reads. Retrying one query on the old `tx` would hit a closed transaction.
  • With a version guard, when would you use update rather than updateMany?
    `update` returns the updated record and throws P2025 when the guard fails, which suits code that wants an exception on conflict. `updateMany` returns only `{ count }`, which suits code that branches on 0 without try and catch. Both send one guarded UPDATE.

  • Wrapping findUnique and update in an interactive $transaction prevents oversell at the default level.
  • Prisma retries a transaction automatically when it reports P2034.
  • update's where only accepts unique fields, so version checks need updateMany.
  • findUnique inside an interactive transaction locks the row it reads.
  • updateMany throws an error when no row matches the where filter.
  • A P2034 retry should re-run only the query that failed.