MongoDB Locking

MongoDB Locking

MongoDB uses multi-granularity locking. The available granularity levels in descending order are as follows:

  • Global
  • Database
  • Collection
  • Document

The locks MongoDB and other databases use are the following in order of granularity:

  • IS: Intent shared
  • IX: Intent exclusive
  • S: Shared
  • X: Exclusive

If we use locking at a granularity level with shared (S) or exclusive (X), then all higher levels need to be locked with an intent lock of the same type.

rule

  • A single database can simultaneously be locked in IS and IX mode
  • An exclusive (X) lock cannot coexist with any other lock
  • A shared (S) lock can only coexist with intent shared (IS) locks

MongoDB will first acquire intention locks in all ancestors before acquiring the lock on the document itself. This way, when a new request comes in, many times it can quickly identify if it cannot be serviced based on less granular locks.

WiredTiger 在global,db和collection level使用意向锁,在document level使用S和X锁,例外情况是针对多个database,需要global lock。

Reads and writes requesting locks are generally queued in FIFO (first-in, first-out) order. The only optimization that MongoDB will actually do is reordering requests according to the next request in queue to be serviced.

IS(1)->IS(2)->X(3)->S(4)->IS(5)

reorder:

IS(1)->IS(2)->S(4)->IS(5)->X(3)

但是如果在执行IS(1)对应的请求时,新来了IS和S仍旧需要排队,等到X(3)完成后,防止X starvation。


mongo使用简化版的意向锁,只保留了IS/IX/S/X四种锁状态。

意向锁协议,是一种树形(层级)资源进行并发控制的协议。由操作约定和冲突矩阵组成

冲突矩阵

注意IX和IS是可以兼容的

Screen Shot 2020-11-04 at 8.47.52 PM
MongoDB Locks

操作约定

  • 如果加IX/X 锁必须先获取父节点的IX 锁
  • 如果加IS/S 锁必须先获取父节点的IS锁

例子:

Screen Shot 2020-11-04 at 9.59.26 PM

对collection2 进行读,先获取IS所,因此递归获取globale的IS锁

Screen Shot 2020-11-04 at 10.10.06 PM

如果要drop db2,则需要获得db2的X锁,由于db2处于IS锁,X于IS不兼容,无法获锁。

Screen Shot 2020-11-04 at 10.12.10 PM

此时如果要对collection 2进行写操作,需要globa和db2的IX锁,IX与IS兼容,因此加锁成功。

This way, when a new request comes in, many times it can quickly identify if it cannot be serviced based on less granular locks.


https://developer.aliyun.com/article/655101