SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Downloaden Sie, um offline zu lesen
In Today’s Session You Will Learn how
to:

•    Gain visibility on site performance
•    Improve scalability and uptime
•    Find and fix key bottlenecks
New Relic + Engine Yard

•  Database
•  Web Servers
•  Caching
•  Background Processing
Web Request Overview
Web Application Overview
DATA
BASE
Database Performance


Lazy loading associated data can quickly
lead to an N+1 query problem.

ORMs (ActiveRecord, DataMapper, etc.) make it easy to
get our data but also make it easy to forget to optimize and
refactor.

N+1 problems are hard to spot in development since you
are working with limited data sets.
N+1 Query Creep

# app/models/customer.rb
class Customer < ActiveRecord::Base
   has_many :addresses
end

# app/models/address.rb
class Address < ActiveRecord::Base
   belongs_to :customer
end

# app/controllers/customers_controller.rb
class CustomersController < ApplicationController
   def index
         @customers = Customer.all
   end
end

# app/views/customers/index.html.erb
<% @customers.each do |customer| %>
   <%= content_tag :h1, customer.name %>
<% end %>
N+1 Query Creep
# app/views/customers/index.html.erb
<% @customers.each do |customer| %>
  <%= content_tag :h1, customer.name %>
  <%= content_tag :h2, customer.addresses.first.city %>
<% end %>


If @customers has 100 records, you'll have 101 queries:

SELECT "customers".* FROM "customers"
SELECT "addresses".* FROM "addresses" WHERE "addresses"."customer_id" = 1
  AND "addresses"."primary" = 't' LIMIT 1
SELECT "addresses".* FROM "addresses" WHERE "addresses"."customer_id" = 2
  AND "addresses"."primary" = 't' LIMIT 1
SELECT "addresses".* FROM "addresses" WHERE "addresses"."customer_id" = 3
  AND "addresses"."primary" = 't' LIMIT 1
...
...
SELECT "addresses".* FROM "addresses" WHERE "addresses"."customer_id" = 100
  AND "addresses"."primary" = 't' LIMIT 1
Eager Loading with .includes

# app/controllers/customers_controller.rb
class CustomersController < ApplicationController
  def index
        @customers = Customer.includes(:addresses).all
  end
end




If @customers has 100 records, now we only have 2 queries:

SELECT "customers".* FROM "customers"
SELECT "addresses".* FROM "addresses" WHERE   "addresses"."customer_id" IN
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,   14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,   52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,   71, 72, 73, 74, 75, 76, 77, 78,
79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,   90, 91, 92, 93, 94, 95, 96, 97,
98, 99, 100)
Finding N+1 in New Relic


New Relic > App Server > Web Transactions > Performance Breakdown
Missing Indexes == Slow Queries
Adding an Index is Simple

# db/migrate/20120201040247_add_index_for_shop_id_on_orders.rb


class AddIndexForShopIdOnOrders < ActiveRecord::Migration
  def change
         add_index :orders, :shop_id
  end
end



 Index Protips:
 •  Searching an index on a table with 1,000 rows is 100x faster than searching a
    table without an index.
 •  Put an index on any columns you will likely query against, it's better to have too
    many than too few indexes.
 •  Adding an index to a table will lock the table!
RUBY
WEB
SERVERS
Passenger 3

•  Simple to operate
•  Simple configuration
•  Handles worker management
•  Great for multi-application environments
•  Great for low resource environments
•  Attached to Nginx/Apache HTTPD
Passenger Request Queue
solo i-c3f2d8a2 ~ # passenger-status
----------- General information -----------
max      = 3
count    = 3
active   = 0
inactive = 3
Waiting on global queue: 0

----------- Application groups -----------
/data/john_yerhot_org/current:
  App root: /data/john_yerhot_org/current
  * PID: 19802   Sessions: 0    Processed: 3     Uptime: 3h 10m 13s

/data/scalingrails/current:
  App root: /data/scalingrails/current
  * PID: 28726   Sessions: 0    Processed: 3     Uptime: 59m 22s

/data/sites/clmeisinger/current:
  App root: /data/sites/clmeisinger/current
  * PID: 22147   Sessions: 0     Processed: 70   Uptime: 10h 45m 57s
Unicorn

•  Independent of front end web server
•  More configuration options
•  Master process will reap children on timeout
•  Great for single application environments
•  Allows for zero downtime deploys
Unicorn Request Queue?

Raindrops
solo i-5b74313d ~ # gem install raindrops
Fetching: raindrops-0.10.0.gem (100%)
Building native extensions. This could take a while...
Successfully installed raindrops-0.10.0
1 gem installed

solo i-5b74313d ~ # ruby -rubygems -e "require 'raindrops'; puts
Raindrops::Linux.unix_listener_stats(['/var/run/engineyard/
unicorn_appname.sock']).inspect"

{"/var/run/engineyard/unicorn_appname.sock"=>#<struct Raindrops::ListenStats
active=0, queued=0>}
Request Queuing in New Relic
Request Queuing in New Relic




     NOT COOL
Request Queuing in New Relic

 •    Time between first ActionContoller hit - X-Queue-Start = Time spent in queuing.

Internet => LB inserts X-Queue-Start => Nginx => Ruby Webserver => Rack =>
Application

Track Rack Middleware as well

def call(env)
  env["HTTP_X_MIDDLEWARE_START"] = "t=#{(Time.now.to_f * 1000000).to_i}"
  @app.call(env)
end
CACHING
Cache Everything


   Rails makes it
   stupid easy to
 cache everything.
            Do it.
Static Files & Nginx

   The best cache is a static file served by
                   Nginx.

# create it on #index, #show, etc..
caches_page :index

# expire it on #creates, #updates, #destory, etc...
expire_page :action => :index
A Note About Static Files:

Use the front end server.

upstream upstream_enki {
  server unix:/var/run/engineyard/unicorn_enki.sock fail_timeout=0;
}

location ~ ^/(images|assets|javascripts|stylesheets)/ {
  try_files $uri $uri/index.html /last_assets/$uri /last_assets/$uri.html
@app_enki;
  expires 10y;
}

location / {
  if (-f $document_root/system/maintenance.html) { return 503; }
    try_files $uri $uri/index.html $uri.html @app_enki;
}
Memcached: The Standard

# config/initializers/memcached.rb
config.cache_store =:mem_cache_store,
     "server-1:11211",
     "server-2:11211",
     "server-3:11211",
"server-4:11211"
Next Best: ActionCaching

Will still go through Rack/Rails, but the action gets
cached.

before_filter :make_sure_youre_ok
caches_action :all_the_things

def all_the_things
  @all_things = Thing.all_in_a_complex_way
end

def expire
  expire_action :action => :all_the_things
end
Fragment Caching


<% cache('my_cache_key') do %>
  <%= render_large_tag_cloud %>
<% end %>

...

def update_large_tag_cloud
  TagCloud.update
  expire_fragment('my_cache_key')
end
Baremetal


Rails.cache.write("john", "yerhot")
Rails.cache.read("john")# => "yerhot"

# execute a block on miss and cache it.
Rails.cache.fetch("miss") do
 "yerhot"
end
Rails.fetch("miss")# => "yerhot"

Rails.cache.exists("john") # => true
Rails.cache.delete("john") # => true
Rails.cache.exists("john") # => false
Background
Processing
Why Background Processing?

•  send email
•  process images
•  grab feeds and cache them
•  complex computations/reports
•  create/expire caches/pages (like Reddit)
Best Practice:



 Use a utility server for background
            jobs and cron.
Resque to the Rescue
Resque in New Relic
Delayed Job Too
Rails 4

Background Processing baked in.

•  Allow an application to switch job systems with minimal
   code change due to common API
•  Very basic queuing system built in
•  Roll your own wrapper class that responds to push & pop


 # application.rb
 config.queue = QueueName
 Rails.queue.push(Job.new)
Review

•  You need to be monitoring your application.

•  Performance has to be reviewed on a regular basis.

•  Database indexes are cheap, make lots of them.

•  Every application can take advantage of some level
   of caching: page, action or fragment.

•  Background any work that you can.

•  Don't neglect front-end performance.
How to Install New Relic

New Relic Standard is Free at Engine Yard

   1.  If you’re an Engine Yard Customer, select your
       plan in your Engine Yard Account Settings

   2.  Add newrelic_rpm to your Gemfile

   3.  Enable monitoring in the Engine Yard
       Dashboard


Full Installation Details: http://ey.io/install-newrelic
Questions?
Chris Kelly        John Yerhot
Thanks for   @amateurhuman
             www.newrelic.com
                                @yerhot
                                www.engineyard.com
Watching!

Weitere ähnliche Inhalte

Was ist angesagt?

Building Scalable .NET Web Applications
Building Scalable .NET Web ApplicationsBuilding Scalable .NET Web Applications
Building Scalable .NET Web ApplicationsBuu Nguyen
 
Apollo ecosystem
Apollo ecosystemApollo ecosystem
Apollo ecosystemJames Akwuh
 
Boost your website by running PHP on Nginx
Boost your website by running PHP on NginxBoost your website by running PHP on Nginx
Boost your website by running PHP on NginxHarald Zeitlhofer
 
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...Sencha
 
Building Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker SwarmBuilding Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker SwarmWei Lin
 
In Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry OsborneIn Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry OsborneEnkitec
 
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Maarten Balliauw
 
High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016Vlad Mihalcea
 
Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)
Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)
Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)Maarten Balliauw
 
Query optimization: from 0 to 10 (and up to 5.7)
Query optimization: from 0 to 10 (and up to 5.7)Query optimization: from 0 to 10 (and up to 5.7)
Query optimization: from 0 to 10 (and up to 5.7)Jaime Crespo
 
High-Performance JDBC Voxxed Bucharest 2016
High-Performance JDBC Voxxed Bucharest 2016High-Performance JDBC Voxxed Bucharest 2016
High-Performance JDBC Voxxed Bucharest 2016Vlad Mihalcea
 
Streamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache AmbariStreamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache AmbariAlejandro Fernandez
 
Tuning Apache Ambari Performance for Big Data at Scale with 3,000 Agents
Tuning Apache Ambari Performance for Big Data at Scale with 3,000 AgentsTuning Apache Ambari Performance for Big Data at Scale with 3,000 Agents
Tuning Apache Ambari Performance for Big Data at Scale with 3,000 AgentsAlejandro Fernandez
 
Scaling up task processing with Celery
Scaling up task processing with CeleryScaling up task processing with Celery
Scaling up task processing with CeleryNicolas Grasset
 
MySQL Query Optimization
MySQL Query OptimizationMySQL Query Optimization
MySQL Query OptimizationMorgan Tocker
 
Performance Schema for MySQL troubleshooting
Performance Schema for MySQL troubleshootingPerformance Schema for MySQL troubleshooting
Performance Schema for MySQL troubleshootingSveta Smirnova
 

Was ist angesagt? (20)

Building Scalable .NET Web Applications
Building Scalable .NET Web ApplicationsBuilding Scalable .NET Web Applications
Building Scalable .NET Web Applications
 
Apollo ecosystem
Apollo ecosystemApollo ecosystem
Apollo ecosystem
 
Boost your website by running PHP on Nginx
Boost your website by running PHP on NginxBoost your website by running PHP on Nginx
Boost your website by running PHP on Nginx
 
Running PHP on Nginx
Running PHP on NginxRunning PHP on Nginx
Running PHP on Nginx
 
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...
SenchaCon 2016: Upgrading an Ext JS 4.x Application to Ext JS 6.x - Mark Linc...
 
Building Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker SwarmBuilding Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker Swarm
 
In Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry OsborneIn Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry Osborne
 
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...
 
High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016
 
Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)
Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)
Get more than a cache back! The Microsoft Azure Redis Cache (NDC Oslo)
 
Query optimization: from 0 to 10 (and up to 5.7)
Query optimization: from 0 to 10 (and up to 5.7)Query optimization: from 0 to 10 (and up to 5.7)
Query optimization: from 0 to 10 (and up to 5.7)
 
High-Performance JDBC Voxxed Bucharest 2016
High-Performance JDBC Voxxed Bucharest 2016High-Performance JDBC Voxxed Bucharest 2016
High-Performance JDBC Voxxed Bucharest 2016
 
Streamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache AmbariStreamline Hadoop DevOps with Apache Ambari
Streamline Hadoop DevOps with Apache Ambari
 
Tuning Apache Ambari Performance for Big Data at Scale with 3,000 Agents
Tuning Apache Ambari Performance for Big Data at Scale with 3,000 AgentsTuning Apache Ambari Performance for Big Data at Scale with 3,000 Agents
Tuning Apache Ambari Performance for Big Data at Scale with 3,000 Agents
 
Scaling up task processing with Celery
Scaling up task processing with CeleryScaling up task processing with Celery
Scaling up task processing with Celery
 
Introduction to Flask Micro Framework
Introduction to Flask Micro FrameworkIntroduction to Flask Micro Framework
Introduction to Flask Micro Framework
 
MySQL Query Optimization
MySQL Query OptimizationMySQL Query Optimization
MySQL Query Optimization
 
Performance Schema for MySQL troubleshooting
Performance Schema for MySQL troubleshootingPerformance Schema for MySQL troubleshooting
Performance Schema for MySQL troubleshooting
 
Awr doag
Awr doagAwr doag
Awr doag
 
HiveServer2
HiveServer2HiveServer2
HiveServer2
 

Andere mochten auch

Engine Yard Cloud Architecture Enhancements
Engine Yard Cloud Architecture EnhancementsEngine Yard Cloud Architecture Enhancements
Engine Yard Cloud Architecture EnhancementsEngine Yard
 
Simplifying PCI on a PaaS Environment
Simplifying PCI on a PaaS EnvironmentSimplifying PCI on a PaaS Environment
Simplifying PCI on a PaaS EnvironmentEngine Yard
 
IRCE 2016 Speaking Session – The Small Things That Add Up: How to Find What D...
IRCE 2016 Speaking Session – The Small Things That Add Up: How to Find What D...IRCE 2016 Speaking Session – The Small Things That Add Up: How to Find What D...
IRCE 2016 Speaking Session – The Small Things That Add Up: How to Find What D...SOASTA
 
Rewriting The Revenue Rules: From Mobile-First To Mobile-Only Mobile Shopping...
Rewriting The Revenue Rules: From Mobile-First To Mobile-Only Mobile Shopping...Rewriting The Revenue Rules: From Mobile-First To Mobile-Only Mobile Shopping...
Rewriting The Revenue Rules: From Mobile-First To Mobile-Only Mobile Shopping...SOASTA
 
Using JMeter in CloudTest for Continuous Testing
Using JMeter in CloudTest for Continuous TestingUsing JMeter in CloudTest for Continuous Testing
Using JMeter in CloudTest for Continuous TestingSOASTA
 
Soasta | CloudBees webinar 11/12/2015
Soasta | CloudBees webinar 11/12/2015Soasta | CloudBees webinar 11/12/2015
Soasta | CloudBees webinar 11/12/2015SOASTA
 
DPM in Pictures
DPM in PicturesDPM in Pictures
DPM in PicturesSOASTA
 
Reinventing the Modern Information Pipeline: Paxata and MapR
Reinventing the Modern Information Pipeline: Paxata and MapRReinventing the Modern Information Pipeline: Paxata and MapR
Reinventing the Modern Information Pipeline: Paxata and MapRLilia Gutnik
 
Aws vs. Azure: 5 Things You Need To Know
Aws vs. Azure: 5 Things You Need To KnowAws vs. Azure: 5 Things You Need To Know
Aws vs. Azure: 5 Things You Need To KnowScalr
 
Engine Yard Partner Program 2014
Engine Yard Partner Program 2014Engine Yard Partner Program 2014
Engine Yard Partner Program 2014Engine Yard
 
Slack presentation
Slack presentationSlack presentation
Slack presentationblevz
 

Andere mochten auch (18)

Cohodatawebinar
Cohodatawebinar Cohodatawebinar
Cohodatawebinar
 
Engine Yard Cloud Architecture Enhancements
Engine Yard Cloud Architecture EnhancementsEngine Yard Cloud Architecture Enhancements
Engine Yard Cloud Architecture Enhancements
 
Simplifying PCI on a PaaS Environment
Simplifying PCI on a PaaS EnvironmentSimplifying PCI on a PaaS Environment
Simplifying PCI on a PaaS Environment
 
Geemus
GeemusGeemus
Geemus
 
Slack
SlackSlack
Slack
 
IRCE 2016 Speaking Session – The Small Things That Add Up: How to Find What D...
IRCE 2016 Speaking Session – The Small Things That Add Up: How to Find What D...IRCE 2016 Speaking Session – The Small Things That Add Up: How to Find What D...
IRCE 2016 Speaking Session – The Small Things That Add Up: How to Find What D...
 
Rewriting The Revenue Rules: From Mobile-First To Mobile-Only Mobile Shopping...
Rewriting The Revenue Rules: From Mobile-First To Mobile-Only Mobile Shopping...Rewriting The Revenue Rules: From Mobile-First To Mobile-Only Mobile Shopping...
Rewriting The Revenue Rules: From Mobile-First To Mobile-Only Mobile Shopping...
 
Scalr Demo
Scalr DemoScalr Demo
Scalr Demo
 
Using JMeter in CloudTest for Continuous Testing
Using JMeter in CloudTest for Continuous TestingUsing JMeter in CloudTest for Continuous Testing
Using JMeter in CloudTest for Continuous Testing
 
Soasta | CloudBees webinar 11/12/2015
Soasta | CloudBees webinar 11/12/2015Soasta | CloudBees webinar 11/12/2015
Soasta | CloudBees webinar 11/12/2015
 
DPM in Pictures
DPM in PicturesDPM in Pictures
DPM in Pictures
 
Prezi
PreziPrezi
Prezi
 
Reinventing the Modern Information Pipeline: Paxata and MapR
Reinventing the Modern Information Pipeline: Paxata and MapRReinventing the Modern Information Pipeline: Paxata and MapR
Reinventing the Modern Information Pipeline: Paxata and MapR
 
Prezi slideshare
Prezi slidesharePrezi slideshare
Prezi slideshare
 
Aws vs. Azure: 5 Things You Need To Know
Aws vs. Azure: 5 Things You Need To KnowAws vs. Azure: 5 Things You Need To Know
Aws vs. Azure: 5 Things You Need To Know
 
Engine Yard Partner Program 2014
Engine Yard Partner Program 2014Engine Yard Partner Program 2014
Engine Yard Partner Program 2014
 
Slack
SlackSlack
Slack
 
Slack presentation
Slack presentationSlack presentation
Slack presentation
 

Ähnlich wie 6 tips for improving ruby performance

Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Pavel Chunyayev
 
Intro to-rails-webperf
Intro to-rails-webperfIntro to-rails-webperf
Intro to-rails-webperfNew Relic
 
Ebs dba con4696_pdf_4696_0001
Ebs dba con4696_pdf_4696_0001Ebs dba con4696_pdf_4696_0001
Ebs dba con4696_pdf_4696_0001jucaab
 
SharePoint 2013 Performance Analysis - Robi Vončina
SharePoint 2013 Performance Analysis - Robi VončinaSharePoint 2013 Performance Analysis - Robi Vončina
SharePoint 2013 Performance Analysis - Robi VončinaSPC Adriatics
 
AAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
AAI-3218 Production Deployment Best Practices for WebSphere Liberty ProfileAAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
AAI-3218 Production Deployment Best Practices for WebSphere Liberty ProfileWASdev Community
 
Become a Performance Diagnostics Hero
Become a Performance Diagnostics HeroBecome a Performance Diagnostics Hero
Become a Performance Diagnostics HeroTechWell
 
Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...
Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...
Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...Andrejs Prokopjevs
 
Monitoring in Motion: Monitoring Containers and Amazon ECS
Monitoring in Motion: Monitoring Containers and Amazon ECSMonitoring in Motion: Monitoring Containers and Amazon ECS
Monitoring in Motion: Monitoring Containers and Amazon ECSAmazon Web Services
 
Performance Optimization of Rails Applications
Performance Optimization of Rails ApplicationsPerformance Optimization of Rails Applications
Performance Optimization of Rails ApplicationsSerge Smetana
 
제3회난공불락 오픈소스 인프라세미나 - MySQL Performance
제3회난공불락 오픈소스 인프라세미나 - MySQL Performance제3회난공불락 오픈소스 인프라세미나 - MySQL Performance
제3회난공불락 오픈소스 인프라세미나 - MySQL PerformanceTommy Lee
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersoazabir
 
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...Amazon Web Services
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindSam Keen
 
Clug 2012 March web server optimisation
Clug 2012 March   web server optimisationClug 2012 March   web server optimisation
Clug 2012 March web server optimisationgrooverdan
 
20160307 apex connects_jira
20160307 apex connects_jira20160307 apex connects_jira
20160307 apex connects_jiraMT AG
 
Effectively Deploying MongoDB on AEM
Effectively Deploying MongoDB on AEMEffectively Deploying MongoDB on AEM
Effectively Deploying MongoDB on AEMNorberto Leite
 
Application Performance Troubleshooting 1x1 - Part 2 - Noch mehr Schweine und...
Application Performance Troubleshooting 1x1 - Part 2 - Noch mehr Schweine und...Application Performance Troubleshooting 1x1 - Part 2 - Noch mehr Schweine und...
Application Performance Troubleshooting 1x1 - Part 2 - Noch mehr Schweine und...rschuppe
 
Presentation of OrientDB v2.2 - Webinar
Presentation of OrientDB v2.2 - WebinarPresentation of OrientDB v2.2 - Webinar
Presentation of OrientDB v2.2 - WebinarOrient Technologies
 
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014Amazon Web Services
 

Ähnlich wie 6 tips for improving ruby performance (20)

Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015
 
Intro to-rails-webperf
Intro to-rails-webperfIntro to-rails-webperf
Intro to-rails-webperf
 
Ebs dba con4696_pdf_4696_0001
Ebs dba con4696_pdf_4696_0001Ebs dba con4696_pdf_4696_0001
Ebs dba con4696_pdf_4696_0001
 
Iac d.damyanov 4.pptx
Iac d.damyanov 4.pptxIac d.damyanov 4.pptx
Iac d.damyanov 4.pptx
 
SharePoint 2013 Performance Analysis - Robi Vončina
SharePoint 2013 Performance Analysis - Robi VončinaSharePoint 2013 Performance Analysis - Robi Vončina
SharePoint 2013 Performance Analysis - Robi Vončina
 
AAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
AAI-3218 Production Deployment Best Practices for WebSphere Liberty ProfileAAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
AAI-3218 Production Deployment Best Practices for WebSphere Liberty Profile
 
Become a Performance Diagnostics Hero
Become a Performance Diagnostics HeroBecome a Performance Diagnostics Hero
Become a Performance Diagnostics Hero
 
Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...
Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...
Optimize DR and Cloning with Logical Hostnames in Oracle E-Business Suite (OA...
 
Monitoring in Motion: Monitoring Containers and Amazon ECS
Monitoring in Motion: Monitoring Containers and Amazon ECSMonitoring in Motion: Monitoring Containers and Amazon ECS
Monitoring in Motion: Monitoring Containers and Amazon ECS
 
Performance Optimization of Rails Applications
Performance Optimization of Rails ApplicationsPerformance Optimization of Rails Applications
Performance Optimization of Rails Applications
 
제3회난공불락 오픈소스 인프라세미나 - MySQL Performance
제3회난공불락 오픈소스 인프라세미나 - MySQL Performance제3회난공불락 오픈소스 인프라세미나 - MySQL Performance
제3회난공불락 오픈소스 인프라세미나 - MySQL Performance
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of users
 
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / Webgrind
 
Clug 2012 March web server optimisation
Clug 2012 March   web server optimisationClug 2012 March   web server optimisation
Clug 2012 March web server optimisation
 
20160307 apex connects_jira
20160307 apex connects_jira20160307 apex connects_jira
20160307 apex connects_jira
 
Effectively Deploying MongoDB on AEM
Effectively Deploying MongoDB on AEMEffectively Deploying MongoDB on AEM
Effectively Deploying MongoDB on AEM
 
Application Performance Troubleshooting 1x1 - Part 2 - Noch mehr Schweine und...
Application Performance Troubleshooting 1x1 - Part 2 - Noch mehr Schweine und...Application Performance Troubleshooting 1x1 - Part 2 - Noch mehr Schweine und...
Application Performance Troubleshooting 1x1 - Part 2 - Noch mehr Schweine und...
 
Presentation of OrientDB v2.2 - Webinar
Presentation of OrientDB v2.2 - WebinarPresentation of OrientDB v2.2 - Webinar
Presentation of OrientDB v2.2 - Webinar
 
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
 

Mehr von Engine Yard

Getting Started with PHP on Engine Yard Cloud
Getting Started with PHP on Engine Yard CloudGetting Started with PHP on Engine Yard Cloud
Getting Started with PHP on Engine Yard CloudEngine Yard
 
The Tao of Documentation
The Tao of DocumentationThe Tao of Documentation
The Tao of DocumentationEngine Yard
 
Innovate Faster in the Cloud with a Platform as a Service
Innovate Faster in the Cloud with a Platform as a ServiceInnovate Faster in the Cloud with a Platform as a Service
Innovate Faster in the Cloud with a Platform as a ServiceEngine Yard
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to RubyEngine Yard
 
JRuby: Enhancing Java Developers Lives
JRuby: Enhancing Java Developers LivesJRuby: Enhancing Java Developers Lives
JRuby: Enhancing Java Developers LivesEngine Yard
 
High Performance Ruby: Evented vs. Threaded
High Performance Ruby: Evented vs. ThreadedHigh Performance Ruby: Evented vs. Threaded
High Performance Ruby: Evented vs. ThreadedEngine Yard
 
Release Early & Release Often: Reducing Deployment Friction
Release Early & Release Often: Reducing Deployment FrictionRelease Early & Release Often: Reducing Deployment Friction
Release Early & Release Often: Reducing Deployment FrictionEngine Yard
 
JRuby Jam Session
JRuby Jam Session JRuby Jam Session
JRuby Jam Session Engine Yard
 
Rubinius and Ruby | A Love Story
Rubinius and Ruby | A Love Story Rubinius and Ruby | A Love Story
Rubinius and Ruby | A Love Story Engine Yard
 
Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel Engine Yard
 
JRuby: Apples and Oranges
JRuby: Apples and OrangesJRuby: Apples and Oranges
JRuby: Apples and OrangesEngine Yard
 
Developing a Language
Developing a LanguageDeveloping a Language
Developing a LanguageEngine Yard
 
Debugging Ruby Systems
Debugging Ruby SystemsDebugging Ruby Systems
Debugging Ruby SystemsEngine Yard
 
Everything Rubinius
Everything RubiniusEverything Rubinius
Everything RubiniusEngine Yard
 
Rails Hosting and the Woes
Rails Hosting and the WoesRails Hosting and the Woes
Rails Hosting and the WoesEngine Yard
 

Mehr von Engine Yard (15)

Getting Started with PHP on Engine Yard Cloud
Getting Started with PHP on Engine Yard CloudGetting Started with PHP on Engine Yard Cloud
Getting Started with PHP on Engine Yard Cloud
 
The Tao of Documentation
The Tao of DocumentationThe Tao of Documentation
The Tao of Documentation
 
Innovate Faster in the Cloud with a Platform as a Service
Innovate Faster in the Cloud with a Platform as a ServiceInnovate Faster in the Cloud with a Platform as a Service
Innovate Faster in the Cloud with a Platform as a Service
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
JRuby: Enhancing Java Developers Lives
JRuby: Enhancing Java Developers LivesJRuby: Enhancing Java Developers Lives
JRuby: Enhancing Java Developers Lives
 
High Performance Ruby: Evented vs. Threaded
High Performance Ruby: Evented vs. ThreadedHigh Performance Ruby: Evented vs. Threaded
High Performance Ruby: Evented vs. Threaded
 
Release Early & Release Often: Reducing Deployment Friction
Release Early & Release Often: Reducing Deployment FrictionRelease Early & Release Often: Reducing Deployment Friction
Release Early & Release Often: Reducing Deployment Friction
 
JRuby Jam Session
JRuby Jam Session JRuby Jam Session
JRuby Jam Session
 
Rubinius and Ruby | A Love Story
Rubinius and Ruby | A Love Story Rubinius and Ruby | A Love Story
Rubinius and Ruby | A Love Story
 
Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel
 
JRuby: Apples and Oranges
JRuby: Apples and OrangesJRuby: Apples and Oranges
JRuby: Apples and Oranges
 
Developing a Language
Developing a LanguageDeveloping a Language
Developing a Language
 
Debugging Ruby Systems
Debugging Ruby SystemsDebugging Ruby Systems
Debugging Ruby Systems
 
Everything Rubinius
Everything RubiniusEverything Rubinius
Everything Rubinius
 
Rails Hosting and the Woes
Rails Hosting and the WoesRails Hosting and the Woes
Rails Hosting and the Woes
 

Kürzlich hochgeladen

Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 

Kürzlich hochgeladen (20)

Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 

6 tips for improving ruby performance

  • 1. In Today’s Session You Will Learn how to: •  Gain visibility on site performance •  Improve scalability and uptime •  Find and fix key bottlenecks
  • 2. New Relic + Engine Yard •  Database •  Web Servers •  Caching •  Background Processing
  • 6. Database Performance Lazy loading associated data can quickly lead to an N+1 query problem. ORMs (ActiveRecord, DataMapper, etc.) make it easy to get our data but also make it easy to forget to optimize and refactor. N+1 problems are hard to spot in development since you are working with limited data sets.
  • 7. N+1 Query Creep # app/models/customer.rb class Customer < ActiveRecord::Base has_many :addresses end # app/models/address.rb class Address < ActiveRecord::Base belongs_to :customer end # app/controllers/customers_controller.rb class CustomersController < ApplicationController def index @customers = Customer.all end end # app/views/customers/index.html.erb <% @customers.each do |customer| %> <%= content_tag :h1, customer.name %> <% end %>
  • 8. N+1 Query Creep # app/views/customers/index.html.erb <% @customers.each do |customer| %> <%= content_tag :h1, customer.name %> <%= content_tag :h2, customer.addresses.first.city %> <% end %> If @customers has 100 records, you'll have 101 queries: SELECT "customers".* FROM "customers" SELECT "addresses".* FROM "addresses" WHERE "addresses"."customer_id" = 1 AND "addresses"."primary" = 't' LIMIT 1 SELECT "addresses".* FROM "addresses" WHERE "addresses"."customer_id" = 2 AND "addresses"."primary" = 't' LIMIT 1 SELECT "addresses".* FROM "addresses" WHERE "addresses"."customer_id" = 3 AND "addresses"."primary" = 't' LIMIT 1 ... ... SELECT "addresses".* FROM "addresses" WHERE "addresses"."customer_id" = 100 AND "addresses"."primary" = 't' LIMIT 1
  • 9. Eager Loading with .includes # app/controllers/customers_controller.rb class CustomersController < ApplicationController def index @customers = Customer.includes(:addresses).all end end If @customers has 100 records, now we only have 2 queries: SELECT "customers".* FROM "customers" SELECT "addresses".* FROM "addresses" WHERE "addresses"."customer_id" IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100)
  • 10. Finding N+1 in New Relic New Relic > App Server > Web Transactions > Performance Breakdown
  • 11. Missing Indexes == Slow Queries
  • 12. Adding an Index is Simple # db/migrate/20120201040247_add_index_for_shop_id_on_orders.rb class AddIndexForShopIdOnOrders < ActiveRecord::Migration def change add_index :orders, :shop_id end end Index Protips: •  Searching an index on a table with 1,000 rows is 100x faster than searching a table without an index. •  Put an index on any columns you will likely query against, it's better to have too many than too few indexes. •  Adding an index to a table will lock the table!
  • 14. Passenger 3 •  Simple to operate •  Simple configuration •  Handles worker management •  Great for multi-application environments •  Great for low resource environments •  Attached to Nginx/Apache HTTPD
  • 15. Passenger Request Queue solo i-c3f2d8a2 ~ # passenger-status ----------- General information ----------- max = 3 count = 3 active = 0 inactive = 3 Waiting on global queue: 0 ----------- Application groups ----------- /data/john_yerhot_org/current: App root: /data/john_yerhot_org/current * PID: 19802 Sessions: 0 Processed: 3 Uptime: 3h 10m 13s /data/scalingrails/current: App root: /data/scalingrails/current * PID: 28726 Sessions: 0 Processed: 3 Uptime: 59m 22s /data/sites/clmeisinger/current: App root: /data/sites/clmeisinger/current * PID: 22147 Sessions: 0 Processed: 70 Uptime: 10h 45m 57s
  • 16. Unicorn •  Independent of front end web server •  More configuration options •  Master process will reap children on timeout •  Great for single application environments •  Allows for zero downtime deploys
  • 17. Unicorn Request Queue? Raindrops solo i-5b74313d ~ # gem install raindrops Fetching: raindrops-0.10.0.gem (100%) Building native extensions. This could take a while... Successfully installed raindrops-0.10.0 1 gem installed solo i-5b74313d ~ # ruby -rubygems -e "require 'raindrops'; puts Raindrops::Linux.unix_listener_stats(['/var/run/engineyard/ unicorn_appname.sock']).inspect" {"/var/run/engineyard/unicorn_appname.sock"=>#<struct Raindrops::ListenStats active=0, queued=0>}
  • 18. Request Queuing in New Relic
  • 19. Request Queuing in New Relic NOT COOL
  • 20. Request Queuing in New Relic •  Time between first ActionContoller hit - X-Queue-Start = Time spent in queuing. Internet => LB inserts X-Queue-Start => Nginx => Ruby Webserver => Rack => Application Track Rack Middleware as well def call(env) env["HTTP_X_MIDDLEWARE_START"] = "t=#{(Time.now.to_f * 1000000).to_i}" @app.call(env) end
  • 22. Cache Everything Rails makes it stupid easy to cache everything. Do it.
  • 23. Static Files & Nginx The best cache is a static file served by Nginx. # create it on #index, #show, etc.. caches_page :index # expire it on #creates, #updates, #destory, etc... expire_page :action => :index
  • 24. A Note About Static Files: Use the front end server. upstream upstream_enki { server unix:/var/run/engineyard/unicorn_enki.sock fail_timeout=0; } location ~ ^/(images|assets|javascripts|stylesheets)/ { try_files $uri $uri/index.html /last_assets/$uri /last_assets/$uri.html @app_enki; expires 10y; } location / { if (-f $document_root/system/maintenance.html) { return 503; } try_files $uri $uri/index.html $uri.html @app_enki; }
  • 25. Memcached: The Standard # config/initializers/memcached.rb config.cache_store =:mem_cache_store, "server-1:11211", "server-2:11211", "server-3:11211", "server-4:11211"
  • 26. Next Best: ActionCaching Will still go through Rack/Rails, but the action gets cached. before_filter :make_sure_youre_ok caches_action :all_the_things def all_the_things @all_things = Thing.all_in_a_complex_way end def expire expire_action :action => :all_the_things end
  • 27. Fragment Caching <% cache('my_cache_key') do %> <%= render_large_tag_cloud %> <% end %> ... def update_large_tag_cloud TagCloud.update expire_fragment('my_cache_key') end
  • 28. Baremetal Rails.cache.write("john", "yerhot") Rails.cache.read("john")# => "yerhot" # execute a block on miss and cache it. Rails.cache.fetch("miss") do "yerhot" end Rails.fetch("miss")# => "yerhot" Rails.cache.exists("john") # => true Rails.cache.delete("john") # => true Rails.cache.exists("john") # => false
  • 30. Why Background Processing? •  send email •  process images •  grab feeds and cache them •  complex computations/reports •  create/expire caches/pages (like Reddit)
  • 31. Best Practice: Use a utility server for background jobs and cron.
  • 32. Resque to the Rescue
  • 33. Resque in New Relic
  • 35. Rails 4 Background Processing baked in. •  Allow an application to switch job systems with minimal code change due to common API •  Very basic queuing system built in •  Roll your own wrapper class that responds to push & pop # application.rb config.queue = QueueName Rails.queue.push(Job.new)
  • 36. Review •  You need to be monitoring your application. •  Performance has to be reviewed on a regular basis. •  Database indexes are cheap, make lots of them. •  Every application can take advantage of some level of caching: page, action or fragment. •  Background any work that you can. •  Don't neglect front-end performance.
  • 37. How to Install New Relic New Relic Standard is Free at Engine Yard 1.  If you’re an Engine Yard Customer, select your plan in your Engine Yard Account Settings 2.  Add newrelic_rpm to your Gemfile 3.  Enable monitoring in the Engine Yard Dashboard Full Installation Details: http://ey.io/install-newrelic
  • 39. Chris Kelly John Yerhot Thanks for @amateurhuman www.newrelic.com @yerhot www.engineyard.com Watching!