Missing Transaction
Multiple Prisma writes without $transaction
warningReliability
missing-transactionWhy this matters
Multiple writes without a transaction can leave your database in an inconsistent state if one fails. You might debit an account without creating the transfer record.
✗ Bad
async function transferCredits(from: string, to: string, amount: number) {
await db.account.update({
where: { id: from },
data: { credits: { decrement: amount } },
});
// If this fails, credits are gone but never received
await db.account.update({
where: { id: to },
data: { credits: { increment: amount } },
});
}✓ Good
async function transferCredits(from: string, to: string, amount: number) {
await db.$transaction([
db.account.update({
where: { id: from },
data: { credits: { decrement: amount } },
}),
db.account.update({
where: { id: to },
data: { credits: { increment: amount } },
}),
]);
}How to fix
Wrap related database writes in a $transaction (Prisma) or a SQL transaction. All writes succeed together or roll back together.