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();
})
await
. You should be using an atomic operation in redis for decrementing the value. Though JS is single threaded, when youawait
a promise, other code gets to run and you could very well get two pieces of your code both fetching the value of 10 here and then each trying to decrement it from there, one overwriting the other. You should be using an atomic decrement operation in redis to prevent this.DECRBY
command which will do an atomic decrement without ever retrieving the value yourself and without a race condition. A simple Google search finds plenty of discussion of locks such as here and here.