SlideShare une entreprise Scribd logo
1  sur  84
Télécharger pour lire hors ligne
Caching and tuning fun
  for high scalability



                           Wim Godden
                         Cu.be Solutions
Who am I ?
Wim Godden (@wimgtr)
Owner of Cu.be Solutions (http://cu.be)
Open Source developer since 1997
Developer of OpenX
Zend Certified Engineer
Zend Framework Certified Engineer
MySQL Certified Developer
Who are you ?
Developers ?
System/network engineers ?
Managers ?

Caching experience ?
Caching and tuning fun
  for high scalability



                           Wim Godden
                         Cu.be Solutions
Goals of this tutorial
Everything about caching and tuning
A few techniques
   How-to
   How-NOT-to


→ Increase reliability, performance and scalability



                5 visitors/day → 5 million visitors/day



                        (Don't expect miracle cure !)
LAMP
Architecture
Our base benchmark
Apachebench = useful enough
Result ?



                      Single webserver                    Proxy
                    Static         PHP         Static             PHP
Apache + PHP        3900           17.5        6700               17.5




                                  Limit :       Limit :
                                CPU, network   database
                                  or disk
Caching
What is caching ?




                    CACHE
What is caching ?

                                             x = 5, y = 2
                                                             Same result
                                                n = 50




                                                                             CACHE


 select
       *
 from
       article
              join user                                     Doesn't change
              on article.user_id = user.id                    all the time
 order by
       created desc
 limit
       10
Theory of caching


                                                                            DB
                                                                le
                                                           t ab
                                                     fro
                                                         m         ul t
                                                               res
                                                 ata     ned
                                           e ct d retur
                                        sel ta =
                                         $da
                       if ($data == false)
             Page
           GET /page                      set(
                                               'key
                                                    ', $
                                        $da      fals data)
                                            ta = e
                                                  get(
                                                       'key
                                                            ')
                                                                          Cache
Theory of caching


                            DB




                    HIT

                          Cache
Caching techniques
                #1 : Store entire pages
           #2 : Store part of a page (block)
           #3 : Store data retrieval (SQL ?)
         #4 : Store complex processing result
                     #? : Your call !

            When you have data, think :
            Creating time ?
            Modification frequency ?
            Retrieval frequency ?
How to find cacheable data
New projects : start from 'cache everything'
Existing projects :
   Look at MySQL slow query log
   Make a complete query log (don't forget to turn it off !)
   Check page loading times
Caching storage - Disk
Data with few updates : good
Caching SQL queries : preferably not

DON'T use NFS or other network file systems
   especially for sessions
   locking issues !
   high latency
Caching storage - Disk / ramdisk
Local
  5 Webservers → 5 local caches
  How will you keep them synchronized ?
        → Don't say NFS or rsync !
Caching storage - Memcache(d)
Facebook, Twitter, YouTube, … → need we say more ?
Distributed memory caching system
Multiple machines ↔ 1 big memory-based hash-table
Key-value storage system
  Keys - max. 250bytes
  Values - max. 1Mbyte
Caching storage - Memcache(d)
Facebook, Twitter, YouTube, … → need we say more ?
Distributed memory caching system
Multiple machines ↔ 1 big memory-based hash-table
Key-value storage system
   Keys - max. 250bytes
   Values - max. 1Mbyte
Extremely fast... non-blocking, UDP (!)
Memcache - where to install
Memcache - where to install
Memcache - installation & running it
Installation
   Distribution package
   PECL
   Windows : binaries
Running
   No config-files
   memcached -d -m <mem> -l <ip> -p <port>
   ex. : memcached -d -m 2048 -l 172.16.1.91 -p 11211
Caching storage - Memcache - some notes
Not fault-tolerant
   It's a cache !
   Lose session data
   Lose shopping cart data
   ...
Caching storage - Memcache - some notes
Not fault-tolerant
   It's a cache !
   Lose session data
   Lose shopping cart data
   …
Firewall your Memcache port !
Memcache in code
<?php
$memcache = new Memcache();
$memcache->addServer('172.16.0.1', 11211);
$memcache->addServer('172.16.0.2', 11211);


$myData = $memcache->get('myKey');
if ($myData === false) {
    $myData = GetMyDataFromDB();
    // Put it in Memcache as 'myKey', without compression, with no expiration
    $memcache->set('myKey', $myData, false, 0);
}
echo $myData;
Where's the data ?
Memcache client decides (!)
2 hashing algorithms :
   Traditional
       Server failure → all data must be rehashed
   Consistent
       Server failure → 1/x of data must be rehashed (x = # of servers)
Benchmark with Memcache




                      Single webserver             Proxy
                    Static         PHP    Static           PHP
Apache + PHP        3900           17.5   6700             17.5
Apache + PHP + MC   3900            55    6700             108
Memcache slabs
            (or why Memcache says it's full when it's not)

Multiple slabs of different sizes :
   Slab 1 : 400 bytes
   Slab 2 : 480 bytes (400 * 1.2)
   Slab 3 : 576 bytes (480 * 1.2) (and so on...)
Multiplier (1.2 here) can be configured
Store a lot of very large objects
→ Large slabs : full
→ Rest : free
→ Eviction of data !
Memcache - Is it working ?
Connect to it using telnet               STAT pid 2941
                                         STAT uptime 10878
                                         STAT time 1296074240
   "stats" command →                     STAT version 1.4.5
                                         STAT pointer_size 64
                                         STAT rusage_user 20.089945
   Use Cacti or other monitoring tools   STAT rusage_system 58.499106
                                         STAT curr_connections 16
                                         STAT total_connections 276950
                                         STAT connection_structures 96
                                         STAT cmd_get 276931
                                         STAT cmd_set 584148
                                         STAT cmd_flush 0
                                         STAT get_hits 211106
                                         STAT get_misses 65825
                                         STAT delete_misses 101
                                         STAT delete_hits 276829
                                         STAT incr_misses 0
                                         STAT incr_hits 0
                                         STAT decr_misses 0
                                         STAT decr_hits 0
                                         STAT cas_misses 0
                                         STAT cas_hits 0
                                         STAT cas_badval 0
                                         STAT auth_cmds 0
                                         STAT auth_errors 0
                                         STAT bytes_read 613193860
                                         STAT bytes_written 553991373
                                         STAT limit_maxbytes 268435456
                                         STAT accepting_conns 1
                                         STAT listen_disabled_num 0
                                         STAT threads 4
                                         STAT conn_yields 0
                                         STAT bytes 20418140
                                         STAT curr_items 65826
                                         STAT total_items 553856
                                         STAT evictions 0
                                         STAT reclaimed 0
Memcache - backing up
Memcache - tip
Page with multiple blocks ?
→ use Memcached::getMulti()



                     Hashing
  getMulti($array)
                     algorithm




But : what if you get some hits and some misses ?
Updating data
Updating data




                LCD_Popular_Product_List
Adding/updating data

$memcache->delete('LCD_Popular_Product_List');
Adding/updating data
Adding/updating data - Why it crashed
Adding/updating data - Why it crashed
Adding/updating data - Why it crashed
Cache stampeding
Cache stampeding
Memcache code ?


    Memcache code




     Visitor interface        Admin interface




                         DB
Cache warmup scripts
Used to fill your cache when it's empty
Run it before starting Webserver !

2 ways :
   Visit all URLs
       Error-prone
       Hard to maintain
   Call all cache-updating methods




                 Make sure you have a warmup script !
Cache stampeding - what about locking ?
Seems like a nice idea, but...
While lock in place
What if the process that created the lock fails ?
LAMP...




          → LAMMP



          → LNMMP
Nginx
Web server
Reverse proxy
Lightweight, fast
10.2% of all Websites
Nginx
No threads, event-driven
Uses epoll / kqueue
Low memory footprint

10000 active connections = normal
Nginx - a true alternative to Apache ?
Not all Apache modules
   mod_auth_*
   mod_dav*
   …
Basic modules are available
Some 3rd party modules (needs recompilation !)
Nginx - Configuration


        server {
         listen        80;
         server_name   www.domain.ext *.domain.ext;

            index      index.html;
            root       /home/domain.ext/www;
        }

        server {
         listen        80;
         server_name   photo.domain.ext;

            index      index.html;
            root       /home/domain.ext/photo;
        }
Nginx + PHP-FPM - performance ?




                         Single webserver                    Proxy
                       Static         PHP           Static           PHP
Apache + PHP           3900           17.5          6700             17.5
Apache + PHP + MC      3900            55           6700             108
Nginx + PHP-FPM + MC   11700           57           11200            112




                                       Limit :
                                  single-threaded
                                   Apachebench
Reverse proxy time...
Varnish
Not just a load balancer
Reverse proxy cache / http accelerator / …
Caches (parts of) pages in memory
Careful :
   uses threads (like Apache)
   Nginx usually scales better (but doesn't have VCL)
Varnish - backends + load balancing
 backend server1 {
     .host = "192.168.0.10";
 }
 backend server2{
     .host = "192.168.0.11";
 }

 director example_director round-robin {
      {
            .backend = server1;
      }
      {
            .backend = server2;
      }
 }
Varnish - VCL
Varnish Configuration Language
DSL (Domain Specific Language)
   → compiled to C
Hooks into each request
Defines :
   Backends (web servers)
   ACLs
   Load balancing strategy
Can be reloaded while running
Varnish - whatever you want
Real-time statistics (varnishtop, varnishhist, ...)
ESI
Varnish - ESI
Perfect for caching pages
             Header (TTL : 60 min)              In your article page output :
                     /top                       <esi:include src="/news"/>

             Latest news (TTL : 2 min) /news
                                                In your Varnish config :
                                                sub vcl_fetch {
                                                   if (req.url == "/news") {
Navigation    Article content page                     esi; /* Do ESI processing */
  (TTL :                                               set obj.ttl = 2m;
 60 min)       Article content (TTL : 15 min)      } elseif (req.url == "/nav") {
   /nav                  /article/732                  esi;
                                                       set obj.ttl = 1m;
                                                   } elseif ….
                                                ….
                                                }
Varnish with ESI - hold on tight !



                         Single webserver             Proxy
                       Static         PHP    Static           PHP
Apache + PHP           3900           17.5   6700             17.5
Apache + PHP + MC      3900            55    6700             108
Nginx + PHP-FPM + MC   11700           57    11200            112
Varnish                  -              -    11200            4200
Varnish - what can/can't be cached ?
Can :
   Static pages
   Images, js, css
   Pages or parts of pages that don't change often (ESI)
Can't :
   POST requests
   Very large files (it's not a file server !)
   Requests with Set-Cookie
   User-specific content
ESI → no caching on user-specific content ?

                                           Logged in as : Wim Godden
                 TTL = 0s ?
                                                          5 messages




      TTL=1h                  TTL = 5min
Coming soon...
Based on Nginx
Reduces load by 50 – 95%
  Requires code changes !
  Well-built project → few changes
  Effect on webservers and database servers
What's the result ?
What's the result ?
Figures
First customer :
   No. of web servers : 18 → 4
   No. of db servers : 6 → 2
   Total : 24 → 6 (75% reduction !)
Second customer (already using Nginx + Memcache) :
   No. of web servers : 72 → 8
   No. of db servers : 15 → 4
   Total : 87 → 12 (86% reduction !)
Availability
Stable at 2 customers
Still under heavy development
Beta : Jul 2012
Final : Sep 2012
Tuning
PHP speed - some tips
Upgrade PHP - every minor release has 5-15% speed gain !
Use an opcode cache
Caching storage - Opcode caching
DB speed - some tips
Use same types for joins
   i.e. don't join decimal with int
RAND() is evil !
count(*) is evil in InnoDB without a where clause !
Persistent connect is sort-of evil
Caching & Tuning @ frontend




        http://www.websiteoptimization.com/speed/tweak/average-web-page/
Frontend tuning
1. You optimize backend
2. Frontend engineers messes up → havoc on backend
3. Don't forget : frontend sends requests to backend !

                             SO...

Care about frontend
Test frontend
Check what requests frontend sends to backend
Tuning frontend
Minimize requests
  Combine CSS/JavaScript files
Tuning frontend
Minimize requests
  Combine CSS/JavaScript files
  Use CSS Sprites
CSS Sprites
Tuning content - CSS sprites
Tuning content - CSS sprites




         11 images             1 image
         11 HTTP requests      1 HTTP requests
         24KByte               14KByte
Tuning frontend
Minimize requests
   Combine CSS/JavaScript files
   Use CSS Sprites (horizontally if possible)
Put CSS at top
Put JavaScript at bottom
   Max. no connections
   Especially if JavaScript does Ajax (advertising-scripts, …) !
Avoid iFrames
   Again : max no. of connections
Don't scale images in HTML
Have a favicon.ico (don't 404 it !)
   → see my blog
What else can kill your site ?
Redirect loops
   Multiple requests
       More load on Webserver
       More PHP to process
   Additional latency for visitor
   Try to avoid redirects anyway
   → In ZF : use $this->_forward instead of $this->_redirect
Watch your logs, but equally important...
Watch the logging process →
Logging = disk I/O → can kill your server !
Slashdot effect
Above all else... be prepared !
Have a monitoring system
Use a cache abstraction layer (disk → Memcache)
Don't install for the worst → prepare for the worst
Have a test-setup
Have fallbacks
   → Turn off non-critical functionality
So...
Cache
  But : never delete, always push !
  Have a warmup script
  Monitor your cache
  Have an abstraction layer
Apache = fine, Nginx = better
Static pages ? Use Varnish
Tune your frontend → impact on backend !
Prepare for the worst
Questions ?
Questions ?
We're hiring !
Lots of challenges
Work with cutting-edge technology
Varied :
   PHP development
   System / network architecture
   Scalability services
   Build our own services
   Work on Open Source


   → mail us : info@cu.be
Contact
Twitter             @wimgtr
Web                http://techblog.wimgodden.be
Slides                 http://www.slideshare.net/wimg
E-mail                 wim.godden@cu.be



                               Please...
          Rate my talk : http://speakerrate.com/talks/9501
Thanks !
                     Please...
Rate my talk : http://speakerrate.com/talks/9501
Caching and tuning fun for high scalability @ LOAD2012

Contenu connexe

Tendances

PostgreSQL Open SV 2018
PostgreSQL Open SV 2018PostgreSQL Open SV 2018
PostgreSQL Open SV 2018artgillespie
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for CassandraEdward Capriolo
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB
 
Database Wizardry for Legacy Applications
Database Wizardry for Legacy ApplicationsDatabase Wizardry for Legacy Applications
Database Wizardry for Legacy ApplicationsGabriela Ferrara
 
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Cliff Seal
 
Riak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup GroupRiak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup Groupsiculars
 
MongoDB Days Silicon Valley: MongoDB and the Hadoop Connector
MongoDB Days Silicon Valley: MongoDB and the Hadoop ConnectorMongoDB Days Silicon Valley: MongoDB and the Hadoop Connector
MongoDB Days Silicon Valley: MongoDB and the Hadoop ConnectorMongoDB
 
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014Cliff Seal
 
It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?MongoDB
 
SunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQLSunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQLGabriela Ferrara
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETTomas Jansson
 
Redis for the Everyday Developer
Redis for the Everyday DeveloperRedis for the Everyday Developer
Redis for the Everyday DeveloperRoss Tuck
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance TuningPuneet Behl
 
Cassandra Summit 2015
Cassandra Summit 2015Cassandra Summit 2015
Cassandra Summit 2015jbellis
 
Nko workshop - node js crud & deploy
Nko workshop - node js crud & deployNko workshop - node js crud & deploy
Nko workshop - node js crud & deploySimon Su
 
神に近づくx/net/context (Finding God with x/net/context)
神に近づくx/net/context (Finding God with x/net/context)神に近づくx/net/context (Finding God with x/net/context)
神に近づくx/net/context (Finding God with x/net/context)guregu
 
MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?Gabriela Ferrara
 

Tendances (20)

Load Data Fast!
Load Data Fast!Load Data Fast!
Load Data Fast!
 
PostgreSQL Open SV 2018
PostgreSQL Open SV 2018PostgreSQL Open SV 2018
PostgreSQL Open SV 2018
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for Cassandra
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() Output
 
Database Wizardry for Legacy Applications
Database Wizardry for Legacy ApplicationsDatabase Wizardry for Legacy Applications
Database Wizardry for Legacy Applications
 
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
Temporary Cache Assistance (Transients API): WordCamp Birmingham 2014
 
Riak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup GroupRiak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup Group
 
MongoDB Days Silicon Valley: MongoDB and the Hadoop Connector
MongoDB Days Silicon Valley: MongoDB and the Hadoop ConnectorMongoDB Days Silicon Valley: MongoDB and the Hadoop Connector
MongoDB Days Silicon Valley: MongoDB and the Hadoop Connector
 
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
Temporary Cache Assistance (Transients API): WordCamp Phoenix 2014
 
Django cryptography
Django cryptographyDjango cryptography
Django cryptography
 
It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?It's 10pm: Do You Know Where Your Writes Are?
It's 10pm: Do You Know Where Your Writes Are?
 
SunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQLSunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQL
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
 
How to Use JSON in MySQL Wrong
How to Use JSON in MySQL WrongHow to Use JSON in MySQL Wrong
How to Use JSON in MySQL Wrong
 
Redis for the Everyday Developer
Redis for the Everyday DeveloperRedis for the Everyday Developer
Redis for the Everyday Developer
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
 
Cassandra Summit 2015
Cassandra Summit 2015Cassandra Summit 2015
Cassandra Summit 2015
 
Nko workshop - node js crud & deploy
Nko workshop - node js crud & deployNko workshop - node js crud & deploy
Nko workshop - node js crud & deploy
 
神に近づくx/net/context (Finding God with x/net/context)
神に近づくx/net/context (Finding God with x/net/context)神に近づくx/net/context (Finding God with x/net/context)
神に近づくx/net/context (Finding God with x/net/context)
 
MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?
 

Similaire à Caching and tuning fun for high scalability @ LOAD2012

Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalabilityWim Godden
 
Caching and tuning fun for high scalability @ 4Developers
Caching and tuning fun for high scalability @ 4DevelopersCaching and tuning fun for high scalability @ 4Developers
Caching and tuning fun for high scalability @ 4DevelopersWim Godden
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalabilityWim Godden
 
Nginx and friends - putting a turbo button on your site
Nginx and friends - putting a turbo button on your siteNginx and friends - putting a turbo button on your site
Nginx and friends - putting a turbo button on your siteWim Godden
 
Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011Wim Godden
 
phptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorialphptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorialWim Godden
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalabilityWim Godden
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalabilityWim Godden
 
Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012Wim Godden
 
Caching and tuning fun for high scalability @ phpBenelux 2011
Caching and tuning fun for high scalability @ phpBenelux 2011Caching and tuning fun for high scalability @ phpBenelux 2011
Caching and tuning fun for high scalability @ phpBenelux 2011Wim Godden
 
Dutch php conference_apc_mem2010
Dutch php conference_apc_mem2010Dutch php conference_apc_mem2010
Dutch php conference_apc_mem2010isnull
 
Zend Server Data Caching
Zend Server Data CachingZend Server Data Caching
Zend Server Data CachingEl Taller Web
 
MySQL cluster 72 in the Cloud
MySQL cluster 72 in the CloudMySQL cluster 72 in the Cloud
MySQL cluster 72 in the CloudMarco Tusa
 
Caching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTourCaching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTourWim Godden
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统yiditushe
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebookguoqing75
 
Wide Column Store NoSQL vs SQL Data Modeling
Wide Column Store NoSQL vs SQL Data ModelingWide Column Store NoSQL vs SQL Data Modeling
Wide Column Store NoSQL vs SQL Data ModelingScyllaDB
 

Similaire à Caching and tuning fun for high scalability @ LOAD2012 (20)

Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
Caching and tuning fun for high scalability @ 4Developers
Caching and tuning fun for high scalability @ 4DevelopersCaching and tuning fun for high scalability @ 4Developers
Caching and tuning fun for high scalability @ 4Developers
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
Nginx and friends - putting a turbo button on your site
Nginx and friends - putting a turbo button on your siteNginx and friends - putting a turbo button on your site
Nginx and friends - putting a turbo button on your site
 
Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011
 
phptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorialphptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorial
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012Caching and tuning fun for high scalability @ FOSDEM 2012
Caching and tuning fun for high scalability @ FOSDEM 2012
 
Caching and tuning fun for high scalability @ phpBenelux 2011
Caching and tuning fun for high scalability @ phpBenelux 2011Caching and tuning fun for high scalability @ phpBenelux 2011
Caching and tuning fun for high scalability @ phpBenelux 2011
 
Dutch php conference_apc_mem2010
Dutch php conference_apc_mem2010Dutch php conference_apc_mem2010
Dutch php conference_apc_mem2010
 
Zend Server Data Caching
Zend Server Data CachingZend Server Data Caching
Zend Server Data Caching
 
MySQL cluster 72 in the Cloud
MySQL cluster 72 in the CloudMySQL cluster 72 in the Cloud
MySQL cluster 72 in the Cloud
 
Caching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTourCaching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTour
 
Advanced Cassandra
Advanced CassandraAdvanced Cassandra
Advanced Cassandra
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
Memcached Study
Memcached StudyMemcached Study
Memcached Study
 
Wide Column Store NoSQL vs SQL Data Modeling
Wide Column Store NoSQL vs SQL Data ModelingWide Column Store NoSQL vs SQL Data Modeling
Wide Column Store NoSQL vs SQL Data Modeling
 
Pecl Picks
Pecl PicksPecl Picks
Pecl Picks
 

Plus de Wim Godden

Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeWim Godden
 
Bringing bright ideas to life
Bringing bright ideas to lifeBringing bright ideas to life
Bringing bright ideas to lifeWim Godden
 
The why and how of moving to php 8
The why and how of moving to php 8The why and how of moving to php 8
The why and how of moving to php 8Wim Godden
 
The why and how of moving to php 7
The why and how of moving to php 7The why and how of moving to php 7
The why and how of moving to php 7Wim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websocketsWim Godden
 
Bringing bright ideas to life
Bringing bright ideas to lifeBringing bright ideas to life
Bringing bright ideas to lifeWim Godden
 
Your app lives on the network - networking for web developers
Your app lives on the network - networking for web developersYour app lives on the network - networking for web developers
Your app lives on the network - networking for web developersWim Godden
 
The why and how of moving to php 7.x
The why and how of moving to php 7.xThe why and how of moving to php 7.x
The why and how of moving to php 7.xWim Godden
 
The why and how of moving to php 7.x
The why and how of moving to php 7.xThe why and how of moving to php 7.x
The why and how of moving to php 7.xWim Godden
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeWim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websocketsWim Godden
 
Your app lives on the network - networking for web developers
Your app lives on the network - networking for web developersYour app lives on the network - networking for web developers
Your app lives on the network - networking for web developersWim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous phpWim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 

Plus de Wim Godden (20)

Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
Bringing bright ideas to life
Bringing bright ideas to lifeBringing bright ideas to life
Bringing bright ideas to life
 
The why and how of moving to php 8
The why and how of moving to php 8The why and how of moving to php 8
The why and how of moving to php 8
 
The why and how of moving to php 7
The why and how of moving to php 7The why and how of moving to php 7
The why and how of moving to php 7
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
 
Bringing bright ideas to life
Bringing bright ideas to lifeBringing bright ideas to life
Bringing bright ideas to life
 
Your app lives on the network - networking for web developers
Your app lives on the network - networking for web developersYour app lives on the network - networking for web developers
Your app lives on the network - networking for web developers
 
The why and how of moving to php 7.x
The why and how of moving to php 7.xThe why and how of moving to php 7.x
The why and how of moving to php 7.x
 
The why and how of moving to php 7.x
The why and how of moving to php 7.xThe why and how of moving to php 7.x
The why and how of moving to php 7.x
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
 
Your app lives on the network - networking for web developers
Your app lives on the network - networking for web developersYour app lives on the network - networking for web developers
Your app lives on the network - networking for web developers
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 

Dernier

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
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
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Dernier (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.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
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Caching and tuning fun for high scalability @ LOAD2012

  • 1. Caching and tuning fun for high scalability Wim Godden Cu.be Solutions
  • 2. Who am I ? Wim Godden (@wimgtr) Owner of Cu.be Solutions (http://cu.be) Open Source developer since 1997 Developer of OpenX Zend Certified Engineer Zend Framework Certified Engineer MySQL Certified Developer
  • 3. Who are you ? Developers ? System/network engineers ? Managers ? Caching experience ?
  • 4. Caching and tuning fun for high scalability Wim Godden Cu.be Solutions
  • 5. Goals of this tutorial Everything about caching and tuning A few techniques How-to How-NOT-to → Increase reliability, performance and scalability 5 visitors/day → 5 million visitors/day (Don't expect miracle cure !)
  • 8. Our base benchmark Apachebench = useful enough Result ? Single webserver Proxy Static PHP Static PHP Apache + PHP 3900 17.5 6700 17.5 Limit : Limit : CPU, network database or disk
  • 10. What is caching ? CACHE
  • 11. What is caching ? x = 5, y = 2 Same result n = 50 CACHE select * from article join user Doesn't change on article.user_id = user.id all the time order by created desc limit 10
  • 12. Theory of caching DB le t ab fro m ul t res ata ned e ct d retur sel ta = $da if ($data == false) Page GET /page set( 'key ', $ $da fals data) ta = e get( 'key ') Cache
  • 13. Theory of caching DB HIT Cache
  • 14. Caching techniques #1 : Store entire pages #2 : Store part of a page (block) #3 : Store data retrieval (SQL ?) #4 : Store complex processing result #? : Your call ! When you have data, think : Creating time ? Modification frequency ? Retrieval frequency ?
  • 15. How to find cacheable data New projects : start from 'cache everything' Existing projects : Look at MySQL slow query log Make a complete query log (don't forget to turn it off !) Check page loading times
  • 16. Caching storage - Disk Data with few updates : good Caching SQL queries : preferably not DON'T use NFS or other network file systems especially for sessions locking issues ! high latency
  • 17. Caching storage - Disk / ramdisk Local 5 Webservers → 5 local caches How will you keep them synchronized ? → Don't say NFS or rsync !
  • 18. Caching storage - Memcache(d) Facebook, Twitter, YouTube, … → need we say more ? Distributed memory caching system Multiple machines ↔ 1 big memory-based hash-table Key-value storage system Keys - max. 250bytes Values - max. 1Mbyte
  • 19. Caching storage - Memcache(d) Facebook, Twitter, YouTube, … → need we say more ? Distributed memory caching system Multiple machines ↔ 1 big memory-based hash-table Key-value storage system Keys - max. 250bytes Values - max. 1Mbyte Extremely fast... non-blocking, UDP (!)
  • 20. Memcache - where to install
  • 21. Memcache - where to install
  • 22. Memcache - installation & running it Installation Distribution package PECL Windows : binaries Running No config-files memcached -d -m <mem> -l <ip> -p <port> ex. : memcached -d -m 2048 -l 172.16.1.91 -p 11211
  • 23. Caching storage - Memcache - some notes Not fault-tolerant It's a cache ! Lose session data Lose shopping cart data ...
  • 24. Caching storage - Memcache - some notes Not fault-tolerant It's a cache ! Lose session data Lose shopping cart data … Firewall your Memcache port !
  • 25. Memcache in code <?php $memcache = new Memcache(); $memcache->addServer('172.16.0.1', 11211); $memcache->addServer('172.16.0.2', 11211); $myData = $memcache->get('myKey'); if ($myData === false) { $myData = GetMyDataFromDB(); // Put it in Memcache as 'myKey', without compression, with no expiration $memcache->set('myKey', $myData, false, 0); } echo $myData;
  • 26. Where's the data ? Memcache client decides (!) 2 hashing algorithms : Traditional Server failure → all data must be rehashed Consistent Server failure → 1/x of data must be rehashed (x = # of servers)
  • 27. Benchmark with Memcache Single webserver Proxy Static PHP Static PHP Apache + PHP 3900 17.5 6700 17.5 Apache + PHP + MC 3900 55 6700 108
  • 28. Memcache slabs (or why Memcache says it's full when it's not) Multiple slabs of different sizes : Slab 1 : 400 bytes Slab 2 : 480 bytes (400 * 1.2) Slab 3 : 576 bytes (480 * 1.2) (and so on...) Multiplier (1.2 here) can be configured Store a lot of very large objects → Large slabs : full → Rest : free → Eviction of data !
  • 29. Memcache - Is it working ? Connect to it using telnet STAT pid 2941 STAT uptime 10878 STAT time 1296074240 "stats" command → STAT version 1.4.5 STAT pointer_size 64 STAT rusage_user 20.089945 Use Cacti or other monitoring tools STAT rusage_system 58.499106 STAT curr_connections 16 STAT total_connections 276950 STAT connection_structures 96 STAT cmd_get 276931 STAT cmd_set 584148 STAT cmd_flush 0 STAT get_hits 211106 STAT get_misses 65825 STAT delete_misses 101 STAT delete_hits 276829 STAT incr_misses 0 STAT incr_hits 0 STAT decr_misses 0 STAT decr_hits 0 STAT cas_misses 0 STAT cas_hits 0 STAT cas_badval 0 STAT auth_cmds 0 STAT auth_errors 0 STAT bytes_read 613193860 STAT bytes_written 553991373 STAT limit_maxbytes 268435456 STAT accepting_conns 1 STAT listen_disabled_num 0 STAT threads 4 STAT conn_yields 0 STAT bytes 20418140 STAT curr_items 65826 STAT total_items 553856 STAT evictions 0 STAT reclaimed 0
  • 31. Memcache - tip Page with multiple blocks ? → use Memcached::getMulti() Hashing getMulti($array) algorithm But : what if you get some hits and some misses ?
  • 33. Updating data LCD_Popular_Product_List
  • 36. Adding/updating data - Why it crashed
  • 37. Adding/updating data - Why it crashed
  • 38. Adding/updating data - Why it crashed
  • 41. Memcache code ? Memcache code Visitor interface Admin interface DB
  • 42. Cache warmup scripts Used to fill your cache when it's empty Run it before starting Webserver ! 2 ways : Visit all URLs Error-prone Hard to maintain Call all cache-updating methods Make sure you have a warmup script !
  • 43. Cache stampeding - what about locking ? Seems like a nice idea, but... While lock in place What if the process that created the lock fails ?
  • 44. LAMP... → LAMMP → LNMMP
  • 45. Nginx Web server Reverse proxy Lightweight, fast 10.2% of all Websites
  • 46. Nginx No threads, event-driven Uses epoll / kqueue Low memory footprint 10000 active connections = normal
  • 47. Nginx - a true alternative to Apache ? Not all Apache modules mod_auth_* mod_dav* … Basic modules are available Some 3rd party modules (needs recompilation !)
  • 48. Nginx - Configuration server { listen 80; server_name www.domain.ext *.domain.ext; index index.html; root /home/domain.ext/www; } server { listen 80; server_name photo.domain.ext; index index.html; root /home/domain.ext/photo; }
  • 49. Nginx + PHP-FPM - performance ? Single webserver Proxy Static PHP Static PHP Apache + PHP 3900 17.5 6700 17.5 Apache + PHP + MC 3900 55 6700 108 Nginx + PHP-FPM + MC 11700 57 11200 112 Limit : single-threaded Apachebench
  • 51. Varnish Not just a load balancer Reverse proxy cache / http accelerator / … Caches (parts of) pages in memory Careful : uses threads (like Apache) Nginx usually scales better (but doesn't have VCL)
  • 52. Varnish - backends + load balancing backend server1 { .host = "192.168.0.10"; } backend server2{ .host = "192.168.0.11"; } director example_director round-robin { { .backend = server1; } { .backend = server2; } }
  • 53. Varnish - VCL Varnish Configuration Language DSL (Domain Specific Language) → compiled to C Hooks into each request Defines : Backends (web servers) ACLs Load balancing strategy Can be reloaded while running
  • 54. Varnish - whatever you want Real-time statistics (varnishtop, varnishhist, ...) ESI
  • 55. Varnish - ESI Perfect for caching pages Header (TTL : 60 min) In your article page output : /top <esi:include src="/news"/> Latest news (TTL : 2 min) /news In your Varnish config : sub vcl_fetch { if (req.url == "/news") { Navigation Article content page esi; /* Do ESI processing */ (TTL : set obj.ttl = 2m; 60 min) Article content (TTL : 15 min) } elseif (req.url == "/nav") { /nav /article/732 esi; set obj.ttl = 1m; } elseif …. …. }
  • 56. Varnish with ESI - hold on tight ! Single webserver Proxy Static PHP Static PHP Apache + PHP 3900 17.5 6700 17.5 Apache + PHP + MC 3900 55 6700 108 Nginx + PHP-FPM + MC 11700 57 11200 112 Varnish - - 11200 4200
  • 57. Varnish - what can/can't be cached ? Can : Static pages Images, js, css Pages or parts of pages that don't change often (ESI) Can't : POST requests Very large files (it's not a file server !) Requests with Set-Cookie User-specific content
  • 58. ESI → no caching on user-specific content ? Logged in as : Wim Godden TTL = 0s ? 5 messages TTL=1h TTL = 5min
  • 59. Coming soon... Based on Nginx Reduces load by 50 – 95% Requires code changes ! Well-built project → few changes Effect on webservers and database servers
  • 62. Figures First customer : No. of web servers : 18 → 4 No. of db servers : 6 → 2 Total : 24 → 6 (75% reduction !) Second customer (already using Nginx + Memcache) : No. of web servers : 72 → 8 No. of db servers : 15 → 4 Total : 87 → 12 (86% reduction !)
  • 63. Availability Stable at 2 customers Still under heavy development Beta : Jul 2012 Final : Sep 2012
  • 65. PHP speed - some tips Upgrade PHP - every minor release has 5-15% speed gain ! Use an opcode cache
  • 66. Caching storage - Opcode caching
  • 67. DB speed - some tips Use same types for joins i.e. don't join decimal with int RAND() is evil ! count(*) is evil in InnoDB without a where clause ! Persistent connect is sort-of evil
  • 68. Caching & Tuning @ frontend http://www.websiteoptimization.com/speed/tweak/average-web-page/
  • 69. Frontend tuning 1. You optimize backend 2. Frontend engineers messes up → havoc on backend 3. Don't forget : frontend sends requests to backend ! SO... Care about frontend Test frontend Check what requests frontend sends to backend
  • 70. Tuning frontend Minimize requests Combine CSS/JavaScript files
  • 71. Tuning frontend Minimize requests Combine CSS/JavaScript files Use CSS Sprites
  • 73. Tuning content - CSS sprites
  • 74. Tuning content - CSS sprites 11 images 1 image 11 HTTP requests 1 HTTP requests 24KByte 14KByte
  • 75. Tuning frontend Minimize requests Combine CSS/JavaScript files Use CSS Sprites (horizontally if possible) Put CSS at top Put JavaScript at bottom Max. no connections Especially if JavaScript does Ajax (advertising-scripts, …) ! Avoid iFrames Again : max no. of connections Don't scale images in HTML Have a favicon.ico (don't 404 it !) → see my blog
  • 76. What else can kill your site ? Redirect loops Multiple requests More load on Webserver More PHP to process Additional latency for visitor Try to avoid redirects anyway → In ZF : use $this->_forward instead of $this->_redirect Watch your logs, but equally important... Watch the logging process → Logging = disk I/O → can kill your server ! Slashdot effect
  • 77. Above all else... be prepared ! Have a monitoring system Use a cache abstraction layer (disk → Memcache) Don't install for the worst → prepare for the worst Have a test-setup Have fallbacks → Turn off non-critical functionality
  • 78. So... Cache But : never delete, always push ! Have a warmup script Monitor your cache Have an abstraction layer Apache = fine, Nginx = better Static pages ? Use Varnish Tune your frontend → impact on backend ! Prepare for the worst
  • 81. We're hiring ! Lots of challenges Work with cutting-edge technology Varied : PHP development System / network architecture Scalability services Build our own services Work on Open Source → mail us : info@cu.be
  • 82. Contact Twitter @wimgtr Web http://techblog.wimgodden.be Slides http://www.slideshare.net/wimg E-mail wim.godden@cu.be Please... Rate my talk : http://speakerrate.com/talks/9501
  • 83. Thanks ! Please... Rate my talk : http://speakerrate.com/talks/9501