Race conditions on multiple instances of Meteor accessing MongoDB

Hey everyone,

I’m running into an issue where multiple Meteor instances accessing the same MongoDB collection would lead to a race condition.

For Eg: I’m selling a shoe on my site. Meteor_inst_1 calls ‘buy.shoe’ method which queries the collection for shoes whose statuses are ‘available’ and then proceeds with deducting money from the user calling the method ‘buy.shoe’.

While the process of deducting money is going on, it is very much possible that Meteor_inst_2 could call the same ‘buy.shoe’ function that would pull up the same shoe that Meteor_inst_1 is processing and leading to selling one shoe for two different users.

How can we avoid race conditions like this?

I looked into $isolated write queries like recommended here but this doesn’t work on sharded databases (https://stackoverflow.com/questions/16334045/solution-to-bulk-findandmodify-in-mongodb)

I’m sure situations like these are very common with multiple meteor instances running and wanted to reach out to the community for help.


You can do this with mongodb using a two-phase commit. See here: https://docs.mongodb.com/manual/core/write-operations-atomicity/

It’s a PITA, but it’s workable. When it’s shoes at stake, you could read the inventory after writing the order and cancel if there’s a problem), or work it out during fulfillment (where there is no shoe to ship).