SlideShare a Scribd company logo
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 (20)

PDF
FITC - Here Be Dragons: Advanced JavaScript Debugging
Rami Sayar
 
PDF
Intro to Apache Solr
Shalin Shekhar Mangar
 
PPT
Simplify your integrations with Apache Camel
Kenneth Peeples
 
PPTX
Apache Solr-Webinar
Edureka!
 
PDF
Solr Recipes
Erik Hatcher
 
PPTX
Day 7 - Make it Fast
Barry Jones
 
PPTX
Enterprise Search Using Apache Solr
sagar chaturvedi
 
PDF
GitBucket: The perfect Github clone by Scala
takezoe
 
PDF
Mura ORM & Ember JS
Mura CMS
 
PDF
Apache Solr Search Course Drupal 7 Acquia
Dropsolid
 
PDF
Perl in the Real World
OpusVL
 
PDF
WebObjects Optimization
WO Community
 
PDF
Unlocking the Magical Powers of WP_Query
Dustin Filippini
 
PPTX
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Marcel Chastain
 
PDF
Hibernate ORM: Tips, Tricks, and Performance Techniques
Brett Meyer
 
PDF
RSpec on Rails Tutorial
Wen-Tien Chang
 
PDF
NoSQL and SQL - Why Choose? Enjoy the best of both worlds with MySQL
Andrew Morgan
 
ODP
ORM, JPA, & Hibernate Overview
Brett Meyer
 
PDF
Event Driven Architecture with Apache Camel
prajods
 
PDF
Skinny Framework Progress Situation
Kazuhiro Sera
 
FITC - Here Be Dragons: Advanced JavaScript Debugging
Rami Sayar
 
Intro to Apache Solr
Shalin Shekhar Mangar
 
Simplify your integrations with Apache Camel
Kenneth Peeples
 
Apache Solr-Webinar
Edureka!
 
Solr Recipes
Erik Hatcher
 
Day 7 - Make it Fast
Barry Jones
 
Enterprise Search Using Apache Solr
sagar chaturvedi
 
GitBucket: The perfect Github clone by Scala
takezoe
 
Mura ORM & Ember JS
Mura CMS
 
Apache Solr Search Course Drupal 7 Acquia
Dropsolid
 
Perl in the Real World
OpusVL
 
WebObjects Optimization
WO Community
 
Unlocking the Magical Powers of WP_Query
Dustin Filippini
 
Get Django, Get Hired - An opinionated guide to getting the best job, for the...
Marcel Chastain
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Brett Meyer
 
RSpec on Rails Tutorial
Wen-Tien Chang
 
NoSQL and SQL - Why Choose? Enjoy the best of both worlds with MySQL
Andrew Morgan
 
ORM, JPA, & Hibernate Overview
Brett Meyer
 
Event Driven Architecture with Apache Camel
prajods
 
Skinny Framework Progress Situation
Kazuhiro Sera
 

Similar to High Performance Rails with MySQL (20)

PDF
[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App
Srijan Technologies
 
PDF
U C2007 My S Q L Performance Cookbook
guestae36d0
 
PPTX
Optimize the obvious
drhenner
 
PDF
query optimization
Dimara Hakim
 
ODP
Beyond PHP - It's not (just) about the code
Wim Godden
 
PDF
MySQL Query Optimisation 101
Federico Razzoli
 
PDF
API Performance
Faizal Fikhri Zakaria
 
PPTX
Boosting the Performance of your Rails Apps
Matt Kuklinski
 
PDF
Five steps perform_2013
PostgreSQL Experts, Inc.
 
PDF
Zurich2007 MySQL Query Optimization
Hiệp Lê Tuấn
 
PDF
Zurich2007 MySQL Query Optimization
Hiệp Lê Tuấn
 
ODP
Beyond php - it's not (just) about the code
Wim Godden
 
ODP
Beyond php it's not (just) about the code
Wim Godden
 
ODP
Beyond php - it's not (just) about the code
Wim Godden
 
PPT
15 Ways to Kill Your Mysql Application Performance
guest9912e5
 
ODP
Beyond php - it's not (just) about the code
Wim Godden
 
PDF
Beyond php - it's not (just) about the code
Wim Godden
 
PDF
How MySQL can boost (or kill) your application v2
Federico Razzoli
 
PDF
Scaling MySQL Strategies for Developers
Jonathan Levin
 
PDF
Scaling Twitter
Blaine
 
[Srijan Wednesday Webinar] Easy Performance Wins for Your Rails App
Srijan Technologies
 
U C2007 My S Q L Performance Cookbook
guestae36d0
 
Optimize the obvious
drhenner
 
query optimization
Dimara Hakim
 
Beyond PHP - It's not (just) about the code
Wim Godden
 
MySQL Query Optimisation 101
Federico Razzoli
 
API Performance
Faizal Fikhri Zakaria
 
Boosting the Performance of your Rails Apps
Matt Kuklinski
 
Five steps perform_2013
PostgreSQL Experts, Inc.
 
Zurich2007 MySQL Query Optimization
Hiệp Lê Tuấn
 
Zurich2007 MySQL Query Optimization
Hiệp Lê Tuấn
 
Beyond php - it's not (just) about the code
Wim Godden
 
Beyond php it's not (just) about the code
Wim Godden
 
Beyond php - it's not (just) about the code
Wim Godden
 
15 Ways to Kill Your Mysql Application Performance
guest9912e5
 
Beyond php - it's not (just) about the code
Wim Godden
 
Beyond php - it's not (just) about the code
Wim Godden
 
How MySQL can boost (or kill) your application v2
Federico Razzoli
 
Scaling MySQL Strategies for Developers
Jonathan Levin
 
Scaling Twitter
Blaine
 
Ad

More from Jervin Real (12)

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

Recently uploaded (20)

PDF
Executive Business Intelligence Dashboards
vandeslie24
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PPTX
Engineering the Java Web Application (MVC)
abhishekoza1981
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
Executive Business Intelligence Dashboards
vandeslie24
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Engineering the Java Web Application (MVC)
abhishekoza1981
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
Tally software_Introduction_Presentation
AditiBansal54083
 

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