Commands requiring a database lock

The following commands require a database lock. We should plan in advance before issuing them in a production environment:

  • db.collection.createIndex() in the (default) foreground mode
  • reIndex
  • compact
  • db.repairDatabase()
  • db.createCollection() if creating a multiple GB capped collection
  • db.collection.validate()
  • db.copyDatabase() which may lock more than one database

We also have some commands that lock the entire database for a really short period of time:

  • db.collection.dropIndex()
  • db.getLastError()
  • db.isMaster()
  • Any rs.status() command
  • db.serverStatus()
  • db.auth()
  • db.addUser()

These commands shouldn't take more than a few milliseconds to operate and so we shouldn't worry about it, except if we have automated scripts with these commands in place, in which case we must take note to throttle how often they would occur.

In a sharded environment, each mongod applies its own locks, thus greatly improving concurrency.

In replica sets, our primary server must take all write operations. For these to be replicated correctly to the secondaries, we must lock the local database that holds the oplog of operations at the same time that we lock our primary document/collection/database. This is usually a short-lived lock that we shouldn't worry about.

Secondaries in replica sets will fetch write operations from the primary's local database's oplog, apply the appropriate X lock, and service reads once the X locks are done with.

From the long preceding explanation, it's evident that locking should be avoided at all costs in MongoDB. We should design our database so that we avoid as many X locks as possible and when we need to take X locks over one or multiple databases, do so in a maintenance window with a backup plan in case operations take longer than expected.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.12.192