0

i want to prevent my api from multiple api calls at the same time (scenario below)

so, here is my case

  1. I have an API to decrease my product stock quantity. eg : initial bread = 5
  2. Let’s say there are 2 api request at the exact same time with each request 3 bread
  3. when it happens, it will only reduce my stock to 3, because they all get the same last stock, which is five

what i want is that one request is successfully decrease the bread stock to 3 and then the other one failed because i dont have enough bread in my stock

what is the best way to prevent this in nodejs ? thank you

  • Does this answer your question? [node.js: How to lock/synchronize a block of code?](https://stackoverflow.com/questions/50981237/node-js-how-to-lock-synchronize-a-block-of-code) – afarah Nov 17 '22 at 12:31
  • im afraid it's not. I dont want to synchronize block of my code either. Is there any other way ? thank youu – Fabio Kounang Nov 19 '22 at 05:12
  • Did you check the answers? The point is you do *not* have to sync it because the requests are not processed in parallel in the first place (your assumption is incorrect). – afarah Nov 25 '22 at 14:27
  • @afarah yes, but what i want is that i want that two incoming request with the exact same time to decrease my stock correctly what can i do in order to achieve that ? – Fabio Kounang Nov 30 '22 at 00:44

0 Answers0