Search code examples
reactjsmongodbnext.js

How to handle concurrent purchase attempts for the same number in a raffle system with Next.js, React, and MongoDB?


I am building a website using Next.js, React, and MongoDB Atlas. I want to implement a raffle system where a user can select and purchase a number. Once the payment is completed, the number is assigned to the user. However, I am unsure how to handle the scenario where two users click on the same number at the exact same moment, causing a conflict.

How can I ensure that only one user can purchase a specific number even if multiple users attempt to select it simultaneously? What are the best practices for handling this kind of concurrency issue with MongoDB?


Solution

  • You can simply use an atomic operation. When a purchase is made assign that number to a user if you want to and then make it unavailable. You can use a schema like this:

    {
        "number": 1,
        "isAvailable": true,
        "userId": null
    }
    

    Handle the logic where if the same number , which is unavailable now, is requested by another user then you throw a meaningful error.

    This way if two users attempt a purchase of the same number then one of them will get a successful purchase and the other will have an error thrown on their end.

    Additionally you can explore SWR which can help you in data revalidation on frontend