Search code examples
node.jses6-promiseconsistency

Consistency in nodejs


Let's say I have a global key-value pair and operations on it returns a promise(actually I am using Redis), and it stores the value of coins left.

Route /path decrements the coins with the number in the request if the quantity left is greater than 0.

Initially, it has a value of say, 10. Now if two requests came simultaneously for 10 and 9 could both of them read length as 10 and inconsistency occur?

What I know is, promises have callbacks and when the first request to getQuantity() is made, the event loop can process the next request and this request then can read quantity as 10, which could result in inconsistency.

app.get("/path",(req,res)=>{

 const decrementBy=req.value;
 const quantity=await obj.getQuantity(); 
 if(quantity-decrementBy>=0){
  await setQuantity(quantity-decrementBy);
 }
 res.send();

})

Solution

  • To maintain consistency you could use a lock for your quantity where quantity will remain locked until one of the requests is complete.