In reservation system, only 5 different user can create bookings. If 100 user call booking api at same time than how to handle concurrency with locking. I am using nodejs with mongodb. I went through mongo concurrency article here and transactions in mongodb, but cannot find any sample coding solution with locking.
I have achieved solution with Optimistic concurrency control (when there is low contention for the resource - This can be easily implemented using versionNumber or timeStamp field).
Thank you in advance for suggesting me solution with locking.
Now the algorithm is,
Step 1: Get userAllowedNumber from userSettings collection.
Query: db.getCollection('userSettings').find({})
Response Data:
{
"userAllowedNumber": 5
}
Step 2, Get current bookedCount from bookings collection.
Query: db.getCollection('bookings').count({ })
Response Data: 2
Step 3, if bookedCount <= userAllowedNumber then insert in bookings.
Query: db.getCollection('bookings').create({ user_id: "usr_1" })
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…