Feature Highlight: maxTimeMS in MongoDB 2.6


It's probably happened to you before -- you have an idea in your head and you want to run an operation against your database to show you the data that will answer your question or find the result you want to act on.

You conjure the query.
You type out the query.
You submit the query.
You wait.
You muse ... "Wow, this should have come back quickly."
You investigate and discover your error ... "oh man, that field isn't indexed."

What to do

Now, you're visualizing hundreds of thousands of documents being meticulously scanned, memory churning, IO utilization increasing, palms are sweaty, knees weak, arms are heavy, and so on. Do you allow the query to finish or do you start querying currentOps to find the offending operation, get its ID, and move to terminate it?

A nifty new feature in MongoDB 2.6 helps you avoid situations like this by fitting an ejector seat, with timer, to your query. It's called maxTimeMS. In your MongoDB console (or also supported by an increasing amount of MongoDB drivers), you can do the following:

db.eminem_songs.find({title: "Lose Yourself"}).maxTimeMS(500)  

Now, if this operation takes more than 500 milliseconds to return, MongoDB automatically gives up and terminates the operation for you. Nice, right? This flag allows the CPU to spend a user-defined amount of time working to generate a result.

Driver support

The maxTimeMS flag is an option that was added to the MongoDB protocol for cursors. Therefore, support for it is steadily being rolled out in clients such as the MongoDB console and popular MongoDB community drivers.

Scenarios where maxTimeMS would be useful

There are a number of scenarios where a flag like this can be helpful. For example, if you are in discovery mode and want to protect your database performance against unintended runaway operations, you could ensure all your queries include this flag.

Another scenario would be the batching of results, allowing you to define the amount of time/effort the database should spend returning results until it quits and moves on to the next request. In this situation, the cursor would continue to return results until the allotted amount of time has expired.

This is a nice features to keep in your toolset for the right occasion. It isn't something you would use every day, but when you do, you'll be glad you had it.

Give it a go!

MongoHQ Elastic Deployments now include the option to run MongoDB 2.6. So, if you want to try maxTimeMS (and a number of other great features), it is easy to get started.

Conquer the Data Layer

Spend your time developing apps, not managing databases.