I’m working on booking service and I use MongoDB as the primary database (and Node.js as back-end).
At some point I encountered a problem with race conditions. In order to make a new booking, I have to verify that the booking time is not reserved by already existing bookings, so I have to do the following book request:
- Load all existing bookings (via find)
- Verify that time not yet reserved
- In case validation passed insert new booking (via insertOne)
This procedure obviously has a flaw of a potential race condition (e.g. 2 persons try to book the same time simultaneously).
So my question is how to handle race-conditions in cases with complicated validation before insert with MongoDB (in particular in my case)? To be precise: what exactly can I do (while still using MongoDB) to still have my validation before insert work, but fix possible race-conditions?
I know about “atomicity” of write operations of MongoDB, still I don’t know how to resolve the problem via something like bulkWrite
.
I tried to find information about locks in MongoDB, but as far as I got, there are no explicit locking mechanism in MongoDB, so I don’t know how to resolve the case I described.
I have found this question is very similar to mine, but no solution for my case were given (I can’t add additional resevration collection for rooms as suggested by Murat Colyaran, cause in my case I don’t have booking for day as a whole, but instead I have booking for “continuous” pieces of time)
Mr Ynoplanetashka is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.