When I handle concurrent request on Node.js, How to handle clearly?

Viewed 56

When I handle concurrent request on Node.js,

// before two req,
// userpoint : 1000
// using point amount per req, 1000
router.post('/', async (req) => {
  const willUsingPointAmount = req.body.amount;

  const userPoints = await getUserPoints();
  if (userPoints >= req.body.amount) {
    res.send(await usingPoint());
  }
})

When concurrent req incomes,
I think Event Queue described like [(req1)getUserPoints, (req2)getUserPoint, (req1)usingPoint, (req2)usingPoint].
So both usingPoint was called in this situation. Is there any solution better than database transaction?

1 Answers

This is an interesting question, I suggest you check Node.js and Mutexes, specially this answer: https://stackoverflow.com/a/20765398/1971120

To achieve what you are describing, there are "semaphores" and "mutexes" that work as the DB transactions, locking a resource. The answer I shared already gives a lib to use, there are others to try too:

Update: I would say the DB transactions are a very good option in the first place :)

Related