Mongo queries in scaleable Meteor app


#1

If you scale a Meteor app horizontally (launch many instances of it), you can get trouble with synchronization. For example, to allow users to decrement a counter on a document by 1 until it’s 0, one would use a deny rule like this:

Collection.deny({
	update: function(userId, doc){
		return 0 < doc.counter
	}
})

If a document’s counter is 1, and two different app instances executes Collection.update("the-document's-id", {$inc:{counter: -1}}) at the same time, the document’s counter will end up being -1, so allow/deny rules aren’t suitable for scaling Meteor apps horizontally, right? In cases as the example above, I’ve been using the following method to get rid of the problem (executed on the server):

Collection.update({
	_id: "the-document's-id",
	counter: {$gt: 0}
}, {
	$inc: {counter: -1}
})

This should work fine, because Mongo only handles one query at a time, right?

Am I correct? Is it a good solution?