node.js – REST API + DB call race condition

So I have the following logic inside of an API route:

  1. Call object = db.getObjectInfo()
  2. If object.isAvailable === TRUE), then db.updateObjectInfo(..set isAvailable to FALSE..) and execute some action. Once action is done, db.updateObjectInfo(..set isAvailable to TRUE..)
  3. If object.isAvailable === FALSE), then return and do nothing

How do I ensure that if two requests are made for this API very quickly, that there isn’t a race condition where the 2nd request does object = db.getObjectInfo() before the first request can update and set isAvailable to FALSE .. causing both of the requests to execute the action?

This is on a node express route and postgres DB.

Read more here: Source link