user1502301
user1502301

Reputation: 565

Node.js, MongoDB, and Concurrency

I'm working on a game prototype and worried about the following case: Browser does AJAX to Node.JS, which has to do several MongoDB operations using async.series.

What prevents multiple requests at the same time causing the database issues? New events (i.e. db operations) seem like they could be run out of order or in between the async.series steps.

In other words, what happens if a user does AJAX calls very quickly, before the prior ones have finished their async.series. Hopefully that makes sense.

If this is indeed an issue, what is the proper way to handle it?

Upvotes: 2

Views: 2708

Answers (2)

grobot
grobot

Reputation: 84

Mongo has database wide read/write locks. It gives preference to writes of the same collection first then fulfills reads. So, if by chance, you have Bill writing to the db and Joe is reading at the same time, Bill's write will execute first while Joe waits until the write is complete and then he is given all the data (including Bill's).

Upvotes: 0

Andrew
Andrew

Reputation: 1289

First and foremost, @fmodos's comment should be completely disregarded. It is wrong on many levels but most simply you could have any number of nodes running (say on Heroku) and there is no guarantee that subsequent requests will hit the same node.

Now, I'm going to answer your question by asking more questions. (You really didn't give me a choice here)

What are these operations doing? Inserting documents? Updating existing documents? Removing documents? This is very important because if all you're doing is simply inserting documents then why does it matter if one finishes for before the other? If you're updating documents then you should NOT be issuing a find, grabbing a ref to the object, and then calling save. (I'm making the assumption you're using mongoose, if you're not, I would) Instead what you should be doing is using built in mongo functions like $inc which properly handle concurrent requests.

http://docs.mongodb.org/manual/reference/operator/update/inc/

Does that help at all? If not, please let me know and I will give it another shot.

Upvotes: 2

Related Questions