SlideShare una empresa de Scribd logo
1 de 52
November 17, 2011

Building Faster Websites:
    Optimizing the Server
                    Jonathan Klein
               jklein@wayfair.com
                    @jonathanklein
Agenda
  Who Am I?

  Why Server Side Performance Matters

  Measuring Performance

  Speeding up the Server

  Improving the Database

  Load Testing
Who is this Guy?

• Senior Software Engineer/Performance Guy at Wayfair

• Organizer - Boston Web Performance Meetup Group

• Organizer - #WPOChat (monthly Twitter chat)




• Wayfair Stats:
   1.   ~1400 requests/sec for static content
   2.   ~400 requests/sec for dynamic content
   3.   ~10 million unique visitors per month
   4.   On a typical Monday we serve 75,000,000 static files



                                                               3
Wayfair Stack Changes

• Windows Server  FreeBSD

• IIS  Lighttpd

• Classic ASP  PHP

• But we are still on MSSQL (more on that later)

• http://engineering.wayfair.com




                                                   4
Why Server Side Performance?
Doesn’t 80% happen on the client?

•   Yes, but not if your server is slow
•   Users staring at a blank page
•   No upper limit
•   HUGE spikes




• Plus, bots crawl fast sites more

                                          7
Time to first byte




  Time To First Byte (TTFB) Matters




                                      8
How Do We Measure It?
Server Side Monitoring

Lots of Options:
• Paid:
   1. Coradiant
   2. dynaTrace
   3. Correlsense
        • http://www.real-user-monitoring.com/ - Free Version


• Free:
   1.   StatsD/Graphite
   2.   Access Logs
   3.   Nagios
   4.   Ganglia
   5.   Hosted WebPagetest
   6.   Selenium/dynaTrace Ajax Edition


                                                                10
Or Something Simple…

<?php
$start = microtime(true);

…script content…

$end   = microtime(true);

do_stuff('Description', $end - $start);
?>



                                          11
do_stuff()?

• do_stuff() can do one of:
  1. Log to a database (not ideal)

  2. Write to a text file (eww)

  3. Make a StatsD call over UDP (good) -
     http://codeascraft.etsy.com/2011/02/15/measure-
     anything-measure-everything/

  4. Choose your own adventure

                                                       12
Averages can be misleading

Better to look at percentiles




                                14
What Does a Scalability Problem Look Like?
This:




        19
Or maybe this!




                 20
Much better!




               21
So How Do We Do It?
What can you do?

• Start with the Database

• Run a database trace
   1. Filter: Queries > 50ms
   2. Filter: Reads > 1000
   3. Start with the worst ones and optimize




                                               23
What does “Optimize” mean?

• Look at execution plan
   1. Remove calls to remote servers




                                       24
Database Optimizations

• Reduce Joins
• Select * from  Select Foo, Bar, Baz from…
• Minimize/consolidate subqueries
• Add indexes where needed
   1. We added one index: Procedure dropped
      from 3.5 sec & 4500 reads to .06 sec and 130
      reads!
• Be careful with where clauses (don’t
  calculate stuff in them)


                                                     25
Example

SELECT id, name, salary
FROM employee
WHERE salary < 25000;

NOT

SELECT id, name, salary
FROM employee
WHERE salary + 10000 < 35000;



                                26
Example

SELECT id, name, salary
FROM employee
WHERE salary < 25000;

NOT

SELECT id, name, salary
FROM employee
WHERE salary + 10000 < 35000;



                                27
Not many hard and fast rules…

• Try something, look at the plan

• Try something else…look at how the plan changes

• This is your friend:




                                                    28
The Fastest DB Query is the
       One You Don’t Make
Memcached

• Caching layer between database and webserver




• Can hold PHP objects and arrays



                                                 30
Memcached

$m = new Memcached();
$m->pconnect(‘1.2.3.4', 11211);




$m->set(‘foo’, $bar, 600);

$baz = $m->get(‘foo’);



                                  31
Install APC

• APC – Alternative PHP Cache
  1. Opcode Cache
  2. User Cache
  3. Awesome!




                                32
Opcode Cache




               33
User Cache

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

Outputs…

string(3) "BAR"



                              34
PHP Code Optimizations
PHP Optimizations

• Set the max loop value before the loop:
  $max = count($rows);
  for ($i = 0; $i < $max; $i++) {
      echo $i;
  }
• require_once() is slow
• Minimize use of define()
• Yes, single quotes are slightly faster than double
  quotes, but…



                                                       36
PHP Optimizations have limited value

• Could go on and on…
  1.http://www.wmtips.com/php/tips-
    optimizing-php-code.htm

• Minimal returns

• Find the hotspots in your application and fix
  them




                                                  37
Example…

• Homepage takes 5 seconds to load

• Optimize PHP…
  1. Reduce PHP execution time by 50%!

• But wait! PHP execution was only taking 100ms
  1. Saves you 50ms in load time
  2. 1% of total page load




                                                  38
If you really need to make your code faster…

• HipHop for PHP

• Built by Facebook and Open Sourced

• Compiles PHP into C++

• Currently supports PHP 5.2

• http://developers.facebook.com/blog/post/358/
• https://github.com/facebook/hiphop-php

                                                  39
Webserver Considerations
Do it right

• Pick the right one
   1. Lighttpd/Nginx instead of Apache
   2. Designed to solve the C10K problem

• Lighttpd Used By:
   1. Youtube
   2. Wikipedia
   3. Meebo




                                           41
Benefits of Lighttpd/Nginx

• Event driven model:
   “Unlike traditional servers, Nginx doesn't rely on threads to
   handle requests. Instead it uses a much more scalable event-
   driven (asynchronous) architecture. This architecture uses
   small, but more importantly, predictable amounts of memory
   under load.”
    - http://wiki.nginx.org/

• FastCGI + spawn-fcgi
   1. PHP Process Management
   2. Many child processes – scale out application tier.




                                                                   42
If you MUST use Apache

• mod_deflate
  1. Gzips content for faster transfer times

• mod_pagespeed
  1. Automatic performance improvements

• KeepAlives on
  1. Server won’t create a new connection for
     every resource


                                                43
Load Testing
JMeter

• Open Source

• Generate load via a GUI or command line

• Can watch req/s peak out

• Easy to use (just make sure you set the
  correct path to Java on your computer).



                                            45
JMeter




         46
JMeter




         48
JMeter

• Watch your User Agent

• Be careful hitting sites you don’t own

• You might tap out your local box/network
  before killing the server




                                             49
Conclusion

• Know and watch your site

• More monitoring is better

• Understand what is behind the scenes – look at
  the full stack

• Load test BEFORE things go to production –
  figure out when they will fall over



                                                   50
Questions?



             We’re Hiring!
        www.wayfair.com/careers

              Get In Touch:
www.meetup.com/Web-Performance-Boston/
          jklein@wayfair.com
            @jonathanklein




                                         51
BTV PHP - Building Fast Websites

Más contenido relacionado

La actualidad más candente

ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
Nexcess.net LLC
 
Roy foubister (hosting high traffic sites on a tight budget)
Roy foubister (hosting high traffic sites on a tight budget)Roy foubister (hosting high traffic sites on a tight budget)
Roy foubister (hosting high traffic sites on a tight budget)
WordCamp Cape Town
 
Scalable Web Architectures - Common Patterns & Approaches
Scalable Web Architectures - Common Patterns & ApproachesScalable Web Architectures - Common Patterns & Approaches
Scalable Web Architectures - Common Patterns & Approaches
Cal Henderson
 

La actualidad más candente (20)

Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i  Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i
 
My Database Skills Killed the Server
My Database Skills Killed the ServerMy Database Skills Killed the Server
My Database Skills Killed the Server
 
How Flipkart scales PHP
How Flipkart scales PHPHow Flipkart scales PHP
How Flipkart scales PHP
 
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
 
Speed Matters
Speed MattersSpeed Matters
Speed Matters
 
Automating your php infrastructure with the zend server api
Automating your php infrastructure with the zend server apiAutomating your php infrastructure with the zend server api
Automating your php infrastructure with the zend server api
 
Using Apache Camel as AKKA
Using Apache Camel as AKKAUsing Apache Camel as AKKA
Using Apache Camel as AKKA
 
PowerShell and SharePoint
PowerShell and SharePointPowerShell and SharePoint
PowerShell and SharePoint
 
Roy foubister (hosting high traffic sites on a tight budget)
Roy foubister (hosting high traffic sites on a tight budget)Roy foubister (hosting high traffic sites on a tight budget)
Roy foubister (hosting high traffic sites on a tight budget)
 
Effectively Deploying MongoDB on AEM
Effectively Deploying MongoDB on AEMEffectively Deploying MongoDB on AEM
Effectively Deploying MongoDB on AEM
 
Scale ColdFusion with Terracotta Distributed Caching for Ehchache
Scale ColdFusion with Terracotta Distributed Caching for EhchacheScale ColdFusion with Terracotta Distributed Caching for Ehchache
Scale ColdFusion with Terracotta Distributed Caching for Ehchache
 
Altitude SF 2017: The power of the network
Altitude SF 2017: The power of the networkAltitude SF 2017: The power of the network
Altitude SF 2017: The power of the network
 
Building Asynchronous Applications
Building Asynchronous ApplicationsBuilding Asynchronous Applications
Building Asynchronous Applications
 
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
SenchaCon 2016: LinkRest - Modern RESTful API Framework for Ext JS Apps - Rou...
 
Single page apps with drupal 7
Single page apps with drupal 7Single page apps with drupal 7
Single page apps with drupal 7
 
Wordpress optimization
Wordpress optimizationWordpress optimization
Wordpress optimization
 
Scalable Web Architectures - Common Patterns & Approaches
Scalable Web Architectures - Common Patterns & ApproachesScalable Web Architectures - Common Patterns & Approaches
Scalable Web Architectures - Common Patterns & Approaches
 
Best Practices for WordPress in Enterprise
Best Practices for WordPress in EnterpriseBest Practices for WordPress in Enterprise
Best Practices for WordPress in Enterprise
 
Anthony Somerset - Site Speed = Success!
Anthony Somerset - Site Speed = Success!Anthony Somerset - Site Speed = Success!
Anthony Somerset - Site Speed = Success!
 
Vladimir Ulogov - Large Scale Simulation | ZabConf2016 Lightning Talk
Vladimir Ulogov - Large Scale Simulation | ZabConf2016 Lightning TalkVladimir Ulogov - Large Scale Simulation | ZabConf2016 Lightning Talk
Vladimir Ulogov - Large Scale Simulation | ZabConf2016 Lightning Talk
 

Destacado

Riding rails for 10 years
Riding rails for 10 yearsRiding rails for 10 years
Riding rails for 10 years
jduff
 
How Shopify Scales Rails
How Shopify Scales RailsHow Shopify Scales Rails
How Shopify Scales Rails
jduff
 

Destacado (17)

Internet retailer
Internet retailerInternet retailer
Internet retailer
 
Wayfair Deck
Wayfair DeckWayfair Deck
Wayfair Deck
 
Riding rails for 10 years
Riding rails for 10 yearsRiding rails for 10 years
Riding rails for 10 years
 
JSDay 2013 - Practical Responsive Web Design
JSDay 2013 - Practical Responsive Web DesignJSDay 2013 - Practical Responsive Web Design
JSDay 2013 - Practical Responsive Web Design
 
UXFest - RUM Distillation 101
UXFest - RUM Distillation 101UXFest - RUM Distillation 101
UXFest - RUM Distillation 101
 
Edge Conf Rendering Performance Panel
Edge Conf Rendering Performance PanelEdge Conf Rendering Performance Panel
Edge Conf Rendering Performance Panel
 
EscConf - Deep Dive Frontend Optimization
EscConf - Deep Dive Frontend OptimizationEscConf - Deep Dive Frontend Optimization
EscConf - Deep Dive Frontend Optimization
 
DIY Synthetic: Private WebPagetest Magic
DIY Synthetic: Private WebPagetest MagicDIY Synthetic: Private WebPagetest Magic
DIY Synthetic: Private WebPagetest Magic
 
PHP On Steroids
PHP On SteroidsPHP On Steroids
PHP On Steroids
 
PHPDay 2013 - High Performance PHP
PHPDay 2013 - High Performance PHPPHPDay 2013 - High Performance PHP
PHPDay 2013 - High Performance PHP
 
Northeast PHP - High Performance PHP
Northeast PHP - High Performance PHPNortheast PHP - High Performance PHP
Northeast PHP - High Performance PHP
 
Scaling PHP to 40 Million Uniques
Scaling PHP to 40 Million UniquesScaling PHP to 40 Million Uniques
Scaling PHP to 40 Million Uniques
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 
PHP UK 2017 - Don't Lose Sleep - Secure Your REST
PHP UK 2017 - Don't Lose Sleep - Secure Your RESTPHP UK 2017 - Don't Lose Sleep - Secure Your REST
PHP UK 2017 - Don't Lose Sleep - Secure Your REST
 
How Slow Load Times Hurt Your Bottom Line (And 17 Things You Can Do to Fix It)
How Slow Load Times Hurt Your Bottom Line (And 17 Things You Can Do to Fix It)How Slow Load Times Hurt Your Bottom Line (And 17 Things You Can Do to Fix It)
How Slow Load Times Hurt Your Bottom Line (And 17 Things You Can Do to Fix It)
 
How Shopify Scales Rails
How Shopify Scales RailsHow Shopify Scales Rails
How Shopify Scales Rails
 
Improving PHP Application Performance with APC
Improving PHP Application Performance with APCImproving PHP Application Performance with APC
Improving PHP Application Performance with APC
 

Similar a BTV PHP - Building Fast Websites

My site is slow
My site is slowMy site is slow
My site is slow
hernanibf
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
xlight
 
Gearman - Northeast PHP 2012
Gearman - Northeast PHP 2012Gearman - Northeast PHP 2012
Gearman - Northeast PHP 2012
Mike Willbanks
 

Similar a BTV PHP - Building Fast Websites (20)

Top ten-list
Top ten-listTop ten-list
Top ten-list
 
My Site is slow - Drupal Camp London 2013
My Site is slow - Drupal Camp London 2013My Site is slow - Drupal Camp London 2013
My Site is slow - Drupal Camp London 2013
 
My site is slow
My site is slowMy site is slow
My site is slow
 
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
 
Cvcc performance tuning
Cvcc performance tuningCvcc performance tuning
Cvcc performance tuning
 
Optimizing performance
Optimizing performanceOptimizing performance
Optimizing performance
 
Do you queue
Do you queueDo you queue
Do you queue
 
Chirp 2010: Scaling Twitter
Chirp 2010: Scaling TwitterChirp 2010: Scaling Twitter
Chirp 2010: Scaling Twitter
 
WordPress Speed & Performance from Pagely's CTO
WordPress Speed & Performance from Pagely's CTOWordPress Speed & Performance from Pagely's CTO
WordPress Speed & Performance from Pagely's CTO
 
Fixing twitter
Fixing twitterFixing twitter
Fixing twitter
 
Fixing_Twitter
Fixing_TwitterFixing_Twitter
Fixing_Twitter
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
 
Performance Benchmarking: Tips, Tricks, and Lessons Learned
Performance Benchmarking: Tips, Tricks, and Lessons LearnedPerformance Benchmarking: Tips, Tricks, and Lessons Learned
Performance Benchmarking: Tips, Tricks, and Lessons Learned
 
ICONUK 2016: Back From the Dead: How Bad Code Kills a Good Server
ICONUK 2016: Back From the Dead: How Bad Code Kills a Good ServerICONUK 2016: Back From the Dead: How Bad Code Kills a Good Server
ICONUK 2016: Back From the Dead: How Bad Code Kills a Good Server
 
Performance tuning the Spring Pet Clinic sample application
Performance tuning the Spring Pet Clinic sample applicationPerformance tuning the Spring Pet Clinic sample application
Performance tuning the Spring Pet Clinic sample application
 
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
 
John adams talk cloudy
John adams   talk cloudyJohn adams   talk cloudy
John adams talk cloudy
 
Gearman - Northeast PHP 2012
Gearman - Northeast PHP 2012Gearman - Northeast PHP 2012
Gearman - Northeast PHP 2012
 
Hadoop Demystified + Automation Smackdown! Austin JUG June 24 2014
Hadoop Demystified + Automation Smackdown!  Austin JUG June 24 2014Hadoop Demystified + Automation Smackdown!  Austin JUG June 24 2014
Hadoop Demystified + Automation Smackdown! Austin JUG June 24 2014
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 

BTV PHP - Building Fast Websites

  • 1. November 17, 2011 Building Faster Websites: Optimizing the Server Jonathan Klein jklein@wayfair.com @jonathanklein
  • 2. Agenda Who Am I? Why Server Side Performance Matters Measuring Performance Speeding up the Server Improving the Database Load Testing
  • 3. Who is this Guy? • Senior Software Engineer/Performance Guy at Wayfair • Organizer - Boston Web Performance Meetup Group • Organizer - #WPOChat (monthly Twitter chat) • Wayfair Stats: 1. ~1400 requests/sec for static content 2. ~400 requests/sec for dynamic content 3. ~10 million unique visitors per month 4. On a typical Monday we serve 75,000,000 static files 3
  • 4. Wayfair Stack Changes • Windows Server  FreeBSD • IIS  Lighttpd • Classic ASP  PHP • But we are still on MSSQL (more on that later) • http://engineering.wayfair.com 4
  • 5.
  • 6. Why Server Side Performance?
  • 7. Doesn’t 80% happen on the client? • Yes, but not if your server is slow • Users staring at a blank page • No upper limit • HUGE spikes • Plus, bots crawl fast sites more 7
  • 8. Time to first byte Time To First Byte (TTFB) Matters 8
  • 9. How Do We Measure It?
  • 10. Server Side Monitoring Lots of Options: • Paid: 1. Coradiant 2. dynaTrace 3. Correlsense • http://www.real-user-monitoring.com/ - Free Version • Free: 1. StatsD/Graphite 2. Access Logs 3. Nagios 4. Ganglia 5. Hosted WebPagetest 6. Selenium/dynaTrace Ajax Edition 10
  • 11. Or Something Simple… <?php $start = microtime(true); …script content… $end = microtime(true); do_stuff('Description', $end - $start); ?> 11
  • 12. do_stuff()? • do_stuff() can do one of: 1. Log to a database (not ideal) 2. Write to a text file (eww) 3. Make a StatsD call over UDP (good) - http://codeascraft.etsy.com/2011/02/15/measure- anything-measure-everything/ 4. Choose your own adventure 12
  • 13.
  • 14. Averages can be misleading Better to look at percentiles 14
  • 15.
  • 16.
  • 17.
  • 18. What Does a Scalability Problem Look Like?
  • 19. This: 19
  • 22. So How Do We Do It?
  • 23. What can you do? • Start with the Database • Run a database trace 1. Filter: Queries > 50ms 2. Filter: Reads > 1000 3. Start with the worst ones and optimize 23
  • 24. What does “Optimize” mean? • Look at execution plan 1. Remove calls to remote servers 24
  • 25. Database Optimizations • Reduce Joins • Select * from  Select Foo, Bar, Baz from… • Minimize/consolidate subqueries • Add indexes where needed 1. We added one index: Procedure dropped from 3.5 sec & 4500 reads to .06 sec and 130 reads! • Be careful with where clauses (don’t calculate stuff in them) 25
  • 26. Example SELECT id, name, salary FROM employee WHERE salary < 25000; NOT SELECT id, name, salary FROM employee WHERE salary + 10000 < 35000; 26
  • 27. Example SELECT id, name, salary FROM employee WHERE salary < 25000; NOT SELECT id, name, salary FROM employee WHERE salary + 10000 < 35000; 27
  • 28. Not many hard and fast rules… • Try something, look at the plan • Try something else…look at how the plan changes • This is your friend: 28
  • 29. The Fastest DB Query is the One You Don’t Make
  • 30. Memcached • Caching layer between database and webserver • Can hold PHP objects and arrays 30
  • 31. Memcached $m = new Memcached(); $m->pconnect(‘1.2.3.4', 11211); $m->set(‘foo’, $bar, 600); $baz = $m->get(‘foo’); 31
  • 32. Install APC • APC – Alternative PHP Cache 1. Opcode Cache 2. User Cache 3. Awesome! 32
  • 34. User Cache <?php $bar = 'BAR'; apc_store('foo', $bar); var_dump(apc_fetch('foo')); ?> Outputs… string(3) "BAR" 34
  • 36. PHP Optimizations • Set the max loop value before the loop: $max = count($rows); for ($i = 0; $i < $max; $i++) { echo $i; } • require_once() is slow • Minimize use of define() • Yes, single quotes are slightly faster than double quotes, but… 36
  • 37. PHP Optimizations have limited value • Could go on and on… 1.http://www.wmtips.com/php/tips- optimizing-php-code.htm • Minimal returns • Find the hotspots in your application and fix them 37
  • 38. Example… • Homepage takes 5 seconds to load • Optimize PHP… 1. Reduce PHP execution time by 50%! • But wait! PHP execution was only taking 100ms 1. Saves you 50ms in load time 2. 1% of total page load 38
  • 39. If you really need to make your code faster… • HipHop for PHP • Built by Facebook and Open Sourced • Compiles PHP into C++ • Currently supports PHP 5.2 • http://developers.facebook.com/blog/post/358/ • https://github.com/facebook/hiphop-php 39
  • 41. Do it right • Pick the right one 1. Lighttpd/Nginx instead of Apache 2. Designed to solve the C10K problem • Lighttpd Used By: 1. Youtube 2. Wikipedia 3. Meebo 41
  • 42. Benefits of Lighttpd/Nginx • Event driven model: “Unlike traditional servers, Nginx doesn't rely on threads to handle requests. Instead it uses a much more scalable event- driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load.” - http://wiki.nginx.org/ • FastCGI + spawn-fcgi 1. PHP Process Management 2. Many child processes – scale out application tier. 42
  • 43. If you MUST use Apache • mod_deflate 1. Gzips content for faster transfer times • mod_pagespeed 1. Automatic performance improvements • KeepAlives on 1. Server won’t create a new connection for every resource 43
  • 45. JMeter • Open Source • Generate load via a GUI or command line • Can watch req/s peak out • Easy to use (just make sure you set the correct path to Java on your computer). 45
  • 46. JMeter 46
  • 47.
  • 48. JMeter 48
  • 49. JMeter • Watch your User Agent • Be careful hitting sites you don’t own • You might tap out your local box/network before killing the server 49
  • 50. Conclusion • Know and watch your site • More monitoring is better • Understand what is behind the scenes – look at the full stack • Load test BEFORE things go to production – figure out when they will fall over 50
  • 51. Questions? We’re Hiring! www.wayfair.com/careers Get In Touch: www.meetup.com/Web-Performance-Boston/ jklein@wayfair.com @jonathanklein 51