skip to Main Content

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();

})

3

Answers


  1. Node.js is single threaded. So no two pieces of code can execute simultaneously. Only one of them will execute at any one time. The non-deterministic part is you cannot predict which request will be processed first.

    Asynchronous I/O means parallel wait, not parallel code execution.

    Login or Signup to reply.
  2. To maintain consistency you could use a lock for your quantity where quantity will remain locked until one of the requests is complete.

    Login or Signup to reply.
  3. There will be inconsistency if more than one requests are coming at the same time.

    Chances of inconsistency ∝ Number of I/O operation with in request and Number of node processes accessing redis.

    As redis is not a transactional data store so redis does not fulfill ACID properties. In order to maintain consistency you can use locking (https://redis.io/topics/distlock). For nodeJs node-redlock is the client to use.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search