SlideShare a Scribd company logo
1 of 31
Rubén Terceño
SolutionsArchitect
Performance Tuning and Optimization
6èmeOctobre,2015
1
Agenda
• Definition of terms
• When to do it
• Measurement tools
• Effecting Change
• Examples
Performance Tuning vs Optimizing
• Optimizing – Modifying a system to work more efficiently or use
fewer resources
• Performance Tuning – Modifying a system to handle increased load
Performance Tuning vs Optimizing
• Optimizing – Modifying a system to work more efficiently or use
fewer resources
• Performance Tuning – Modifying a system to handle increased load
Developmen
t
QA Production
Performance Tuning vs Optimizing
• Optimizing – Modifying a system to work more efficiently or use
fewer resources
• Performance Tuning – Modifying a system to handle increased load
Developmen
t
QA Production
Performance Tuning vs Optimizing
• Optimizing – Modifying a system to work more efficiently or use
fewer resources
• Performance Tuning – Modifying a system to handle increased load
Developmen
t
QA Production
Measurement Tools
Log files, Profiler, Query Optimizer
mongod
log file
profiler (collection)
query engine
Explain plan – Query Planner
Jakes-MacBook-Pro(mongod-3.0.1)[PRIMARY] test> db.example.find({a:1}).explain() // using the old <3.0 syntax
{
"ok": 1,
"queryPlanner": {
"indexFilterSet": false,
"namespace": "test.example",
"parsedQuery": {
"a": {
"$eq": 1
}
},
"plannerVersion": 1,
"rejectedPlans": [ ],
"winningPlan": {
"direction": "forward",
"filter": {
"a": {
"$eq": 1
}
},
"stage": "COLLSCAN"
}
},
"serverInfo": {
"gitVersion": "534b5a3f9d10f00cd27737fbcd951032248b5952",
"host": "Jakes-MacBook-Pro.local",
"port": 27017,
"version": "3.0.1"
}
}
Explain plan – Adding an Index
Jakes-MacBook-Pro(mongod-3.0.1)[PRIMARY] test> db.example.ensureIndex({a:1})
Jakes-MacBook-Pro(mongod-3.0.1)[PRIMARY] test> db.example.find({a:1}).explain() // using the old <3.0 syntax
{
"ok": 1,
"queryPlanner": {
"indexFilterSet": false,
"namespace": "test.example",
"parsedQuery": {
"a": {
"$eq": 1
}
},
"plannerVersion": 1,
"rejectedPlans": [ ],
"winningPlan": {
"inputStage": {
"direction": "forward",
"indexBounds": {
"a": [
"[1.0, 1.0]"
]
},
"indexName": "a_1",
"isMultiKey": false,
"keyPattern": {
"a": 1
},
"stage": "IXSCAN"
},
"stage": "FETCH"
}
}
[…]
New Explain Syntax in MongoDB 3.0
• count, remove, aggregate, etc. now have an explain() method
> db.example.find({a:1}).count().explain() // <3.0
E QUERY TypeError: Object 3 has no method
'explain'
at (shell):1:32
> db.example.explain().find({a:1}).count() // 3.0
• Explain a remove operation without actually removing anything
> db.example.explain().remove({a:1}) // doesn't
remove anything
Explain Levels in MongoDB 3.0
• queryPlanner (default level): runs the query planner and chooses
the winning plan without actually executing the query
– Use case: "Which plan will MongoDB choose to run my query?"
• executionStats – runs the query optimizer, then runs the winning
plan to completion
– Use case: "How is my query performing?"
• allPlansExecution – same as executionStats, but returns all the
query plans, not just the winning plan.
– Use case: "I want as much information as possible to diagnose a
slow query."
Explain plan – Query Planner
Jakes-MacBook-Pro(mongod-3.0.1)[PRIMARY] test> db.example.explain().find({a:1}) // new 3.0 syntax, default level
{
"ok": 1,
"queryPlanner": {
"indexFilterSet": false,
"namespace": "test.example",
"parsedQuery": {
"a": {
"$eq": 1
}
},
"plannerVersion": 1,
"rejectedPlans": [ ],
"winningPlan": {
"inputStage": {
"direction": "forward",
"indexBounds": {
"a": [
"[1.0, 1.0]"
]
},
"indexName": "a_1",
"isMultiKey": false,
"keyPattern": {
"a": 1
},
"stage": "IXSCAN"
},
"stage": "FETCH"
}
}
[…]
queryPlanner (default level): runs
the query planner and chooses the
winning plan without actually
executing the query
Explain plan – Query Optimizer
> db.example.explain("executionStats").find({a:1}) // new 3.0 syntax
{
"executionStats": {
"executionStages": {
"advanced": 3,
"alreadyHasObj": 0,
"docsExamined": 3,
"executionTimeMillisEstimate": 0,
"inputStage": {
"advanced": 3,
"direction": "forward",
"dupsDropped": 0,
"dupsTested": 0,
"executionTimeMillisEstimate": 0,
"indexBounds": {
"a": [
"[1.0, 1.0]"
]
},
"indexName": "a_1",
"invalidates": 0,
"isEOF": 1,
"isMultiKey": false,
"keyPattern": {
"a": 1
},
"keysExamined": 3,
"matchTested": 0,
"nReturned": 3,
"needFetch": 0,
"needTime": 0,
"restoreState": 0,
"saveState": 0,
"seenInvalidated": 0,
"stage": "IXSCAN",
"works": 3
},
"invalidates": 0,
"isEOF": 1,
"nReturned": 3,
"needFetch": 0,
"needTime": 0,
"restoreState": 0,
"saveState": 0,
"stage": "FETCH",
"works": 4
},
"executionSuccess": true,
"executionTimeMillis": 0,
"nReturned": 3,
"totalDocsExamined": 3,
"totalKeysExamined": 3
},
"ok": 1,
"queryPlanner": {
[…]
}
}
executionStats – runs the query optimizer,
then runs the winning plan to completion
Profiler
• 1MB capped collection named system.profile per database, per replica set
• One document per operation
• Examples:
> db.setProfilingLevel(1) // log all operations greater than 100ms
> db.setProfilingLevel(1, 20) // log all operations greater than 20ms
> db.setProfilingLevel(2) // log all operations regardless of duration
> db.setProfilingLevel(0) // turn off profiling
> db.getProfilingStatus() // display current profiling level
{
"slowms": 100,
"was": 2
}
• In a sharded cluster, you will need to connect to each shard's primary
mongod, not mongos
mongod Log Files
Sun Jun 29 06:35:37.646 [conn2]
query test.docs query: {
parent.company: "22794",
parent.employeeId: "83881" }
ntoreturn:1 ntoskip:0
nscanned:806381 keyUpdates:0
numYields: 5 locks(micros)
r:2145254 nreturned:0 reslen:20
1156ms
date and time thread
operation
namespace
n…
counters
lock
times
duration
number
of yields
Parsing Log Files
mtools
• http://github.com/rueckstiess/mtools
• log file analysis for poorly performing queries
– Show me queries that took more than 1000 ms from 6
am to 6 pm:
$ mlogfilter mongodb.log --from 06:00 --to
18:00 --slow 1000 > mongodb-filtered.log
mtools graphs
% mplotqueries --type histogram --group namespace --bucketSize 3600
Command Line tools
• iostat
• dstat
• mongostat
• mongotop
• mongoperf
Ops Manager / Cloud Manager
• Memory usage
• Opcounters
• Lock percentage
• Queues
• Background flush average
• Replication oplog window and lag
Effecting Change
Process
1. Measure current performance
2. Find the bottleneck (the hard part)
3. Remove the bottleneck
4. Measure again
5. Repeat as needed
What can you change?
• Schema design
• Access patterns
• Indexes
• Instance
• Hardware
Schema Design
• Replay Norberto’s conference
in your mind.
• Now we’re done
• (La cuillère n’existe pas)
Example: Access Patterns
• Application allowed searches for users by first and/or last name
Tue Jul 1 13:08:29.858 [conn581923] query db.users query: {
$query: {$and: [ { $and: [ { firstName: /((?i)QbobE)/ }, {
lastName: /((?i)QjonesE)/ } ] } ] }, $orderby: { lastName:
1 } } ntoreturn:25 ntoskip:0 nscanned:2626282 scanAndOrder:1
keyUpdates:0 numYields: 299 locks(micros) r:30536738
nreturned:14 reslen:8646 15504ms
Example: Access Patterns
• Application was searching for unindexed, case-insensitive, unanchored regular
expressions
• MongoDB is better at indexed, case-sensitive, left-anchored regular expressions
{
_id: 1,
firstName: "Bob",
lastName: "Jones"
}
{
_id: 1,
firstName: "Bob",
lastName: "Jones",
fn: "bob",
ln: "jones"
}
> db.users.ensureIndex({ln:1, fn:1})
> db.users.ensureIndex({fn:1, ln:1})
> db.users.find({fn:/^bob/}).sort
({ln:1})
Indexing Suggestions
• Create indexes that support your queries!
• Create highly selective indexes
• Don't create unnecessary indexes and delete unused ones
• Eliminate duplicate indexes with a compound index, if possible
> db.collection.ensureIndex({A:1, B:1, C:1})
– allows queries using leftmost prefix
• Order compound index fields thusly: equality, sort, then range
– see http://emptysqua.re/blog/optimizing-mongodb-compound-indexes/
• Create indexes that support covered queries
• Prevent collection scans in pre-production environments
$ mongod --notablescan
> db.getSiblingDB("admin").runCommand( { setParameter: 1,
notablescan: 1 } )
Example: Hardware
Do's and Don’ts
• Do:
– Read production notes in MongoDB documentation
– Eliminate suspects in the right order (schema,
indexes, operations, instance, hardware)
– Know what is considered "normal" behavior by
monitoring
• Don't:
– confuse symptoms with root causes
– shard a poorly performing system
Questions?

More Related Content

What's hot

Базы данных. HBase
Базы данных. HBaseБазы данных. HBase
Базы данных. HBase
Vadim Tsesko
 
Real-Time Integration Between MongoDB and SQL Databases
Real-Time Integration Between MongoDB and SQL Databases Real-Time Integration Between MongoDB and SQL Databases
Real-Time Integration Between MongoDB and SQL Databases
MongoDB
 
MongoDB Best Practices in AWS
MongoDB Best Practices in AWS MongoDB Best Practices in AWS
MongoDB Best Practices in AWS
Chris Harris
 
High Performance, Scalable MongoDB in a Bare Metal Cloud
High Performance, Scalable MongoDB in a Bare Metal CloudHigh Performance, Scalable MongoDB in a Bare Metal Cloud
High Performance, Scalable MongoDB in a Bare Metal Cloud
MongoDB
 

What's hot (20)

Базы данных. HBase
Базы данных. HBaseБазы данных. HBase
Базы данных. HBase
 
MongoDB: Comparing WiredTiger In-Memory Engine to Redis
MongoDB: Comparing WiredTiger In-Memory Engine to RedisMongoDB: Comparing WiredTiger In-Memory Engine to Redis
MongoDB: Comparing WiredTiger In-Memory Engine to Redis
 
MongoDB - Sharded Cluster Tutorial
MongoDB - Sharded Cluster TutorialMongoDB - Sharded Cluster Tutorial
MongoDB - Sharded Cluster Tutorial
 
Webinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationWebinar: Index Tuning and Evaluation
Webinar: Index Tuning and Evaluation
 
Introduction to Apache Tajo: Data Warehouse for Big Data
Introduction to Apache Tajo: Data Warehouse for Big DataIntroduction to Apache Tajo: Data Warehouse for Big Data
Introduction to Apache Tajo: Data Warehouse for Big Data
 
Understanding and tuning WiredTiger, the new high performance database engine...
Understanding and tuning WiredTiger, the new high performance database engine...Understanding and tuning WiredTiger, the new high performance database engine...
Understanding and tuning WiredTiger, the new high performance database engine...
 
Exploring the replication in MongoDB
Exploring the replication in MongoDBExploring the replication in MongoDB
Exploring the replication in MongoDB
 
Bucket Your Partitions Wisely (Markus Höfer, codecentric AG) | Cassandra Summ...
Bucket Your Partitions Wisely (Markus Höfer, codecentric AG) | Cassandra Summ...Bucket Your Partitions Wisely (Markus Höfer, codecentric AG) | Cassandra Summ...
Bucket Your Partitions Wisely (Markus Höfer, codecentric AG) | Cassandra Summ...
 
MongoDB - External Authentication
MongoDB - External AuthenticationMongoDB - External Authentication
MongoDB - External Authentication
 
MongoDB: Advance concepts - Replication and Sharding
MongoDB: Advance concepts - Replication and ShardingMongoDB: Advance concepts - Replication and Sharding
MongoDB: Advance concepts - Replication and Sharding
 
Real-Time Integration Between MongoDB and SQL Databases
Real-Time Integration Between MongoDB and SQL Databases Real-Time Integration Between MongoDB and SQL Databases
Real-Time Integration Between MongoDB and SQL Databases
 
MongoDB Aggregation Performance
MongoDB Aggregation PerformanceMongoDB Aggregation Performance
MongoDB Aggregation Performance
 
Debugging & Tuning in Spark
Debugging & Tuning in SparkDebugging & Tuning in Spark
Debugging & Tuning in Spark
 
Advanced Apache Cassandra Operations with JMX
Advanced Apache Cassandra Operations with JMXAdvanced Apache Cassandra Operations with JMX
Advanced Apache Cassandra Operations with JMX
 
Monitoring MySQL with OpenTSDB
Monitoring MySQL with OpenTSDBMonitoring MySQL with OpenTSDB
Monitoring MySQL with OpenTSDB
 
MongoDB Best Practices in AWS
MongoDB Best Practices in AWS MongoDB Best Practices in AWS
MongoDB Best Practices in AWS
 
High Performance, Scalable MongoDB in a Bare Metal Cloud
High Performance, Scalable MongoDB in a Bare Metal CloudHigh Performance, Scalable MongoDB in a Bare Metal Cloud
High Performance, Scalable MongoDB in a Bare Metal Cloud
 
Sharding Methods for MongoDB
Sharding Methods for MongoDBSharding Methods for MongoDB
Sharding Methods for MongoDB
 
5 Pitfalls to Avoid with MongoDB
5 Pitfalls to Avoid with MongoDB5 Pitfalls to Avoid with MongoDB
5 Pitfalls to Avoid with MongoDB
 
Integrate Solr with real-time stream processing applications
Integrate Solr with real-time stream processing applicationsIntegrate Solr with real-time stream processing applications
Integrate Solr with real-time stream processing applications
 

Viewers also liked

Trading up: Adding Flexibility and Scalability to Bouygues Telecom with MongoDB
Trading up: Adding Flexibility and Scalability to Bouygues Telecom with MongoDBTrading up: Adding Flexibility and Scalability to Bouygues Telecom with MongoDB
Trading up: Adding Flexibility and Scalability to Bouygues Telecom with MongoDB
MongoDB
 
Availability and scalability in mongo
Availability and scalability in mongoAvailability and scalability in mongo
Availability and scalability in mongo
Md. Khairul Anam
 
MongoDB Basic Concepts
MongoDB Basic ConceptsMongoDB Basic Concepts
MongoDB Basic Concepts
MongoDB
 

Viewers also liked (9)

Indexing
IndexingIndexing
Indexing
 
Trading up: Adding Flexibility and Scalability to Bouygues Telecom with MongoDB
Trading up: Adding Flexibility and Scalability to Bouygues Telecom with MongoDBTrading up: Adding Flexibility and Scalability to Bouygues Telecom with MongoDB
Trading up: Adding Flexibility and Scalability to Bouygues Telecom with MongoDB
 
Agility and Scalability with MongoDB
Agility and Scalability with MongoDBAgility and Scalability with MongoDB
Agility and Scalability with MongoDB
 
Availability and scalability in mongo
Availability and scalability in mongoAvailability and scalability in mongo
Availability and scalability in mongo
 
MongoDB Basic Concepts
MongoDB Basic ConceptsMongoDB Basic Concepts
MongoDB Basic Concepts
 
Inside MongoDB: the Internals of an Open-Source Database
Inside MongoDB: the Internals of an Open-Source DatabaseInside MongoDB: the Internals of an Open-Source Database
Inside MongoDB: the Internals of an Open-Source Database
 
MongoDB: How it Works
MongoDB: How it WorksMongoDB: How it Works
MongoDB: How it Works
 
Scaling and Transaction Futures
Scaling and Transaction FuturesScaling and Transaction Futures
Scaling and Transaction Futures
 
Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)
Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)
Developing with the Modern App Stack: MEAN and MERN (with Angular2 and ReactJS)
 

Similar to Performance Tuning and Optimization

The Art of Database Experiments – PostgresConf Silicon Valley 2018 / San Jose
The Art of Database Experiments – PostgresConf Silicon Valley 2018 / San JoseThe Art of Database Experiments – PostgresConf Silicon Valley 2018 / San Jose
The Art of Database Experiments – PostgresConf Silicon Valley 2018 / San Jose
Nikolay Samokhvalov
 

Similar to Performance Tuning and Optimization (20)

Webinar: Performance Tuning + Optimization
Webinar: Performance Tuning + OptimizationWebinar: Performance Tuning + Optimization
Webinar: Performance Tuning + Optimization
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profiler
 
Building a Complex, Real-Time Data Management Application
Building a Complex, Real-Time Data Management ApplicationBuilding a Complex, Real-Time Data Management Application
Building a Complex, Real-Time Data Management Application
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
 
Seven deadly sins of ElasticSearch Benchmarking
Seven deadly sins of ElasticSearch BenchmarkingSeven deadly sins of ElasticSearch Benchmarking
Seven deadly sins of ElasticSearch Benchmarking
 
Oracle Database : Addressing a performance issue the drilldown approach
Oracle Database : Addressing a performance issue the drilldown approachOracle Database : Addressing a performance issue the drilldown approach
Oracle Database : Addressing a performance issue the drilldown approach
 
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
 
Oracle Database Performance Tuning Basics
Oracle Database Performance Tuning BasicsOracle Database Performance Tuning Basics
Oracle Database Performance Tuning Basics
 
PostgreSQL Performance Problems: Monitoring and Alerting
PostgreSQL Performance Problems: Monitoring and AlertingPostgreSQL Performance Problems: Monitoring and Alerting
PostgreSQL Performance Problems: Monitoring and Alerting
 
Analyze database system using a 3 d method
Analyze database system using a 3 d methodAnalyze database system using a 3 d method
Analyze database system using a 3 d method
 
The Art of Database Experiments – PostgresConf Silicon Valley 2018 / San Jose
The Art of Database Experiments – PostgresConf Silicon Valley 2018 / San JoseThe Art of Database Experiments – PostgresConf Silicon Valley 2018 / San Jose
The Art of Database Experiments – PostgresConf Silicon Valley 2018 / San Jose
 
How to use the new Domino Query Language
How to use the new Domino Query LanguageHow to use the new Domino Query Language
How to use the new Domino Query Language
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App
[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App
[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App
 
Scientific Software Development
Scientific Software DevelopmentScientific Software Development
Scientific Software Development
 
Shooting the Rapids
Shooting the RapidsShooting the Rapids
Shooting the Rapids
 
Intro_2.ppt
Intro_2.pptIntro_2.ppt
Intro_2.ppt
 
Intro.ppt
Intro.pptIntro.ppt
Intro.ppt
 
Intro.ppt
Intro.pptIntro.ppt
Intro.ppt
 
The Ring programming language version 1.5.3 book - Part 7 of 184
The Ring programming language version 1.5.3 book - Part 7 of 184The Ring programming language version 1.5.3 book - Part 7 of 184
The Ring programming language version 1.5.3 book - Part 7 of 184
 

More from MongoDB

More from MongoDB (20)

MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
 
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
MongoDB SoCal 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
MongoDB SoCal 2020: Using MongoDB Services in Kubernetes: Any Platform, Devel...
 
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDBMongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
MongoDB SoCal 2020: A Complete Methodology of Data Modeling for MongoDB
 
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
MongoDB SoCal 2020: From Pharmacist to Analyst: Leveraging MongoDB for Real-T...
 
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series DataMongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
MongoDB SoCal 2020: Best Practices for Working with IoT and Time-series Data
 
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 MongoDB SoCal 2020: MongoDB Atlas Jump Start MongoDB SoCal 2020: MongoDB Atlas Jump Start
MongoDB SoCal 2020: MongoDB Atlas Jump Start
 
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
MongoDB .local San Francisco 2020: Powering the new age data demands [Infosys]
 
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
MongoDB .local San Francisco 2020: Using Client Side Encryption in MongoDB 4.2
 
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
MongoDB .local San Francisco 2020: Using MongoDB Services in Kubernetes: any ...
 
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
MongoDB .local San Francisco 2020: Go on a Data Safari with MongoDB Charts!
 
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your MindsetMongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
MongoDB .local San Francisco 2020: From SQL to NoSQL -- Changing Your Mindset
 
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas JumpstartMongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
MongoDB .local San Francisco 2020: MongoDB Atlas Jumpstart
 
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
MongoDB .local San Francisco 2020: Tips and Tricks++ for Querying and Indexin...
 
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
MongoDB .local San Francisco 2020: Aggregation Pipeline Power++
 
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
MongoDB .local San Francisco 2020: A Complete Methodology of Data Modeling fo...
 
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep DiveMongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
MongoDB .local San Francisco 2020: MongoDB Atlas Data Lake Technical Deep Dive
 
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & GolangMongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
MongoDB .local San Francisco 2020: Developing Alexa Skills with MongoDB & Golang
 
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
MongoDB .local Paris 2020: Realm : l'ingrédient secret pour de meilleures app...
 
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
MongoDB .local Paris 2020: Upply @MongoDB : Upply : Quand le Machine Learning...
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Performance Tuning and Optimization

  • 1. Rubén Terceño SolutionsArchitect Performance Tuning and Optimization 6èmeOctobre,2015 1
  • 2. Agenda • Definition of terms • When to do it • Measurement tools • Effecting Change • Examples
  • 3. Performance Tuning vs Optimizing • Optimizing – Modifying a system to work more efficiently or use fewer resources • Performance Tuning – Modifying a system to handle increased load
  • 4. Performance Tuning vs Optimizing • Optimizing – Modifying a system to work more efficiently or use fewer resources • Performance Tuning – Modifying a system to handle increased load Developmen t QA Production
  • 5. Performance Tuning vs Optimizing • Optimizing – Modifying a system to work more efficiently or use fewer resources • Performance Tuning – Modifying a system to handle increased load Developmen t QA Production
  • 6. Performance Tuning vs Optimizing • Optimizing – Modifying a system to work more efficiently or use fewer resources • Performance Tuning – Modifying a system to handle increased load Developmen t QA Production
  • 8. Log files, Profiler, Query Optimizer mongod log file profiler (collection) query engine
  • 9. Explain plan – Query Planner Jakes-MacBook-Pro(mongod-3.0.1)[PRIMARY] test> db.example.find({a:1}).explain() // using the old <3.0 syntax { "ok": 1, "queryPlanner": { "indexFilterSet": false, "namespace": "test.example", "parsedQuery": { "a": { "$eq": 1 } }, "plannerVersion": 1, "rejectedPlans": [ ], "winningPlan": { "direction": "forward", "filter": { "a": { "$eq": 1 } }, "stage": "COLLSCAN" } }, "serverInfo": { "gitVersion": "534b5a3f9d10f00cd27737fbcd951032248b5952", "host": "Jakes-MacBook-Pro.local", "port": 27017, "version": "3.0.1" } }
  • 10. Explain plan – Adding an Index Jakes-MacBook-Pro(mongod-3.0.1)[PRIMARY] test> db.example.ensureIndex({a:1}) Jakes-MacBook-Pro(mongod-3.0.1)[PRIMARY] test> db.example.find({a:1}).explain() // using the old <3.0 syntax { "ok": 1, "queryPlanner": { "indexFilterSet": false, "namespace": "test.example", "parsedQuery": { "a": { "$eq": 1 } }, "plannerVersion": 1, "rejectedPlans": [ ], "winningPlan": { "inputStage": { "direction": "forward", "indexBounds": { "a": [ "[1.0, 1.0]" ] }, "indexName": "a_1", "isMultiKey": false, "keyPattern": { "a": 1 }, "stage": "IXSCAN" }, "stage": "FETCH" } } […]
  • 11. New Explain Syntax in MongoDB 3.0 • count, remove, aggregate, etc. now have an explain() method > db.example.find({a:1}).count().explain() // <3.0 E QUERY TypeError: Object 3 has no method 'explain' at (shell):1:32 > db.example.explain().find({a:1}).count() // 3.0 • Explain a remove operation without actually removing anything > db.example.explain().remove({a:1}) // doesn't remove anything
  • 12. Explain Levels in MongoDB 3.0 • queryPlanner (default level): runs the query planner and chooses the winning plan without actually executing the query – Use case: "Which plan will MongoDB choose to run my query?" • executionStats – runs the query optimizer, then runs the winning plan to completion – Use case: "How is my query performing?" • allPlansExecution – same as executionStats, but returns all the query plans, not just the winning plan. – Use case: "I want as much information as possible to diagnose a slow query."
  • 13. Explain plan – Query Planner Jakes-MacBook-Pro(mongod-3.0.1)[PRIMARY] test> db.example.explain().find({a:1}) // new 3.0 syntax, default level { "ok": 1, "queryPlanner": { "indexFilterSet": false, "namespace": "test.example", "parsedQuery": { "a": { "$eq": 1 } }, "plannerVersion": 1, "rejectedPlans": [ ], "winningPlan": { "inputStage": { "direction": "forward", "indexBounds": { "a": [ "[1.0, 1.0]" ] }, "indexName": "a_1", "isMultiKey": false, "keyPattern": { "a": 1 }, "stage": "IXSCAN" }, "stage": "FETCH" } } […] queryPlanner (default level): runs the query planner and chooses the winning plan without actually executing the query
  • 14. Explain plan – Query Optimizer > db.example.explain("executionStats").find({a:1}) // new 3.0 syntax { "executionStats": { "executionStages": { "advanced": 3, "alreadyHasObj": 0, "docsExamined": 3, "executionTimeMillisEstimate": 0, "inputStage": { "advanced": 3, "direction": "forward", "dupsDropped": 0, "dupsTested": 0, "executionTimeMillisEstimate": 0, "indexBounds": { "a": [ "[1.0, 1.0]" ] }, "indexName": "a_1", "invalidates": 0, "isEOF": 1, "isMultiKey": false, "keyPattern": { "a": 1 }, "keysExamined": 3, "matchTested": 0, "nReturned": 3, "needFetch": 0, "needTime": 0, "restoreState": 0, "saveState": 0, "seenInvalidated": 0, "stage": "IXSCAN", "works": 3 }, "invalidates": 0, "isEOF": 1, "nReturned": 3, "needFetch": 0, "needTime": 0, "restoreState": 0, "saveState": 0, "stage": "FETCH", "works": 4 }, "executionSuccess": true, "executionTimeMillis": 0, "nReturned": 3, "totalDocsExamined": 3, "totalKeysExamined": 3 }, "ok": 1, "queryPlanner": { […] } } executionStats – runs the query optimizer, then runs the winning plan to completion
  • 15. Profiler • 1MB capped collection named system.profile per database, per replica set • One document per operation • Examples: > db.setProfilingLevel(1) // log all operations greater than 100ms > db.setProfilingLevel(1, 20) // log all operations greater than 20ms > db.setProfilingLevel(2) // log all operations regardless of duration > db.setProfilingLevel(0) // turn off profiling > db.getProfilingStatus() // display current profiling level { "slowms": 100, "was": 2 } • In a sharded cluster, you will need to connect to each shard's primary mongod, not mongos
  • 16. mongod Log Files Sun Jun 29 06:35:37.646 [conn2] query test.docs query: { parent.company: "22794", parent.employeeId: "83881" } ntoreturn:1 ntoskip:0 nscanned:806381 keyUpdates:0 numYields: 5 locks(micros) r:2145254 nreturned:0 reslen:20 1156ms date and time thread operation namespace n… counters lock times duration number of yields
  • 18. mtools • http://github.com/rueckstiess/mtools • log file analysis for poorly performing queries – Show me queries that took more than 1000 ms from 6 am to 6 pm: $ mlogfilter mongodb.log --from 06:00 --to 18:00 --slow 1000 > mongodb-filtered.log
  • 19. mtools graphs % mplotqueries --type histogram --group namespace --bucketSize 3600
  • 20. Command Line tools • iostat • dstat • mongostat • mongotop • mongoperf
  • 21. Ops Manager / Cloud Manager • Memory usage • Opcounters • Lock percentage • Queues • Background flush average • Replication oplog window and lag
  • 23. Process 1. Measure current performance 2. Find the bottleneck (the hard part) 3. Remove the bottleneck 4. Measure again 5. Repeat as needed
  • 24. What can you change? • Schema design • Access patterns • Indexes • Instance • Hardware
  • 25. Schema Design • Replay Norberto’s conference in your mind. • Now we’re done • (La cuillère n’existe pas)
  • 26. Example: Access Patterns • Application allowed searches for users by first and/or last name Tue Jul 1 13:08:29.858 [conn581923] query db.users query: { $query: {$and: [ { $and: [ { firstName: /((?i)QbobE)/ }, { lastName: /((?i)QjonesE)/ } ] } ] }, $orderby: { lastName: 1 } } ntoreturn:25 ntoskip:0 nscanned:2626282 scanAndOrder:1 keyUpdates:0 numYields: 299 locks(micros) r:30536738 nreturned:14 reslen:8646 15504ms
  • 27. Example: Access Patterns • Application was searching for unindexed, case-insensitive, unanchored regular expressions • MongoDB is better at indexed, case-sensitive, left-anchored regular expressions { _id: 1, firstName: "Bob", lastName: "Jones" } { _id: 1, firstName: "Bob", lastName: "Jones", fn: "bob", ln: "jones" } > db.users.ensureIndex({ln:1, fn:1}) > db.users.ensureIndex({fn:1, ln:1}) > db.users.find({fn:/^bob/}).sort ({ln:1})
  • 28. Indexing Suggestions • Create indexes that support your queries! • Create highly selective indexes • Don't create unnecessary indexes and delete unused ones • Eliminate duplicate indexes with a compound index, if possible > db.collection.ensureIndex({A:1, B:1, C:1}) – allows queries using leftmost prefix • Order compound index fields thusly: equality, sort, then range – see http://emptysqua.re/blog/optimizing-mongodb-compound-indexes/ • Create indexes that support covered queries • Prevent collection scans in pre-production environments $ mongod --notablescan > db.getSiblingDB("admin").runCommand( { setParameter: 1, notablescan: 1 } )
  • 30. Do's and Don’ts • Do: – Read production notes in MongoDB documentation – Eliminate suspects in the right order (schema, indexes, operations, instance, hardware) – Know what is considered "normal" behavior by monitoring • Don't: – confuse symptoms with root causes – shard a poorly performing system