Mongodb – Overview of how MongoDB uses its various threads

mongodb

On one instance I have MongoDB using ~85 threads. In lieu of having time to investigate directly, I am curious:

  1. What are the threads used for? Do they fall into a few high-level usage categories?
  2. How can I control/influence the number of threads used? E.g. max connection params, etc.

Best Answer

Max connection count is usually %80 of ulimit value which is 1024 in most linux distros by default. That gives you 819 connections. It can be changed by changing ulimit value.

In MongoDB, each host can use 10 connections which is set by MongoOptions.connectionsPerHost property. These connections are controlled by an internal connection pool. It is thread-safe and you can have up to ConnectionPerHost x threadsAllowedToBlockForConnectionMultiplier threads running simultaneously. threadsAllowedToBlockForConnectionMultiplier also can be changed, its default value is 5. That is by default, you can have 50 simultaneous threads running from one host. Threads more than that value will get the "Out of semaphores to get db connection" exception.

You can change MongoOptions.connectionsPerHost and threadsAllowedToBlockForConnectionMultiplier values appropriately according to your needs.

If you are using drivers on a web application, you should use it as singleton class. No need to 'open connection-> do some work -> close connection' loop. Just declare a global connection once (and initialize in init method of your servlet) and use it in your entire web application.