Elie Steinbock
Elie Steinbock

Reputation: 5098

Dealing with concurrent requests in Meteor

I'm dealing with a problem where a user can update a document within a specified time limit, and if he doesn't, the server will.

The update involves incrementing a value and adding an object to an array of a document. I need to ensure that only one of the user/server updates the document. Not both.

To ensure this happens, some checks are run to see if the document has already been updated, but there are times where the user and server run at exactly the same time and both pass the checks and then the document is updated twice.

I've been trying many different ways of fixing this, but I haven't been able to. I tried implement a lock similar to this: http://en.wikipedia.org/wiki/Peterson%27s_algorithm to ensure that only one update will happen and the second update will fail, but I haven't been successful. Any ideas?

Upvotes: 1

Views: 678

Answers (1)

stubailo
stubailo

Reputation: 6147

To ensure this happens, some checks are run to see if the document has already been updated, but there are times where the user and server run at exactly the same time and both pass the checks and then the document is updated twice.

You can achieve this by using a MongoDB update query that simultaneously checks if the value has been updated and updates it. Like this:

var post = Posts.findOne("ID");
// ... do some stuff with the post ...
Posts.update({counter: post.counter}, {$push: {items: newItem}, $inc: {counter: 1}});

As you can see, in one query we both check the counter and increment it - so if two of these queries run one right after another only one will actually update the document (since the counter won't match anymore).

Upvotes: 3

Related Questions