Welcome!

AJAX & REA Authors: Gathering Clouds, Patson Luk, James Carlini, Sebastian Kruk, Toddy Mladenov

Related Topics: Java, Open Source, AJAX & REA, Web 2.0, Cloud Expo, Big Data Journal

Java: Article

How to Identify a MongoDB Performance Anti Pattern in Five Minutes

Analyzing the application

The other day I was looking at a web application that was using MongoDB as its central database. We were analyzing the application for potential performance problems and inside five minutes I detected what I must consider to be a MongoDB anti pattern and had a 40% impact on response time. The funny thing: It was a Java best practice that triggered it.

Analyzing the Application
The first thing I always do is look at the topology of an application to get a feel for it.

Overall Transaction Flow of the Application

As we see it's a modestly complex web application and it's using MongoDB as its datastore. Overall MongoDB contributes about 7% to the response time of the application. I noticed that about half of all transactions are actually calling MongoDB so I took a closer look.

Flow of Transactions that access MongoDB, showing 10% response time contribution of MongoDB

Those transactions that actually do call MongoDB spend about 10% of their response time in that popular document database. As a next step I wanted to know what was being executed against MongoDB.

Overview of all MongoDB commands. This shows that the JourneyCollection find and getCount contribute the most to response time

One immediately notices the first two lines, which contribute much more to the response time per transaction than all the others. What was interesting was that thegetCount on the JourneyCollection had the highest contribution time, but the developer responsible was not aware that he was even using it anywhere.

Things get interesting - the mysterious getCount call
Taking things one level deeper, we looked at all transactions that were executing the ominous getCount on the JourneyCollection.

Transactions that call JourneyCollection.getCount spend nearly half their time in MongoDB

What jumps out is that those particular transactions spend indeed over 40% of their time in MongoDB, so there was a big potential for improvement here. Another click and we looked at all MongoDB calls that were executed within the context of the same transaction as the getCount call we found so mysterious.

All MongoDB Statements that run within the same transaction context as the JourneyCollection.getCount

What struck us as interesting was that the number of executions per transaction of thefind and getCount on the JourneyCollection seemed closely connected. At this point we decided to look at the transactions themselves - we needed to understand why that particular MongoDB call was executed.

Single Transactions that execute the ominous getCount call

It's immediately clear that several different transaction types are executing that particulargetCount. What that meant for us is that the problem was likely in the core framework of that particular application rather than being specific to any one user action. Here is the interesting snippet:

The Transaction Trace shows where the getCount is executed exactly

We see that the WebService findJourneys spends all its time in the two MongoDB calls. The first is the actual find call to the Journey Collection. The MongoDB client is good at lazy loading, so the find does not actually do much yet. It only calls the server once we access the result set. We can see the round trip to MongoDB visualized in the call node at the end.

We also see the offending getCount. We see that it is executed by a method called sizewhich turns out to be com.mongodb.DBCursor.size method. This was news to our developer. Looking at several other transactions we found that this was a common pattern. Every time we search for something in the JourneyCollection the getCountwould be executed by com.mongodb.DBCursor.size. This always happens before we would really execute the send the find command to the server(which happens in the callmethod). So we used CompuwareAPM DTM's (a.k.a dynaTrace) developer integration and took a look at the offending code. Here is what we found:

BasicDBObject fields = new BasicDBObject();
fields.put(journeyStr + "." + MongoConstants.ID, 1);
fields.put(MongoConstants.ID, 0);

Collection locations = find(patternQuery, fields);

ArrayList results = new ArrayList(locations.size());
for (DBObject dbObject : locations) {
String loc = dbObject.getString(journeyStr);
results.add(loc);
}
return results;


The code looks harmless enough; we execute a find, create an array for the result and fill it. The offender is the location.size(). MongoDBs DBCursor is similar to the ResultSet in JDBC, it does not return the whole data set at once, but only a subset. As a consequence it doesn't really know how many elements the find will end up with. The only way for MongoDB to determine the final size seems to be to execute a getCountwith the same criteria as the original find. In our case that additional unnecessary roundtrip made up 40% of the web services response time!

An Anti-Patter triggered by a Best Practice
So it turns out that calling size on the DBCursor must be considered an anti-pattern! The real funny thing is that the developer thought he was writing performant code. He was following the best practice to pre-size arrays. This avoids any unnecessary re-sizing. In this particular case however, that minor theoretical performance improvement led to a 40% performance degradation!

Conclusion
The take away here is not that MongoDB is bad or doesn't perform. In fact the customer is rather happy with it. But mistakes happen and similar to other database applications we need to have the visibility into a running application to see how much it contributes to the overall response time. We also need to have that visibility to understand which statements are called where and why.

In addition this also demonstrates nicely why premature micro optimization, without leveraging an APM solution, in production will not lead to better performance. In some cases - like this one - it can actually lead to worse performance.

More Stories By Michael Kopp

Michael Kopp has over 12 years of experience as an architect and developer in the Enterprise Java space. Before coming to CompuwareAPM dynaTrace he was the Chief Architect at GoldenSource, a major player in the EDM space. In 2009 he joined dynaTrace as a technology strategist in the center of excellence. He specializes application performance management in large scale production environments with special focus on virtualized and cloud environments. His current focus is how to effectively leverage BigData Solutions and how these technologies impact and change the application landscape.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Cloud Expo Breaking News
“I believe it is incumbent on the Cloud Service Providers (CSPs) and/or System Integrators (SIs) to understand the regulatory and compliance-related issues that their customers face,” noted Manjula Talreja, VP of Global Cloud Business Development at Cisco, in this exclusive Q&A with Cloud Expo Conference Chair Jeremy Geelan. “Of course these issues are different in each industry and in each country.” Cloud Computing Journal: The move to cloud isn't about saving money, it is about saving time - ...
“Regulations and compliance are key trust topics with regards to cloud solutions and technology,” noted Sven Denecken, Vice President, Strategy and Co-Innovation Cloud Solutions, SAP AG, in this exclusive Q&A with Cloud Expo Conference Chair Jeremy Geelan. “But it is also more than security of access – it is portability of data and a clear definition of where the data resides.” Cloud Computing Journal: The move to cloud isn't about saving money, it is about saving time – agree or disagree? Sve...
Many organizations want to expand upon the IaaS foundation to deliver cloud services in all forms – software, mobility, infrastructure and IT. Understanding the strategy, planning process and tools for this transformation will help catalyze changes in the way the business operates and deliver real value.
WSO2 on Thursday announced that WSO2 Vice President of Technology Evangelism Chris Haddad and SUSE Business Development Manager Frank Rego will lead a joint presentation at 12 International Cloud Expo. The session, "Bridging IaaS and PaaS to Deliver the Service-Oriented Data Center," is part of the event's Enterprise Cloud Computing Track on Thursday, June 13, 2013. The Cloud Expo conference is being held June 10-13, 2013 at the Javits Center in New York City. Bridging IaaS and PaaS to Deliver ...
IT has more opportunities than ever before with the growth in users, devices, data and secure cloud services. This creates not only a more enriching experience for users, but more opportunities for businesses. The key to capitalizing on these opportunities is to have the right tools in place to help scale operations. In his Day 3 Keynote at 12th Cloud Expo | Cloud Expo New York [June 10-13, 2013], Intel's Rob Crooke will describe the range of products that Intel provides to support different usa...
Quantum Corp., a proven global expert in data protection and Big Data management, has announced that Senior Vice President of Cloud Solutions Henrik Rosendahl will present a session exploring the future of cloud data protection and the impact of data reduction technologies on cloud storage at the 12th International Cloud Expo. The conference takes place June 10-13 at the Javits Center in New York City. Rosendahl will explore trends in cloud-based backup and disaster recovery (DR) and how curre...
One of the cloud’s biggest draws is the capability to virtualize computing resources, allowing it to be consumed with the click of a mouse. But behind that simple click is an enormous infrastructure challenge that has recently been cited as a major cause for slower enterprise adoption. Enterprises can better prepare for this shift and take full advantage of future computing benefits. Between architecture design and migration planning, the road can be long, so what do you do with your talent? I...
In the old world of IT, if you didn't have hardware capacity or the budget to buy more, your project was dead in the water. Budget constraints can leave some of the best, most creative and most ingenious innovations on the cutting room floor. It’s a true dilemma for developers and innovators – why spend the time creating, when a project could be abandoned in a blink? That was the old world. In the new world of IT, developers rule. They have access to resources they can spin up instantly. A hyb...
INetU, the industry's experts in complex hosting and a global provider of business-centric managed cloud and application hosting, has announced that Cloud Architect Rich Hand will be presenting "Private Cloud, Public Cloud - Is There a Third Option?" at the 12th International Cloud Expo taking place June 10-13, 2013 in New York City. As more enterprise IT departments move into the cloud, many executives are evaluating whether to adopt a Public or Private cloud. The cost benefits of the Public ...
“I’m careful when using terms like Big Data, because it can mean so many things to different people,” explained Eric Hanselman, Chief Analyst at 451 Research, in this exclusive Q&A with Cloud Expo Conference Chair Jeremy Geelan. “There is huge value in analytics that companies can use to pull intelligence from a collection of data sources that are available in their businesses. The inexpensive storage that cloud services can offer make a great environment to pull together siloed data.” Cloud Co...