Always wrap multiple related database operations in a transaction to ensure data consistency and prevent partial updates. This applies to operations across different tables or when coordinating database updates with external services (e.g., Redis cache).
Always wrap multiple related database operations in a transaction to ensure data consistency and prevent partial updates. This applies to operations across different tables or when coordinating database updates with external services (e.g., Redis cache).
Example:
- const dbPromise = prisma.label.upsert({ ... })
- const redisPromise = saveUserLabel({ ... })
- await Promise.all([dbPromise, redisPromise])
+ await prisma.$transaction(async (tx) => {
+ const dbResult = await tx.label.upsert({ ... });
+ await saveUserLabel({ ... });
+ });
Key benefits:
Apply this pattern when:
Enter the URL of a public GitHub repository