How to automatically kill slow MongoDB queries?

前端 未结 4 1144
执笔经年
执笔经年 2021-01-13 04:54

Is there a way that I can protect my app against slow queries in MongoDB? My application has tons of possibilities of filters and I\'m monitoring all these queries but at th

4条回答
  •  无人及你
    2021-01-13 05:41

    Right now with version 2.6 this is possible. In their press release you can see the following:

    with MaxTimeMS operators and developers can specify auto-cancellation of queries, providing better control of resource utilization;

    Therefore with MaxTimeMS you can specify how much time you allow your query to be executed. For example I do not want a specific query to run more than 200 ms.

    db.collection.find({
      // my query
    }).maxTimeMS(200)
    

    What is cool about this, is that you can specify different timeouts for different operations.

    To answer OP's question in the comment. There is not global setting for this. One reason is that different queries can have different maximum tolerating time. For example you can have query that finds userInfo by it's ID. This is very common operation and should run super fast (otherwise we are doing something wrong). So we can not tolerate it to run longer than 200 ms.

    But we also have some aggregation query, which we run once a day. For this operation it is ok to run for 4 seconds. But we can not tolerate it longer than 10 seconds. So we can put 10000 as maxTimeMS.

提交回复
热议问题