SlideShare a Scribd company logo
1 of 45
Download to read offline
High Performance Rails with MySQL
Jervin Real, March 2014
I am…
• Consultant, Percona
• @dotmanila
• http://dotmanila.com/blog/
• http://www.mysqlperformanceblog.com/
Rails Fu Mastah!
http://walksalong.files.wordpress.com/2007/05/bruce_on_rails.jpg
Beginner
http://www.devonring.ca/img/ouch.png
Customer Problems
Web Apps Performance
• Powerful servers
• CPUs, higher clock speeds
• Lots of memory
• Fast storage
• Scale in the cloud
• Agile development techniques
Why Not?
• Premature scaling is expensive
• Cost inefficient
• Agile means less effective measurement to compensate
for fast deployments
Squeeze the Software
• Exhaust application optimizations first
• You cannot optimize what you can’t measure
• Cacti, NewRelic, Scout
• NewRelic RPM Developer Mode, Rails Footnotes (2, 3,
4!), Google PerfTools for Ruby
• Dumb schemas and queries (somewhat)
Characteristics of Rails
:primary_key, :string, :text, :integer, :float, :decimal, 

:datetime, :timestamp, :time, :date, :binary, :boolean
• Dumb schemas
• Likes to use SHOW FIELDS
Characteristics of Rails
• Dumb schemas
• Likes to use SHOW FIELDS
• N+1 queries problem
• Well documented and discouraged for use
Characteristics of Rails
• Dumb schemas
• Likes to use SHOW FIELDS
• N+1 queries problem
• Well documented and discouraged for use
• Does SELECT FOR UPDATE
• NOOP transactions still wrapped in BEGIN/COMMIT
Characteristics of Rails
• FK relationships - logical - GOOD
Rails - Good
• FK relationships - logical - GOOD
• Knows how to use PRIMARY KEYs — VERY GOOD!
Rails - Good
• FK relationships - logical - GOOD
• Knows how to use PRIMARY KEYs — VERY GOOD!
• Knows NOOP changes - GOOD
Rails - Good
• FK relationships - logical - GOOD
• Knows how to use PRIMARY KEYs — VERY GOOD!
• Knows NOOP changes - GOOD
• Database agnostic - GOOD
Rails - Good
MySQL by Default
• Assumes you have less powerful hardware
• ironically on 5.5, assumes you have very powerful
CPUs - innodb_thread_concurrency = 0
MySQL by Default
• Assumes you have less powerful hardware
• ironically on 5.5, assumes you have very powerful
CPUs - innodb_thread_concurrency = 0
• Not optimized for faster storage
MySQL by Default
• Assumes you have less powerful hardware
• ironically on 5.5, assumes you have very powerful
CPUs - innodb_thread_concurrency = 0
• Not optimized for faster storage
• Still have bad configuration assumptions
• Query cache
• MyISAM < 5.5.5
MySQL by Default
• Assumes you have less powerful hardware
• ironically on 5.5, assumes you have very powerful
CPUs - innodb_thread_concurrency = 0
• Not optimized for faster storage
• Still have bad configuration assumptions
• Query cache
• MyISAM < 5.5.5
• Still haunted by mutexes
What to Optimize - MySQL
• Disable Query Cache
What to Optimize - MySQL
• Disable Query Cache
• query_cache_size = 0
What to Optimize - MySQL
• Disable Query Cache
• query_cache_size = 0
• query_cache_type = 0
What to Optimize - MySQL
• Disable Query Cache
• skip_name_resolve
What to Optimize - MySQL
• Disable Query Cache
• skip_name_resolve
• Use >= 5.5
What to Optimize - MySQL
• Disable Query Cache
• skip_name_resolve
• Use >= 5.5
• Use Indexes, EXPLAIN should be your friend!
What to Optimize - MySQL
• Disable Query Cache
• skip_name_resolve
• Use >= 5.5
• Use Indexes, EXPLAIN should be your friend!
• 5.6 does Subquery Optimizations
What to Optimize - MySQL
• Slow queries - search and destroy
• long_query_time = 0
• log_slow_verbosity - Percona Server
• pt-query-digest/Percona Cloud Tools
What to Optimize - MySQL
• Use InnoDB
innodb_buffer_pool_size       #  keep  hot  data  in  memory  
innodb_log_file_size             #  allow  more  IO  buffer  
innodb_flush_method  =  O_DIRECT  #  skip  OS  cache  
innodb_[read|write]_io_threads  >  4  
innodb_io_capacity  
innodb_adaptive_flushing_method
What to Optimize - Rails
• counter_cache
• Good for InnoDB if you often SELECT COUNT(*)
• Indexes for find_by, where and family
@posts  =  Post.where(title:  params[:keyword])  
!
mysql>  EXPLAIN  SELECT  `posts`.*  FROM  `posts`    WHERE  `posts`.`title`  =  'LongTitles'  G  
***************************  1.  row  ***************************  
                      id:  1  
    select_type:  SIMPLE  
                table:  posts  
                  type:  ALL  
possible_keys:  NULL  
                    key:  NULL  
            key_len:  NULL  
                    ref:  NULL  
                  rows:  2  
                Extra:  Using  where  
1  row  in  set  (0.00  sec)
What to Optimize - Rails
• dependent: :destroy
24  Query          BEGIN  
24  Query          SELECT  `comments`.*  FROM  `comments`    WHERE  `comments`.`post_id`  =  1  
24  Query          DELETE  FROM  `comments`  WHERE  `comments`.`id`  =  2  
24  Query          DELETE  FROM  `posts`  WHERE  `posts`.`id`  =  1  
24  Query          COMMIT
24  Query          BEGIN  
24  Query          DELETE  FROM  `comments`  WHERE  `comments`.`post_id`  =  4  
24  Query          DELETE  FROM  `posts`  WHERE  `posts`.`id`  =  4  
24  Query          COMMIT
BAD
Use dependent: :delete_all
What to Optimize - Rails
• Cache SHOW FIELDS output - patches for now
• Disable innodb_stats_on_metadata
What to Optimize - Rails
• Cache SHOW FIELDS output - patches for now
• Disable innodb_stats_on_metadata
• Pull only the columns you need - especially excluding
BLOBS
@posts  =  Post.select(“title”)
What to Optimize - Rails
• Avoid pessimistic locks when possible - SELECT … FOR
UPDATE - UPDATE directly and return affected rows
What to Optimize - Rails
• Avoid pessimistic locks when possible - SELECT … FOR
UPDATE - UPDATE directly and return affected rows
• Avoid N+1 queries - use JOIN or includes
What to Optimize - Rails
@posts  =  Post.limit(2)  
!
@posts.each  do  |post|  
   puts  post.authors.name  
end
24  SELECT    `posts`.*  FROM  `posts`    LIMIT  2  
24  Query          SELECT    `authors`.*  FROM  `authors`    WHERE  
`authors`.`id`  =  1    ORDER  BY  `authors`.`id`  ASC  LIMIT  1  
24  Query          SELECT    `authors`.*  FROM  `authors`    WHERE  
`authors`.`id`  =  2    ORDER  BY  `authors`.`id`  ASC  LIMIT  1
With this:
You get this:
What to Optimize - Rails
@posts  =  Post.includes(:authors).limit(2)
24  Query          SELECT    `posts`.*  FROM  `posts`    LIMIT  2  
24  Query          SELECT  `authors`.*  FROM  `authors`    
WHERE  `authors`.`id`  IN  (1,  2)
With this:
You get this:
What to Optimize - Rails
@posts  =  Post.joins(:authors).limit(2);
24  Query          SELECT    `posts`.*  FROM  `posts`  INNER  
JOIN  `authors`  ON  `authors`.`id`  =  
`posts`.`authors_id`  LIMIT  2
With this:
You get this:
What to Optimize - Rails
• Avoid pessimistic locks when possible - SELECT … FOR
UPDATE - UPDATE directly and return affected rows
• Avoid N+1 queries - use JOIN or includes
• Compress MySQL requests, especially transactions!
What to Optimize - Rails
• Avoid pessimistic locks when possible - SELECT … FOR
UPDATE - UPDATE directly and return affected rows
• Avoid N+1 queries - use JOIN or includes
• Compress MySQL requests, especially transactions!
• Learn and use SQL - find_by_sql
What to Optimize - Rails
• Avoid pessimistic locks when possible - SELECT … FOR
UPDATE - UPDATE directly and return affected rows
• Avoid N+1 queries - use JOIN or includes
• Compress MySQL requests, especially transactions!
• Learn and use SQL - find_by_sql
• Don’t accept Model defaults
Further Thoughts
• GDB, Strace, OProfile
• Smart aggregation, use summary tables when possible
• Rails > Caching > MySQL
• Avoid:
config.action_controller.session_store  =  :active_record_store
http://www.amyvernon.net/wp-content/uploads/2014/01/upward-graph-striving.png
Thank you!
… and
• We’re hiring!
• http://www.percona.com/about-us/careers/open-
positions

More Related Content

What's hot

FITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript DebuggingFITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript DebuggingRami Sayar
 
Simplify your integrations with Apache Camel
Simplify your integrations with Apache CamelSimplify your integrations with Apache Camel
Simplify your integrations with Apache CamelKenneth Peeples
 
Apache Solr-Webinar
Apache Solr-WebinarApache Solr-Webinar
Apache Solr-WebinarEdureka!
 
Day 7 - Make it Fast
Day 7 - Make it FastDay 7 - Make it Fast
Day 7 - Make it FastBarry Jones
 
Enterprise Search Using Apache Solr
Enterprise Search Using Apache SolrEnterprise Search Using Apache Solr
Enterprise Search Using Apache Solrsagar chaturvedi
 
GitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by ScalaGitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by Scalatakezoe
 
Mura ORM & Ember JS
Mura ORM & Ember JSMura ORM & Ember JS
Mura ORM & Ember JSMura CMS
 
Apache Solr Search Course Drupal 7 Acquia
Apache Solr Search Course Drupal 7 AcquiaApache Solr Search Course Drupal 7 Acquia
Apache Solr Search Course Drupal 7 AcquiaDropsolid
 
Perl in the Real World
Perl in the Real WorldPerl in the Real World
Perl in the Real WorldOpusVL
 
WebObjects Optimization
WebObjects OptimizationWebObjects Optimization
WebObjects OptimizationWO Community
 
Unlocking the Magical Powers of WP_Query
Unlocking the Magical Powers of WP_QueryUnlocking the Magical Powers of WP_Query
Unlocking the Magical Powers of WP_QueryDustin Filippini
 
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Get Django, Get Hired - An opinionated guide to getting the best job, for the...Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Get Django, Get Hired - An opinionated guide to getting the best job, for the...Marcel Chastain
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesBrett Meyer
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails TutorialWen-Tien Chang
 
NoSQL and SQL - Why Choose? Enjoy the best of both worlds with MySQL
NoSQL and SQL - Why Choose? Enjoy the best of both worlds with MySQLNoSQL and SQL - Why Choose? Enjoy the best of both worlds with MySQL
NoSQL and SQL - Why Choose? Enjoy the best of both worlds with MySQLAndrew Morgan
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewBrett Meyer
 
Event Driven Architecture with Apache Camel
Event Driven Architecture with Apache CamelEvent Driven Architecture with Apache Camel
Event Driven Architecture with Apache Camelprajods
 
Skinny Framework Progress Situation
Skinny Framework Progress SituationSkinny Framework Progress Situation
Skinny Framework Progress SituationKazuhiro Sera
 

What's hot (20)

FITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript DebuggingFITC - Here Be Dragons: Advanced JavaScript Debugging
FITC - Here Be Dragons: Advanced JavaScript Debugging
 
Intro to Apache Solr
Intro to Apache SolrIntro to Apache Solr
Intro to Apache Solr
 
Simplify your integrations with Apache Camel
Simplify your integrations with Apache CamelSimplify your integrations with Apache Camel
Simplify your integrations with Apache Camel
 
Apache Solr-Webinar
Apache Solr-WebinarApache Solr-Webinar
Apache Solr-Webinar
 
Solr Recipes
Solr RecipesSolr Recipes
Solr Recipes
 
Day 7 - Make it Fast
Day 7 - Make it FastDay 7 - Make it Fast
Day 7 - Make it Fast
 
Enterprise Search Using Apache Solr
Enterprise Search Using Apache SolrEnterprise Search Using Apache Solr
Enterprise Search Using Apache Solr
 
GitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by ScalaGitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by Scala
 
Mura ORM & Ember JS
Mura ORM & Ember JSMura ORM & Ember JS
Mura ORM & Ember JS
 
Apache Solr Search Course Drupal 7 Acquia
Apache Solr Search Course Drupal 7 AcquiaApache Solr Search Course Drupal 7 Acquia
Apache Solr Search Course Drupal 7 Acquia
 
Perl in the Real World
Perl in the Real WorldPerl in the Real World
Perl in the Real World
 
WebObjects Optimization
WebObjects OptimizationWebObjects Optimization
WebObjects Optimization
 
Unlocking the Magical Powers of WP_Query
Unlocking the Magical Powers of WP_QueryUnlocking the Magical Powers of WP_Query
Unlocking the Magical Powers of WP_Query
 
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Get Django, Get Hired - An opinionated guide to getting the best job, for the...Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails Tutorial
 
NoSQL and SQL - Why Choose? Enjoy the best of both worlds with MySQL
NoSQL and SQL - Why Choose? Enjoy the best of both worlds with MySQLNoSQL and SQL - Why Choose? Enjoy the best of both worlds with MySQL
NoSQL and SQL - Why Choose? Enjoy the best of both worlds with MySQL
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
 
Event Driven Architecture with Apache Camel
Event Driven Architecture with Apache CamelEvent Driven Architecture with Apache Camel
Event Driven Architecture with Apache Camel
 
Skinny Framework Progress Situation
Skinny Framework Progress SituationSkinny Framework Progress Situation
Skinny Framework Progress Situation
 

Similar to High Performance Rails with MySQL

Optimizing MySQL for Cascade Server
Optimizing MySQL for Cascade ServerOptimizing MySQL for Cascade Server
Optimizing MySQL for Cascade Serverhannonhill
 
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)Aurimas Mikalauskas
 
[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 AppSrijan Technologies
 
BTV PHP - Building Fast Websites
BTV PHP - Building Fast WebsitesBTV PHP - Building Fast Websites
BTV PHP - Building Fast WebsitesJonathan Klein
 
My sql 56_roadmap_april2012
My sql 56_roadmap_april2012My sql 56_roadmap_april2012
My sql 56_roadmap_april2012sqlhjalp
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersJonathan Levin
 
MySQL Performance Tuning at COSCUP 2014
MySQL Performance Tuning at COSCUP 2014MySQL Performance Tuning at COSCUP 2014
MySQL Performance Tuning at COSCUP 2014Ryusuke Kajiyama
 
Silicon Valley Code Camp 2015 - Advanced MongoDB - The Sequel
Silicon Valley Code Camp 2015 - Advanced MongoDB - The SequelSilicon Valley Code Camp 2015 - Advanced MongoDB - The Sequel
Silicon Valley Code Camp 2015 - Advanced MongoDB - The SequelDaniel Coupal
 
Query Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New TricksQuery Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New TricksMYXPLAIN
 
Cassandra Community Webinar: MySQL to Cassandra - What I Wish I'd Known
Cassandra Community Webinar: MySQL to Cassandra - What I Wish I'd KnownCassandra Community Webinar: MySQL to Cassandra - What I Wish I'd Known
Cassandra Community Webinar: MySQL to Cassandra - What I Wish I'd KnownDataStax
 
Lessons learned while building Omroep.nl
Lessons learned while building Omroep.nlLessons learned while building Omroep.nl
Lessons learned while building Omroep.nlbartzon
 
Rails 4 at Austin on Rails
Rails 4 at Austin on RailsRails 4 at Austin on Rails
Rails 4 at Austin on Railsjaustinhughey
 
Lessons learned while building Omroep.nl
Lessons learned while building Omroep.nlLessons learned while building Omroep.nl
Lessons learned while building Omroep.nltieleman
 
Presto Meetup 2016 Small Start
Presto Meetup 2016 Small StartPresto Meetup 2016 Small Start
Presto Meetup 2016 Small StartHiroshi Toyama
 
Performance & Scalability Improvements in Perforce
Performance & Scalability Improvements in PerforcePerformance & Scalability Improvements in Perforce
Performance & Scalability Improvements in PerforcePerforce
 
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013Jaime Crespo
 
ATLRUG Rails Security Presentation - 9/10/2014
ATLRUG Rails Security Presentation - 9/10/2014ATLRUG Rails Security Presentation - 9/10/2014
ATLRUG Rails Security Presentation - 9/10/2014jasnow
 

Similar to High Performance Rails with MySQL (20)

Optimizing MySQL for Cascade Server
Optimizing MySQL for Cascade ServerOptimizing MySQL for Cascade Server
Optimizing MySQL for Cascade Server
 
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
MySQL Performance Tuning. Part 1: MySQL Configuration (includes MySQL 5.7)
 
[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
 
BTV PHP - Building Fast Websites
BTV PHP - Building Fast WebsitesBTV PHP - Building Fast Websites
BTV PHP - Building Fast Websites
 
My sql 56_roadmap_april2012
My sql 56_roadmap_april2012My sql 56_roadmap_april2012
My sql 56_roadmap_april2012
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for Developers
 
MySQL Performance Tuning at COSCUP 2014
MySQL Performance Tuning at COSCUP 2014MySQL Performance Tuning at COSCUP 2014
MySQL Performance Tuning at COSCUP 2014
 
Silicon Valley Code Camp 2015 - Advanced MongoDB - The Sequel
Silicon Valley Code Camp 2015 - Advanced MongoDB - The SequelSilicon Valley Code Camp 2015 - Advanced MongoDB - The Sequel
Silicon Valley Code Camp 2015 - Advanced MongoDB - The Sequel
 
mtl_rubykaigi
mtl_rubykaigimtl_rubykaigi
mtl_rubykaigi
 
Query Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New TricksQuery Optimization with MySQL 5.6: Old and New Tricks
Query Optimization with MySQL 5.6: Old and New Tricks
 
Cassandra Community Webinar: MySQL to Cassandra - What I Wish I'd Known
Cassandra Community Webinar: MySQL to Cassandra - What I Wish I'd KnownCassandra Community Webinar: MySQL to Cassandra - What I Wish I'd Known
Cassandra Community Webinar: MySQL to Cassandra - What I Wish I'd Known
 
Lessons learned while building Omroep.nl
Lessons learned while building Omroep.nlLessons learned while building Omroep.nl
Lessons learned while building Omroep.nl
 
Rails 4 at Austin on Rails
Rails 4 at Austin on RailsRails 4 at Austin on Rails
Rails 4 at Austin on Rails
 
MySQL 5.7 what's new
MySQL 5.7 what's newMySQL 5.7 what's new
MySQL 5.7 what's new
 
Lessons learned while building Omroep.nl
Lessons learned while building Omroep.nlLessons learned while building Omroep.nl
Lessons learned while building Omroep.nl
 
Breaking data
Breaking dataBreaking data
Breaking data
 
Presto Meetup 2016 Small Start
Presto Meetup 2016 Small StartPresto Meetup 2016 Small Start
Presto Meetup 2016 Small Start
 
Performance & Scalability Improvements in Perforce
Performance & Scalability Improvements in PerforcePerformance & Scalability Improvements in Perforce
Performance & Scalability Improvements in Perforce
 
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
Query Optimization with MySQL 5.6: Old and New Tricks - Percona Live London 2013
 
ATLRUG Rails Security Presentation - 9/10/2014
ATLRUG Rails Security Presentation - 9/10/2014ATLRUG Rails Security Presentation - 9/10/2014
ATLRUG Rails Security Presentation - 9/10/2014
 

More from Jervin Real

Low Cost Transactional and Analytics with MySQL + Clickhouse
 Low Cost Transactional and Analytics with MySQL + Clickhouse Low Cost Transactional and Analytics with MySQL + Clickhouse
Low Cost Transactional and Analytics with MySQL + ClickhouseJervin Real
 
Low Cost Transactional and Analytics with MySQL + Clickhouse
Low Cost Transactional and Analytics with MySQL + ClickhouseLow Cost Transactional and Analytics with MySQL + Clickhouse
Low Cost Transactional and Analytics with MySQL + ClickhouseJervin Real
 
ZFS and MySQL on Linux, the Sweet Spots
ZFS and MySQL on Linux, the Sweet SpotsZFS and MySQL on Linux, the Sweet Spots
ZFS and MySQL on Linux, the Sweet SpotsJervin Real
 
Lock, Stock and Backup: Data Guaranteed
Lock, Stock and Backup: Data GuaranteedLock, Stock and Backup: Data Guaranteed
Lock, Stock and Backup: Data GuaranteedJervin Real
 
Learning MySQL 5.7
Learning MySQL 5.7Learning MySQL 5.7
Learning MySQL 5.7Jervin Real
 
Heterogenous Persistence
Heterogenous PersistenceHeterogenous Persistence
Heterogenous PersistenceJervin Real
 
Preventing and Resolving MySQL Downtime
Preventing and Resolving MySQL DowntimePreventing and Resolving MySQL Downtime
Preventing and Resolving MySQL DowntimeJervin Real
 
TokuDB - What You Need to Know
TokuDB - What You Need to KnowTokuDB - What You Need to Know
TokuDB - What You Need to KnowJervin Real
 
PLAM 2015 - Evolving Backups Strategy, Devploying pyxbackup
PLAM 2015 - Evolving Backups Strategy, Devploying pyxbackupPLAM 2015 - Evolving Backups Strategy, Devploying pyxbackup
PLAM 2015 - Evolving Backups Strategy, Devploying pyxbackupJervin Real
 
Learning by Experience, Devploying pyxbackup
Learning by Experience, Devploying pyxbackupLearning by Experience, Devploying pyxbackup
Learning by Experience, Devploying pyxbackupJervin Real
 
AWS Users Meetup April 2015
AWS Users Meetup April 2015AWS Users Meetup April 2015
AWS Users Meetup April 2015Jervin Real
 
Highly Available MySQL/PHP Applications with mysqlnd
Highly Available MySQL/PHP Applications with mysqlndHighly Available MySQL/PHP Applications with mysqlnd
Highly Available MySQL/PHP Applications with mysqlndJervin Real
 

More from Jervin Real (12)

Low Cost Transactional and Analytics with MySQL + Clickhouse
 Low Cost Transactional and Analytics with MySQL + Clickhouse Low Cost Transactional and Analytics with MySQL + Clickhouse
Low Cost Transactional and Analytics with MySQL + Clickhouse
 
Low Cost Transactional and Analytics with MySQL + Clickhouse
Low Cost Transactional and Analytics with MySQL + ClickhouseLow Cost Transactional and Analytics with MySQL + Clickhouse
Low Cost Transactional and Analytics with MySQL + Clickhouse
 
ZFS and MySQL on Linux, the Sweet Spots
ZFS and MySQL on Linux, the Sweet SpotsZFS and MySQL on Linux, the Sweet Spots
ZFS and MySQL on Linux, the Sweet Spots
 
Lock, Stock and Backup: Data Guaranteed
Lock, Stock and Backup: Data GuaranteedLock, Stock and Backup: Data Guaranteed
Lock, Stock and Backup: Data Guaranteed
 
Learning MySQL 5.7
Learning MySQL 5.7Learning MySQL 5.7
Learning MySQL 5.7
 
Heterogenous Persistence
Heterogenous PersistenceHeterogenous Persistence
Heterogenous Persistence
 
Preventing and Resolving MySQL Downtime
Preventing and Resolving MySQL DowntimePreventing and Resolving MySQL Downtime
Preventing and Resolving MySQL Downtime
 
TokuDB - What You Need to Know
TokuDB - What You Need to KnowTokuDB - What You Need to Know
TokuDB - What You Need to Know
 
PLAM 2015 - Evolving Backups Strategy, Devploying pyxbackup
PLAM 2015 - Evolving Backups Strategy, Devploying pyxbackupPLAM 2015 - Evolving Backups Strategy, Devploying pyxbackup
PLAM 2015 - Evolving Backups Strategy, Devploying pyxbackup
 
Learning by Experience, Devploying pyxbackup
Learning by Experience, Devploying pyxbackupLearning by Experience, Devploying pyxbackup
Learning by Experience, Devploying pyxbackup
 
AWS Users Meetup April 2015
AWS Users Meetup April 2015AWS Users Meetup April 2015
AWS Users Meetup April 2015
 
Highly Available MySQL/PHP Applications with mysqlnd
Highly Available MySQL/PHP Applications with mysqlndHighly Available MySQL/PHP Applications with mysqlnd
Highly Available MySQL/PHP Applications with mysqlnd
 

Recently uploaded

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 

Recently uploaded (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 

High Performance Rails with MySQL

  • 1. High Performance Rails with MySQL Jervin Real, March 2014
  • 2. I am… • Consultant, Percona • @dotmanila • http://dotmanila.com/blog/ • http://www.mysqlperformanceblog.com/
  • 6. Web Apps Performance • Powerful servers • CPUs, higher clock speeds • Lots of memory • Fast storage • Scale in the cloud • Agile development techniques
  • 7. Why Not? • Premature scaling is expensive • Cost inefficient • Agile means less effective measurement to compensate for fast deployments
  • 8. Squeeze the Software • Exhaust application optimizations first • You cannot optimize what you can’t measure • Cacti, NewRelic, Scout • NewRelic RPM Developer Mode, Rails Footnotes (2, 3, 4!), Google PerfTools for Ruby
  • 9. • Dumb schemas and queries (somewhat) Characteristics of Rails :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean
  • 10. • Dumb schemas • Likes to use SHOW FIELDS Characteristics of Rails
  • 11. • Dumb schemas • Likes to use SHOW FIELDS • N+1 queries problem • Well documented and discouraged for use Characteristics of Rails
  • 12. • Dumb schemas • Likes to use SHOW FIELDS • N+1 queries problem • Well documented and discouraged for use • Does SELECT FOR UPDATE • NOOP transactions still wrapped in BEGIN/COMMIT Characteristics of Rails
  • 13. • FK relationships - logical - GOOD Rails - Good
  • 14. • FK relationships - logical - GOOD • Knows how to use PRIMARY KEYs — VERY GOOD! Rails - Good
  • 15. • FK relationships - logical - GOOD • Knows how to use PRIMARY KEYs — VERY GOOD! • Knows NOOP changes - GOOD Rails - Good
  • 16. • FK relationships - logical - GOOD • Knows how to use PRIMARY KEYs — VERY GOOD! • Knows NOOP changes - GOOD • Database agnostic - GOOD Rails - Good
  • 17. MySQL by Default • Assumes you have less powerful hardware • ironically on 5.5, assumes you have very powerful CPUs - innodb_thread_concurrency = 0
  • 18. MySQL by Default • Assumes you have less powerful hardware • ironically on 5.5, assumes you have very powerful CPUs - innodb_thread_concurrency = 0 • Not optimized for faster storage
  • 19. MySQL by Default • Assumes you have less powerful hardware • ironically on 5.5, assumes you have very powerful CPUs - innodb_thread_concurrency = 0 • Not optimized for faster storage • Still have bad configuration assumptions • Query cache • MyISAM < 5.5.5
  • 20. MySQL by Default • Assumes you have less powerful hardware • ironically on 5.5, assumes you have very powerful CPUs - innodb_thread_concurrency = 0 • Not optimized for faster storage • Still have bad configuration assumptions • Query cache • MyISAM < 5.5.5 • Still haunted by mutexes
  • 21. What to Optimize - MySQL • Disable Query Cache
  • 22. What to Optimize - MySQL • Disable Query Cache • query_cache_size = 0
  • 23. What to Optimize - MySQL • Disable Query Cache • query_cache_size = 0 • query_cache_type = 0
  • 24. What to Optimize - MySQL • Disable Query Cache • skip_name_resolve
  • 25. What to Optimize - MySQL • Disable Query Cache • skip_name_resolve • Use >= 5.5
  • 26. What to Optimize - MySQL • Disable Query Cache • skip_name_resolve • Use >= 5.5 • Use Indexes, EXPLAIN should be your friend!
  • 27. What to Optimize - MySQL • Disable Query Cache • skip_name_resolve • Use >= 5.5 • Use Indexes, EXPLAIN should be your friend! • 5.6 does Subquery Optimizations
  • 28. What to Optimize - MySQL • Slow queries - search and destroy • long_query_time = 0 • log_slow_verbosity - Percona Server • pt-query-digest/Percona Cloud Tools
  • 29. What to Optimize - MySQL • Use InnoDB innodb_buffer_pool_size       #  keep  hot  data  in  memory   innodb_log_file_size             #  allow  more  IO  buffer   innodb_flush_method  =  O_DIRECT  #  skip  OS  cache   innodb_[read|write]_io_threads  >  4   innodb_io_capacity   innodb_adaptive_flushing_method
  • 30. What to Optimize - Rails • counter_cache • Good for InnoDB if you often SELECT COUNT(*) • Indexes for find_by, where and family @posts  =  Post.where(title:  params[:keyword])   ! mysql>  EXPLAIN  SELECT  `posts`.*  FROM  `posts`    WHERE  `posts`.`title`  =  'LongTitles'  G   ***************************  1.  row  ***************************                        id:  1      select_type:  SIMPLE                  table:  posts                    type:  ALL   possible_keys:  NULL                      key:  NULL              key_len:  NULL                      ref:  NULL                    rows:  2                  Extra:  Using  where   1  row  in  set  (0.00  sec)
  • 31. What to Optimize - Rails • dependent: :destroy 24  Query          BEGIN   24  Query          SELECT  `comments`.*  FROM  `comments`    WHERE  `comments`.`post_id`  =  1   24  Query          DELETE  FROM  `comments`  WHERE  `comments`.`id`  =  2   24  Query          DELETE  FROM  `posts`  WHERE  `posts`.`id`  =  1   24  Query          COMMIT 24  Query          BEGIN   24  Query          DELETE  FROM  `comments`  WHERE  `comments`.`post_id`  =  4   24  Query          DELETE  FROM  `posts`  WHERE  `posts`.`id`  =  4   24  Query          COMMIT BAD Use dependent: :delete_all
  • 32. What to Optimize - Rails • Cache SHOW FIELDS output - patches for now • Disable innodb_stats_on_metadata
  • 33. What to Optimize - Rails • Cache SHOW FIELDS output - patches for now • Disable innodb_stats_on_metadata • Pull only the columns you need - especially excluding BLOBS @posts  =  Post.select(“title”)
  • 34. What to Optimize - Rails • Avoid pessimistic locks when possible - SELECT … FOR UPDATE - UPDATE directly and return affected rows
  • 35. What to Optimize - Rails • Avoid pessimistic locks when possible - SELECT … FOR UPDATE - UPDATE directly and return affected rows • Avoid N+1 queries - use JOIN or includes
  • 36. What to Optimize - Rails @posts  =  Post.limit(2)   ! @posts.each  do  |post|     puts  post.authors.name   end 24  SELECT    `posts`.*  FROM  `posts`    LIMIT  2   24  Query          SELECT    `authors`.*  FROM  `authors`    WHERE   `authors`.`id`  =  1    ORDER  BY  `authors`.`id`  ASC  LIMIT  1   24  Query          SELECT    `authors`.*  FROM  `authors`    WHERE   `authors`.`id`  =  2    ORDER  BY  `authors`.`id`  ASC  LIMIT  1 With this: You get this:
  • 37. What to Optimize - Rails @posts  =  Post.includes(:authors).limit(2) 24  Query          SELECT    `posts`.*  FROM  `posts`    LIMIT  2   24  Query          SELECT  `authors`.*  FROM  `authors`     WHERE  `authors`.`id`  IN  (1,  2) With this: You get this:
  • 38. What to Optimize - Rails @posts  =  Post.joins(:authors).limit(2); 24  Query          SELECT    `posts`.*  FROM  `posts`  INNER   JOIN  `authors`  ON  `authors`.`id`  =   `posts`.`authors_id`  LIMIT  2 With this: You get this:
  • 39. What to Optimize - Rails • Avoid pessimistic locks when possible - SELECT … FOR UPDATE - UPDATE directly and return affected rows • Avoid N+1 queries - use JOIN or includes • Compress MySQL requests, especially transactions!
  • 40. What to Optimize - Rails • Avoid pessimistic locks when possible - SELECT … FOR UPDATE - UPDATE directly and return affected rows • Avoid N+1 queries - use JOIN or includes • Compress MySQL requests, especially transactions! • Learn and use SQL - find_by_sql
  • 41. What to Optimize - Rails • Avoid pessimistic locks when possible - SELECT … FOR UPDATE - UPDATE directly and return affected rows • Avoid N+1 queries - use JOIN or includes • Compress MySQL requests, especially transactions! • Learn and use SQL - find_by_sql • Don’t accept Model defaults
  • 42. Further Thoughts • GDB, Strace, OProfile • Smart aggregation, use summary tables when possible • Rails > Caching > MySQL • Avoid: config.action_controller.session_store  =  :active_record_store
  • 45. … and • We’re hiring! • http://www.percona.com/about-us/careers/open- positions