Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage concurrency in MongoDB?

I am new to MongoDB database and for one of my application planning some portion of it to move to MongoDB. Where we need to handle optimistic concurrency. What are the best practices available with MongoDB.

Is MongoDB right choice for application which requires concurrency?

like image 253
Vipul Avatar asked Jul 18 '16 16:07

Vipul


1 Answers

Yes MongoDB would be right choice for concurrency.

MongoDB Locking is Different than the locking in RDBMS.

MongoDB uses multi-granularity locking(see wired tiger) that allows operations to lock at the global, database or collection level, and allows for individual storage engines to implement their own concurrency control below the collection level (e.g., at the document-level in WiredTiger).

MongoDB uses reader-writer locks that allow concurrent readers shared access to a resource, such as a database or collection, but in MMAPv1, give exclusive access to a single write operation.

WiredTiger uses optimistic concurrency control. WiredTiger uses only intent locks at the global, database and collection levels. When the storage engine detects conflicts between two operations, one will incur a write conflict causing MongoDB to transparently retry that operation.

MongoDB has a reader/writer latch for each database.

The latch is multiple-reader, single-writer, and it is writer-greedy, so we can have a unlimited number of simultaneous readers on a database, but there can be only one writer at a time on any collection in any one database.

"writer-greedy", gives priority to write, so when we get a write request, all the read requests are blocked until the write is completed.

The lock here is called as latch since it's lighter than a lock and it performs the job within microseconds.

MongoDB is capable of running as many simultaneous queries.

Hope it Helps!!

References

https://docs.mongodb.com/manual/faq/concurrency/

https://docs.mongodb.com/manual/reference/command/findAndModify/

like image 172
Clement Amarnath Avatar answered Oct 04 '22 08:10

Clement Amarnath