MongoDb max timeout for all queries

mongodbPHPtimeout

I am using MongoDb/PHP on a Linux server.
The problem is that, if a query takes too long to execute, the mongo server stop (apache keeps running).
So is there any way ,so that I can limit the time for a query to execute, and kill the process automatically like in php- max execution time ?

Till now I have found:

  1. socketTimeoutMS, but I found some where , it will not kill the process.
  2. cursor.maxTimeMS() , but I have to define it for each query.

So can anyone please suggest which approach I should follow so that

  1. the query is automatically killed, if it takes more time,
  2. I don't need to change every query.

Best Answer

As at MongoDB 3.4, the $maxTimeMS value is a cursor option that needs to be set by the client/driver making the request.

There is currently no equivalent server configuration directive, but there is a relevant feature request to watch/upvote in the MongoDB issue tracker: SERVER-13775: maxTimeMS on an instance/database level.

There are some potential caveats to consider for a server-level default $maxTimeMS:

  • This would be a breaking behaviour change for use cases that have intentional long-running query execution times. For example, backup tools such as mongodump would have to be updated to explicitly set a no-MaxTimeMS option or handle unexpected early termination.
  • $maxTimeMS applies to cumulative time for query execution (including multiple batches of results for the same cursor) so this option may have an unexpected outcome for queries returning a larger number/size of results.

Generally your application will have more context on which queries can be terminated, so I suspect a closer fit would be adding the ability to set a default $maxTimeMS per authenticated user/role. The closest related feature suggestion is currently SERVER-15072: Limit resource usage for certain users.