Taming Concurrency: Handling Prisma P2002 Unique Collisions in High-Traffic Voting Handlers
The Double-Click Race Condition in Upvote Toggling A classic bug in toggle endpoints (like bookmarking or upvoting) is the check-then-act race condition. When a user clicks rapidly, or multiple instances fire simultaneously, two identical queries arrive within 10 milliseconds of each other. If both queries see that no upvote exists, both attempt to execute db.productUpvote.create(). The second query crashes with Prisma error P2002 (Unique constraint failed on the fields: (userId,productId)), throwing an unhandled HTTP 500 error to the client. By catching P2002 explicitly and wrapping complex state transitions in Prisma transactions, we achieved 100% crash-free upvote toggling even under aggressive concurrent stress testing. How do you handle unique constraint collisions and idempotent mutations in your TypeScript backend services?
P2002 is the bane of naive Prisma endpoints. Explicitly handling constraint collisions instead of letting them bubble up as 500s makes a world of difference for UI snappiness.