Under load, a Prisma 7 checkout's interactive transactions fail with P2028 errors; what do maxWait and timeout govern, and how do you fix the checkout?
answer
- two clocks, two phases
- waiting for a connection versus running
- what the callback awaits
- a connection held end to end
basics
~20 smaxWait (default 2000 ms) bounds the wait to start the transaction, which needs a pooled connection; timeout (default 5000 ms) bounds its run before Prisma rolls it back. Long callbacks hold connections, so the fix is shorter callbacks, not bigger numbers.
solid answer
~50 sAn interactive `$transaction` has two clocks. `maxWait`, 2000 ms by default, covers getting it started: a connection from the driver adapter's pool plus BEGIN; when it runs out you get P2028 "Unable to start a transaction in the given time." `timeout`, 5000 ms by default, covers the running transaction; when it fires Prisma rolls back, and the next `tx` call or the commit rejects with P2028 "cannot be executed on an expired transaction". Both failures usually share one cause: callbacks that hold their connection while awaiting slow work such as a payment call, so a few hundred checkouts queue behind a small pool. The fix is to move network calls out of the callback, replace read-check-write with a conditional update, use `tx` everywhere, and only then tune `maxWait` and `timeout`, per call or through `transactionOptions`.
code
typescript · 27 linesimport { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "./generated/prisma/client";
const prisma = new PrismaClient({
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
});
// Before: the payment call holds a pooled connection inside the transaction.
await prisma.$transaction(async (tx) => {
const product = await tx.product.findUniqueOrThrow({ where: { id: productId } });
if (product.stock < qty) throw new Error("Out of stock");
await chargeCard(paymentToken, total); // 1-8 s of network time while the connection is held
await tx.product.update({ where: { id: productId }, data: { stock: product.stock - qty } });
await tx.order.create({ data: { productId, qty, status: "PAID" } });
});
// After: two short transactions, network call outside both.
const order = await prisma.$transaction(async (tx) => {
const reserved = await tx.product.updateMany({
where: { id: productId, stock: { gte: qty } },
data: { stock: { decrement: qty } },
});
if (reserved.count === 0) throw new Error("Out of stock"); // rolls back, nothing reserved
return tx.order.create({ data: { productId, qty, status: "PENDING" } });
});
await chargeCard(paymentToken, total);
await prisma.order.update({ where: { id: order.id }, data: { status: "PAID" } });go deeper
Recall that an interactive transaction has a maxWait and a timeout, 2000 ms and 5000 ms by default, and that exceeding either ends in a P2028 error.
Explain the two phases: maxWait covers getting a pooled connection and BEGIN, timeout covers the running transaction, and expiry means Prisma rolled back while your callback kept running.
Diagnose the spike from the two messages, trace it to connections held across slow awaits, and restructure the checkout into short transactions before touching any limit.
Set the team's position: whether network calls inside interactive transactions are banned in review, which transactionOptions defaults the shared client carries, and how connection budget is split across services.
## The scenario A checkout endpoint runs this shape inside `prisma.$transaction(async (tx) => ...)`: read the cart, check stock, **call the payment provider**, decrement stock, create the order. It works in testing. Under a traffic spike two errors appear, both with code **P2028** ("Transaction API error"): ```plaintext Transaction API error: Unable to start a transaction in the given time. ``` ```plaintext Transaction API error: A query cannot be executed on an expired transaction. The timeout for this transaction was 5000 ms, however 7012 ms passed since the start of the transaction. Consider increasing the interactive transaction timeout or doing less work in the transaction. ``` To fix it you need to know exactly what each option measures. ## The two clocks | Option | Default | What it bounds | Failure | |---|---|---|---| | `maxWait` | 2000 ms | starting the transaction: getting a connection from the adapter's pool, then BEGIN (and the isolation level, if set) | P2028 "Unable to start a transaction in the given time." | | `timeout` | 5000 ms | the running transaction, from its start until commit | Prisma rolls back; the next `tx` query or the commit rejects with P2028 "... cannot be executed on an expired transaction ..." | Key details: - In Prisma 7.10 the `timeout` clock starts once the transaction has started, so time spent waiting under `maxWait` is not charged to it. - When `timeout` fires, Prisma rolls the transaction back, but it does **not** stop your callback's JavaScript. The callback keeps running until its next `tx` call rejects, or until it returns and the commit rejects with "A commit cannot be executed on an expired transaction". Anything it did outside the database, such as charging a card, has already happened. - Defaults come from the `PrismaClient` constructor's `transactionOptions` when set, otherwise 2000 and 5000; a per-call options object overrides both. The constructor rejects a `transactionOptions` value of 0 or below. ## Why load turns one problem into two An interactive transaction takes **one connection from the adapter's pool and holds it for the whole callback**, including every `await` on something that is not the database. With `PrismaPg`, that pool is the one the adapter manages, sized by the adapter's settings (covered with Prisma's connection and deployment configuration). Put numbers on it. If the payment call takes 1.5 s and the pool has 10 connections, at most about 6 or 7 checkouts per second can hold a connection; request 11 waits. Once the queue is longer than `maxWait`, new transactions fail to start. Meanwhile slow payment responses push running transactions past `timeout`, and they expire. The same root cause produces both messages. Two habits make it worse: 1. **Calling the outer `prisma` inside the callback.** That query needs a second connection from the same pool, and it can wait behind the very transactions that are holding the pool. 2. **Read-check-write in the callback.** Reading stock, checking it in JavaScript and writing it back keeps the transaction open across several round trips, when one conditional statement would do. ## Fixing the checkout 1. **Take network calls out of the callback.** Reserve stock and create a pending order in a short transaction, call the payment provider with no transaction open, then mark the order paid in a second short transaction. Make each step safe to retry. 2. **Shrink what remains.** `tx.product.updateMany({ where: { id, stock: { gte: qty } }, data: { stock: { decrement: qty } } })` checks and decrements in one statement; a `count` of 0 means out of stock, and throwing then rolls back the rest. 3. **Use `tx` for every query** and pass it into helpers instead of importing the shared client. 4. **Only then tune.** Raising `timeout` to 15000 ms makes each transaction hold its connection longer, so the pool drains faster under the same load. Raise `maxWait` or `timeout` per call for a known slow job, or set `transactionOptions` for the whole client, after measuring. ## Diagnosing which clock fired - "Unable to start a transaction in the given time": the pool is saturated or the database is slow to accept BEGIN; look at how long transactions hold connections, not at this one. - "cannot be executed on an expired transaction": this transaction ran too long; the message prints the configured timeout and the time taken, so you can see by how much. - A P2034 instead is a write conflict or deadlock, not a timeout, and calls for a retry rather than a bigger number.
- After the timeout fires, does Prisma stop the code running inside the callback?No. Prisma rolls the transaction back on its timer, but the callback's JavaScript keeps going. The next `tx` query rejects with P2028 for an expired transaction, or, if the callback makes no further query, the commit rejects the same way. Side effects already performed, like an HTTP call, are not undone.
- Where do you set maxWait and timeout for the whole application rather than per call?In the `transactionOptions` option of the `PrismaClient` constructor, which accepts `maxWait`, `timeout` and `isolationLevel`. Any `$transaction` call can still override them in its own options object. Values of 0 or below are rejected when the client is constructed.
- If the pool is the bottleneck, why not simply make the adapter's pool much larger?A bigger pool moves the queue to the database, which has its own connection limit shared by every instance of the service. If each transaction still holds its connection for seconds, more connections only means more idle sessions inside open transactions. Shortening the time each transaction holds a connection raises throughput without that cost.
An interactive transaction is a table held at a busy restaurant. maxWait is how long a new party will wait at the door for a free table; timeout is how long the host lets one party keep its table before clearing it. If you step out for a long phone call, the host clears the table without ending your call, and when you come back your next order is refused.
- The interactive transaction timeout defaults to 10 seconds and maxWait to 5 seconds.
- When the timeout fires, Prisma aborts the callback function immediately.
- Raising timeout is the fix for P2028 under load.
- maxWait limits how long each query inside the transaction may run.
- Calling the outer prisma client inside the callback reuses the transaction's connection.
- P2028 means a write conflict, so retrying the same transaction fixes it.
Assumes Prisma ORM 7: every database goes through a driver adapter such as PrismaPg, so the connection an interactive transaction waits for comes from that adapter's pool.