SlideShare uma empresa Scribd logo
1 de 45
Baixar para ler 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 

Último (20)

OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 

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