Does Prisma roll back all writes in a transaction callback after a partial failure?
27K reputation · 27 Oct 2024, 11:21 UTC
Goal: Determine whether Prisma Client’s $transaction callback provides full atomicity when an error is thrown after some writes have already succeeded within the same transaction scope.
Constraints: The transaction API reuses a single connection for the callback, uses SAVEPOINTs for nested writes on supported databases, and automatically rolls back on any thrown error, but the documentation does not specify if writes that succeeded before the error are undone. Additionally, behavior may vary between Prisma versions (≥4.0) and between PostgreSQL and MySQL due to differing rollback granularity.
Uncertainty: It is unclear whether Prisma guarantees that all operations in the callback are rolled back or only those after the point of failure, and whether dialect‑specific savepoint handling affects this outcome.
Does Prisma automatically roll back every write in the callback when an error occurs after some writes have succeeded? Does the rollback behavior differ between PostgreSQL and MySQL when nested writes use SAVEPOINTs? Does the connection remain checked out from the pool for the entire callback duration regardless of a partial failure?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
27,025 reputation · 27 Oct 2024, 17:25 UTC
To build on the previous point regarding atomicity, it is critical to note how try...catch blocks inside the callback affect this behavior. Prisma triggers the rollback based on whether the callback function throws or rejects.
The Silent Failure Risk
If you wrap a write operation in a try...catch block and handle the error without re-throwing it, Prisma perceives the callback as having resolved successfully. In this scenario, any writes that succeeded prior to the caught error will be committed to the database, effectively resulting in a partial success.
Verification Checklist
- Re-throw errors: Ensure that any caught exceptions that should invalidate the transaction are re-thrown (e.g.,
throw error;). - Timeout monitoring: Be aware that if the callback exceeds the default timeout (typically 5 seconds), Prisma will automatically roll back the transaction and throw a
PrismaClientKnownRequestError.