Prisma Interactive Transaction Retry
Use Prisma interactive transactions with serialization failure detection, bounded retry loops, and rollback on invariant violations.
Code
import { PrismaClient, Prisma } from '@prisma/client';
const prisma = new PrismaClient({ log: ['warn', 'error'] });
async function adjustBalance(userId: number, delta: number) {
for (let attempt = 1; attempt <= 4; attempt++) {
try {
return await prisma.$transaction(async (tx) => {
const wallet = await tx.wallet.findUniqueOrThrow({
where: { userId },
});
const next = wallet.balanceCents + delta;
if (next < 0) {
throw new Error('balance would go negative');
}
return tx.wallet.update({
where: { userId },
data: { balanceCents: next },
});
}, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable });
} catch (err) {
const conflict =
err instanceof Prisma.PrismaClientKnownRequestError
&& ['P2034'].includes(err.code);
if (conflict && attempt < 4) {
await new Promise((r) => setTimeout(r, 50 * 2 ** attempt));
continue;
}
throw err;
}
}
throw new Error('unreachable');
}
const wallet = await adjustBalance(1, -250);
console.log('balance now:', wallet.balanceCents);
await prisma.$disconnect();How it works
Prisma Interactive Transaction Retry comes down to the function adjustBalance.
for (let attempt = 1; attempt <= 4; attempt++) is the loop that carries the per-item work. Every asynchronous step is awaited, so rejections surface where the call happens. The import line is the dependency contract: PrismaClient, Prisma come from @prisma/client and nothing else. Error marks loop exhaustion — the code reaches it only after the final attempt fails to return early.
What to watch for
@prisma/clientmust be installed first — the snippet imports it directly.- The guard
next < 0short-circuits the flow with an earlythrowwhen its condition holds.
Putting it to use
Entry signature: async function adjustBalance(userId: number, delta: number)
The demo output is labeled (balance now:), so every printed line has a specific operation behind it.
Core lines
await new Promise((r) => setTimeout(r, 50 * 2 ** attempt));
const wallet = await tx.wallet.findUniqueOrThrow({
where: { userId },
});
throw new Error('balance would go negative');
Interactive Tools for This Topic
FAQ
- Is there a failure path here?
- After loop exhaustion, not on bad input: the `Error` sits after the loop and runs only when the loop finishes.
- Do I need to install anything before running this?
- Yes: `@prisma/client` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.