SlideShare a Scribd company logo
1 of 43
Download to read offline
Maximize your Cache 
for no Ca$h 
Yorick Phoenix 
slides: slidesha.re/1vQDbOv 
about.me/yorickphoenix | @scribblings | github.com/yphoenix | yorick@issio.net
Why Cache Stuff 
• What is a Cache and why do we want 
to cache data?! 
• Holds a copy for fast access.! 
• The nearer the data is to the user, the 
faster the access.! 
• Not just speed but latency and page 
load order.!
Cache Downsides 
• Stale Data / Update Problems.! 
• Cache Synchronization.! 
• The more you do, the more work it 
is to do it.
At least 7 Kinds of Cache 
1. PHP OpCode Cache! 
2. Session Variable Cache! 
3. Browser Cache! 
4. Content Delivery Network Cache! 
5. SessionStorage! 
6. LocalStorage! 
7. AppCache / Manifests!
1. PHP ByteCode Cache 
• PHP byte code compiler parses the code into 
OpCode.! 
• To save having to do this more than once, it 
is cached.! 
• APC (alternative PHP Cache)! 
• XCache.! 
• OPCache (built-in from PHP 5.5 onwards)
Advantages 
• Easy to configure! 
• Can also be used to cache your own 
information, not just OpCodes! 
• Great for code or site wide static 
data or statistical measurement! 
• php.net/manual/en/book.apc.php
Install APC 
% pecl install APC 
% vi /etc/php.ini! 
extension=apc.so 
% sudo apachectl restart #or! 
% sudo kill -SIGUSR2 ! 
`cat /usr/var/run/php-fpm.pid`
APC Status 
http:/localhost/apc.php
Storing non-code in APC 
apc_store($key, $value); 
apc_fetch($key); 
apc_inc($key); 
apc_dec($key); 
apc_delete($key);
2. $_SESSION Variables 
• The Web Server will store stuff for you. 
Any structure or data type like.! 
• You store a reference to this data in a 
cookie which you send with every page 
request.! 
• Stored until you delete it or it expires.! 
• php.net/manual/en/book.session.php
How Sessions Work 
Get Session Info 
Server 
Browser 
/tmp/sess_SessionID 
Page Request 
(send sessionID) 
Save Session Info 
Page Response 
(receive sessionID) 
1 
2 
3 
4
Session Example 
<?php! 
session_start();! 
2 
if (!isset($_SESSION['count'])) 
{! 
$_SESSION['count'] = 0;! 
} else {! 
$_SESSION['count']++;! 
}! 
! 
echo $_SESSION[‘count’];! 
?>! 
3
Session DEMO 
svcc.scribblings.com/session.php!
Session Security 
• Data stored securely on server, never 
downloaded to users Browser.! 
• Only SessionID transmitted to Browser.! 
• SessionID’s can be stolen, so always use 
a secure HTTPS connection.! 
• Store some unique token inside the 
session and store that in the browser, 
send with page request & validate
3. Browser Cache 
• The browser will cache stuff for 
you…! 
• Any file (css, js, html, jpg, png, etc)! 
• Two different expiration checks! 
• Expires in 'n' minutes! 
• Last modified
Expires in ’n’ minutes 
• Specify how long to cache a file for.! 
• You need to work out in advance how 
often you are going to need to update 
your code.! 
• Once it is in the users browser with a 
cache expiration period, the browser 
isn’t going to re-download it without 
the user forcing it.
Expires in ’n’ flow 
• Browser downloads file, with 
expiration! 
• When next requested, checks 
expiration! 
• If not expired, uses cached version! 
• If expired, requests a new version
Enabling Apache Cache 
<IfModule mod_expires.c> 
ExpiresActive On 
! # expire images after 24 hours 
ExpiresByType image/gif A86400 
ExpiresByType image/jpeg A86400 
ExpiresByType image/png A86400 
! # expire JavaScript & CSS after 4 hours 
ExpiresByType text/javascript A21600 
ExpiresByType text/css A21600 
</IfModule> 
! 
www.mobify.com/blog/beginners-guide-to-http-cache- 
headers/ 
!www.mnot.net/cache_docs/
Last Modified flow 
• Downloads file, with modification 
date! 
• When next requested, asks server if 
file is newer than date recorded! 
• If newer, downloads new version! 
• If not modified uses cache version
Browser Cache Issues 
• Trade off of how long to cache vs how 
frequent to download! 
• If you update frequently then this 
needs to be small! 
• Results in more more frequent 
downloads or last modified checks! 
• You will always download more often 
than you really need to
Browser Cache Updates 
• Unpredictable behavior! 
• Browser makes the decisions! 
• Don’t play the rename the file to 
update game
Different Browsers 
• Different browsers cache things 
differently.! 
• Learn to use the debugging tools.! 
• Chrome, Safari, FireFox, IE.! 
• It's always a trade off.
4. Content Delivery Network 
• They help mitigate the Browser Cache 
Issue by moving the static data closer to 
the user.! 
• Automatic caching at a data center 
nearest your user! 
• Automatic redundancy of servers! 
• Basic level of service is FREE
downloadSpeed: “fast” 
Cache your data & code as close 
to the user as you possibly can….
Lots of CDN’s 
Use a good CDN and all this 
will be handled for you….
Other CDN Pluses 
• You can edge cache static PHP if 
you want! 
• Replication of your static data takes 
the load off your primary server! 
• All for free and free SSL too
5. sessionStorage 
• Can store any arbitrary string! 
• Persist between page reloads! 
• Disappears when window / tab 
closed! 
• Stored on a Domain by Domain 
basis, window by window basis
Session DEMO 
svcc.scribblings.com/ss.html! 
<script>! 
var count;! 
! 
count = sessionStorage.svcc || 0;! 
count++;! 
sessionStorage.svcc=count;! 
document.writeln(count);! 
</script>!
sessionStorage Uses 
• Good for storing status / tracking 
information between page loads! 
• Can have different information in 
different windows even for the 
same domain (unlike cookies).! 
• Information is local to the user, 
never sent over the wire.
6. localStorage 
• Can store any arbitrary string! 
• Persist between page reloads! 
• Persists when window closed! 
• Persists when browser quit! 
• Stored on a Domain by Domain 
basis
Session DEMO 
svcc.scribblings.com/ls.html! 
<script>! 
var count;! 
! 
count = localStorage.svcc || 0;! 
count++;! 
localStorage.svcc=count;! 
document.writeln(count);! 
</script>!
sessionStorage Uses 
• Good for storing status / tracking 
information for a domain.! 
• Information is shared across 
multiple windows (same domain).! 
• Information is local to the user, 
never sent over the wire.! 
• Persists when Browser is quit.
And Code / Data too 
• You can store any string….. thus! 
• You can store Code, data (JSON), 
CSS, lots of things…! 
• You could download all your 
JavaScript / CSS, store it and only 
update if you needed to.
Store Code, Store Data 
Can store code! 
localStorage.myCode =  
‘function HelloWorld()  
{  
alert(“Hello, World”);  
}’;! 
Can store data! 
localStorage.myData =  
‘{Days: [“Sun”, “Mon”, “Tue”, “Wed”,  
“Thu”, “Fri”, “Sat”],  
Months: [31, 28, 31, 30, 31, 30,  
31, 31, 30, 31, 30, 31]}’;!
Store JS in localStorage 
$('script[src]').map( 
function(idx, val) { 
var url, name; 
! 
url = $(val).attr('src'); 
name = url.replace(/[^a-zA-Z]/g,'-'); 
while (name[0] === '-') { 
name = name.slice(1); 
} 
! 
$.get(url, 
function (code) { 
localStorage[name] = code; 
}); 
});
7. AppCache (Manifest) 
• Can store any resource! 
• JavaScript! 
• CSS! 
• Images! 
• HTML! 
• Any file you like….
AppCache 
• Single “last modified” check can 
update lots of files! 
• Automatic fallback to the network! 
• Can work totally offline
AppCache 
<html manifest="cache.manifest"> 
CACHE MANIFEST 
NETWORK: 
* 
CACHE: 
/favicon.ico 
/index.html 
/js/lib/jquery.min.js 
/js/lib/mylibs.js 
/css/mainStyles.css 
//ajax.googleapis.com/ajax/libs/jquery/2.1.1/ 
jquery.min.js 
... 
You store any file you want…
AppCache Update Control 
• You - sort of - control this one.! 
• Can have different behaviors on 
different pages! 
• You store and update only when you 
want to 
% touch cache.manifest
AppCache References 
• www.html5rocks.com/en/tutorials/ 
appcache/beginner/! 
• alistapart.com/article/application-cache- 
is-a-douchebag! 
• www.whatwg.org/specs/web-apps/ 
current-work/multipage/ 
browsers.html#appcache
AppCache DEMO 
svcc.scribblings.com/appCache!
Putting it all together 
• PHP ByteCode for PHP caching! 
• $_SESSION’s for application state! 
• CDN for quick access! 
• Leverage Browser Cache when you can! 
• sessionStorage for runtime data! 
• localStorage for static data / code /css! 
• AppCache for everything
and… in the End 
Q &A

More Related Content

What's hot

Profiling php applications
Profiling php applicationsProfiling php applications
Profiling php applicationsJustin Carmony
 
Reverse proxy & web cache with NGINX, HAProxy and Varnish
Reverse proxy & web cache with NGINX, HAProxy and VarnishReverse proxy & web cache with NGINX, HAProxy and Varnish
Reverse proxy & web cache with NGINX, HAProxy and VarnishEl Mahdi Benzekri
 
Localstorage > Cookies
Localstorage > CookiesLocalstorage > Cookies
Localstorage > CookiesShane Riley
 
Introducing DynaTrace AJAX Edition
Introducing DynaTrace AJAX EditionIntroducing DynaTrace AJAX Edition
Introducing DynaTrace AJAX EditionKyoungtaek Koo
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit universityMandakini Kumari
 
What I learned from FluentConf and then some
What I learned from FluentConf and then someWhat I learned from FluentConf and then some
What I learned from FluentConf and then someOhad Kravchick
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHPDavid de Boer
 
Joomla plugin & module develpment - Presented at Sydney JUG 09/04/2013
Joomla plugin & module develpment - Presented at Sydney JUG 09/04/2013Joomla plugin & module develpment - Presented at Sydney JUG 09/04/2013
Joomla plugin & module develpment - Presented at Sydney JUG 09/04/2013Tim Plummer
 
Highload осень 2012 лекция 3
Highload осень 2012 лекция 3Highload осень 2012 лекция 3
Highload осень 2012 лекция 3Technopark
 
Nginx: Accelerate Rails, HTTP Tricks
Nginx: Accelerate Rails, HTTP TricksNginx: Accelerate Rails, HTTP Tricks
Nginx: Accelerate Rails, HTTP TricksAdam Wiggins
 
jsdom @ nodeconf 2011
jsdom @ nodeconf 2011jsdom @ nodeconf 2011
jsdom @ nodeconf 2011tmpvar
 
20100425 Configuration Management With Puppet Lfnw
20100425 Configuration Management With Puppet Lfnw20100425 Configuration Management With Puppet Lfnw
20100425 Configuration Management With Puppet Lfnwgarrett honeycutt
 

What's hot (20)

Profiling php applications
Profiling php applicationsProfiling php applications
Profiling php applications
 
Top ten-list
Top ten-listTop ten-list
Top ten-list
 
Reverse proxy & web cache with NGINX, HAProxy and Varnish
Reverse proxy & web cache with NGINX, HAProxy and VarnishReverse proxy & web cache with NGINX, HAProxy and Varnish
Reverse proxy & web cache with NGINX, HAProxy and Varnish
 
Localstorage > Cookies
Localstorage > CookiesLocalstorage > Cookies
Localstorage > Cookies
 
Introducing DynaTrace AJAX Edition
Introducing DynaTrace AJAX EditionIntroducing DynaTrace AJAX Edition
Introducing DynaTrace AJAX Edition
 
Php cookies
Php cookiesPhp cookies
Php cookies
 
Php sessions
Php sessionsPhp sessions
Php sessions
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 
What I learned from FluentConf and then some
What I learned from FluentConf and then someWhat I learned from FluentConf and then some
What I learned from FluentConf and then some
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHP
 
Joomla plugin & module develpment - Presented at Sydney JUG 09/04/2013
Joomla plugin & module develpment - Presented at Sydney JUG 09/04/2013Joomla plugin & module develpment - Presented at Sydney JUG 09/04/2013
Joomla plugin & module develpment - Presented at Sydney JUG 09/04/2013
 
Node.js
Node.jsNode.js
Node.js
 
Cookies in PHP
Cookies in PHPCookies in PHP
Cookies in PHP
 
Containers > VMs
Containers > VMsContainers > VMs
Containers > VMs
 
Highload осень 2012 лекция 3
Highload осень 2012 лекция 3Highload осень 2012 лекция 3
Highload осень 2012 лекция 3
 
Nginx: Accelerate Rails, HTTP Tricks
Nginx: Accelerate Rails, HTTP TricksNginx: Accelerate Rails, HTTP Tricks
Nginx: Accelerate Rails, HTTP Tricks
 
jsdom @ nodeconf 2011
jsdom @ nodeconf 2011jsdom @ nodeconf 2011
jsdom @ nodeconf 2011
 
hacking with node.JS
hacking with node.JShacking with node.JS
hacking with node.JS
 
Week 7 html css js
Week 7   html css jsWeek 7   html css js
Week 7 html css js
 
20100425 Configuration Management With Puppet Lfnw
20100425 Configuration Management With Puppet Lfnw20100425 Configuration Management With Puppet Lfnw
20100425 Configuration Management With Puppet Lfnw
 

Viewers also liked

A Look Back at the Great Recession
A Look Back at the Great RecessionA Look Back at the Great Recession
A Look Back at the Great RecessionDavid_Beckworth
 
Persistent mobile JavaScript
Persistent mobile JavaScriptPersistent mobile JavaScript
Persistent mobile JavaScriptYorick Phoenix
 
WTCManesar - Crux of All Successful Businesses
WTCManesar - Crux of All Successful BusinessesWTCManesar - Crux of All Successful Businesses
WTCManesar - Crux of All Successful BusinessesAN Buildwell
 
El banjo.Historia i descripció.
El banjo.Historia i descripció.El banjo.Historia i descripció.
El banjo.Historia i descripció.paugamez
 
Fuel Management Systems 2015
Fuel Management Systems 2015Fuel Management Systems 2015
Fuel Management Systems 2015Justin O'Donnell
 
The Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event HandlingThe Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event HandlingYorick Phoenix
 

Viewers also liked (9)

ATB2012-2
ATB2012-2ATB2012-2
ATB2012-2
 
A Look Back at the Great Recession
A Look Back at the Great RecessionA Look Back at the Great Recession
A Look Back at the Great Recession
 
Ranger ULN - Brochure
Ranger ULN - BrochureRanger ULN - Brochure
Ranger ULN - Brochure
 
Persistent mobile JavaScript
Persistent mobile JavaScriptPersistent mobile JavaScript
Persistent mobile JavaScript
 
WTCManesar - Crux of All Successful Businesses
WTCManesar - Crux of All Successful BusinessesWTCManesar - Crux of All Successful Businesses
WTCManesar - Crux of All Successful Businesses
 
El banjo.Historia i descripció.
El banjo.Historia i descripció.El banjo.Historia i descripció.
El banjo.Historia i descripció.
 
Fuel Management Systems 2015
Fuel Management Systems 2015Fuel Management Systems 2015
Fuel Management Systems 2015
 
The Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event HandlingThe Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event Handling
 
Mothaha village
Mothaha villageMothaha village
Mothaha village
 

Similar to Maximize caching for fast page loads with PHP, CDNs, browser storage

Lt local storage
Lt local storageLt local storage
Lt local storageYuzu Saijo
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSDegu8
 
Caching your rails application
Caching your rails applicationCaching your rails application
Caching your rails applicationArrrrCamp
 
Tuning Your SharePoint Environment
Tuning Your SharePoint EnvironmentTuning Your SharePoint Environment
Tuning Your SharePoint Environmentvmaximiuk
 
Notes on SF W3Conf
Notes on SF W3ConfNotes on SF W3Conf
Notes on SF W3ConfEdy Dawson
 
Accelerating Rails with edge caching
Accelerating Rails with edge cachingAccelerating Rails with edge caching
Accelerating Rails with edge cachingMichael May
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentationAnnujj Agrawaal
 
Php 07-cookies-sessions
Php 07-cookies-sessionsPhp 07-cookies-sessions
Php 07-cookies-sessionsYUSRA FERNANDO
 
Php file upload, cookies & session
Php file upload, cookies & sessionPhp file upload, cookies & session
Php file upload, cookies & sessionJamshid Hashimi
 
About Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JSAbout Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JSNaga Harish M
 
Going on an HTTP Diet: Front-End Web Performance
Going on an HTTP Diet: Front-End Web PerformanceGoing on an HTTP Diet: Front-End Web Performance
Going on an HTTP Diet: Front-End Web PerformanceAdam Norwood
 
Rails Caching: Secrets From the Edge
Rails Caching: Secrets From the EdgeRails Caching: Secrets From the Edge
Rails Caching: Secrets From the EdgeFastly
 
Rails Caching Secrets from the Edge
Rails Caching Secrets from the EdgeRails Caching Secrets from the Edge
Rails Caching Secrets from the EdgeMichael May
 
Building Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsBuilding Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsrobertjd
 
AD113 Speed Up Your Applications w/ Nginx and PageSpeed
AD113  Speed Up Your Applications w/ Nginx and PageSpeedAD113  Speed Up Your Applications w/ Nginx and PageSpeed
AD113 Speed Up Your Applications w/ Nginx and PageSpeededm00se
 
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
 
SenchaCon 2016 - How to Auto Generate a Back-end in Minutes
SenchaCon 2016 - How to Auto Generate a Back-end in MinutesSenchaCon 2016 - How to Auto Generate a Back-end in Minutes
SenchaCon 2016 - How to Auto Generate a Back-end in MinutesMalin Weiss
 

Similar to Maximize caching for fast page loads with PHP, CDNs, browser storage (20)

Lt local storage
Lt local storageLt local storage
Lt local storage
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
 
Caching your rails application
Caching your rails applicationCaching your rails application
Caching your rails application
 
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
 
Tuning Your SharePoint Environment
Tuning Your SharePoint EnvironmentTuning Your SharePoint Environment
Tuning Your SharePoint Environment
 
Notes on SF W3Conf
Notes on SF W3ConfNotes on SF W3Conf
Notes on SF W3Conf
 
Accelerating Rails with edge caching
Accelerating Rails with edge cachingAccelerating Rails with edge caching
Accelerating Rails with edge caching
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentation
 
Php 07-cookies-sessions
Php 07-cookies-sessionsPhp 07-cookies-sessions
Php 07-cookies-sessions
 
HTML5 Web storage
HTML5 Web storageHTML5 Web storage
HTML5 Web storage
 
Php file upload, cookies & session
Php file upload, cookies & sessionPhp file upload, cookies & session
Php file upload, cookies & session
 
About Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JSAbout Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JS
 
Going on an HTTP Diet: Front-End Web Performance
Going on an HTTP Diet: Front-End Web PerformanceGoing on an HTTP Diet: Front-End Web Performance
Going on an HTTP Diet: Front-End Web Performance
 
Building Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 FeaturesBuilding Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 Features
 
Rails Caching: Secrets From the Edge
Rails Caching: Secrets From the EdgeRails Caching: Secrets From the Edge
Rails Caching: Secrets From the Edge
 
Rails Caching Secrets from the Edge
Rails Caching Secrets from the EdgeRails Caching Secrets from the Edge
Rails Caching Secrets from the Edge
 
Building Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsBuilding Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTs
 
AD113 Speed Up Your Applications w/ Nginx and PageSpeed
AD113  Speed Up Your Applications w/ Nginx and PageSpeedAD113  Speed Up Your Applications w/ Nginx and PageSpeed
AD113 Speed Up Your Applications w/ Nginx and PageSpeed
 
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)
 
SenchaCon 2016 - How to Auto Generate a Back-end in Minutes
SenchaCon 2016 - How to Auto Generate a Back-end in MinutesSenchaCon 2016 - How to Auto Generate a Back-end in Minutes
SenchaCon 2016 - How to Auto Generate a Back-end in Minutes
 

Recently uploaded

Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 

Recently uploaded (20)

Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 

Maximize caching for fast page loads with PHP, CDNs, browser storage

  • 1. Maximize your Cache for no Ca$h Yorick Phoenix slides: slidesha.re/1vQDbOv about.me/yorickphoenix | @scribblings | github.com/yphoenix | yorick@issio.net
  • 2. Why Cache Stuff • What is a Cache and why do we want to cache data?! • Holds a copy for fast access.! • The nearer the data is to the user, the faster the access.! • Not just speed but latency and page load order.!
  • 3. Cache Downsides • Stale Data / Update Problems.! • Cache Synchronization.! • The more you do, the more work it is to do it.
  • 4. At least 7 Kinds of Cache 1. PHP OpCode Cache! 2. Session Variable Cache! 3. Browser Cache! 4. Content Delivery Network Cache! 5. SessionStorage! 6. LocalStorage! 7. AppCache / Manifests!
  • 5. 1. PHP ByteCode Cache • PHP byte code compiler parses the code into OpCode.! • To save having to do this more than once, it is cached.! • APC (alternative PHP Cache)! • XCache.! • OPCache (built-in from PHP 5.5 onwards)
  • 6. Advantages • Easy to configure! • Can also be used to cache your own information, not just OpCodes! • Great for code or site wide static data or statistical measurement! • php.net/manual/en/book.apc.php
  • 7. Install APC % pecl install APC % vi /etc/php.ini! extension=apc.so % sudo apachectl restart #or! % sudo kill -SIGUSR2 ! `cat /usr/var/run/php-fpm.pid`
  • 9. Storing non-code in APC apc_store($key, $value); apc_fetch($key); apc_inc($key); apc_dec($key); apc_delete($key);
  • 10. 2. $_SESSION Variables • The Web Server will store stuff for you. Any structure or data type like.! • You store a reference to this data in a cookie which you send with every page request.! • Stored until you delete it or it expires.! • php.net/manual/en/book.session.php
  • 11. How Sessions Work Get Session Info Server Browser /tmp/sess_SessionID Page Request (send sessionID) Save Session Info Page Response (receive sessionID) 1 2 3 4
  • 12. Session Example <?php! session_start();! 2 if (!isset($_SESSION['count'])) {! $_SESSION['count'] = 0;! } else {! $_SESSION['count']++;! }! ! echo $_SESSION[‘count’];! ?>! 3
  • 14. Session Security • Data stored securely on server, never downloaded to users Browser.! • Only SessionID transmitted to Browser.! • SessionID’s can be stolen, so always use a secure HTTPS connection.! • Store some unique token inside the session and store that in the browser, send with page request & validate
  • 15. 3. Browser Cache • The browser will cache stuff for you…! • Any file (css, js, html, jpg, png, etc)! • Two different expiration checks! • Expires in 'n' minutes! • Last modified
  • 16. Expires in ’n’ minutes • Specify how long to cache a file for.! • You need to work out in advance how often you are going to need to update your code.! • Once it is in the users browser with a cache expiration period, the browser isn’t going to re-download it without the user forcing it.
  • 17. Expires in ’n’ flow • Browser downloads file, with expiration! • When next requested, checks expiration! • If not expired, uses cached version! • If expired, requests a new version
  • 18. Enabling Apache Cache <IfModule mod_expires.c> ExpiresActive On ! # expire images after 24 hours ExpiresByType image/gif A86400 ExpiresByType image/jpeg A86400 ExpiresByType image/png A86400 ! # expire JavaScript & CSS after 4 hours ExpiresByType text/javascript A21600 ExpiresByType text/css A21600 </IfModule> ! www.mobify.com/blog/beginners-guide-to-http-cache- headers/ !www.mnot.net/cache_docs/
  • 19. Last Modified flow • Downloads file, with modification date! • When next requested, asks server if file is newer than date recorded! • If newer, downloads new version! • If not modified uses cache version
  • 20. Browser Cache Issues • Trade off of how long to cache vs how frequent to download! • If you update frequently then this needs to be small! • Results in more more frequent downloads or last modified checks! • You will always download more often than you really need to
  • 21. Browser Cache Updates • Unpredictable behavior! • Browser makes the decisions! • Don’t play the rename the file to update game
  • 22. Different Browsers • Different browsers cache things differently.! • Learn to use the debugging tools.! • Chrome, Safari, FireFox, IE.! • It's always a trade off.
  • 23. 4. Content Delivery Network • They help mitigate the Browser Cache Issue by moving the static data closer to the user.! • Automatic caching at a data center nearest your user! • Automatic redundancy of servers! • Basic level of service is FREE
  • 24. downloadSpeed: “fast” Cache your data & code as close to the user as you possibly can….
  • 25. Lots of CDN’s Use a good CDN and all this will be handled for you….
  • 26. Other CDN Pluses • You can edge cache static PHP if you want! • Replication of your static data takes the load off your primary server! • All for free and free SSL too
  • 27. 5. sessionStorage • Can store any arbitrary string! • Persist between page reloads! • Disappears when window / tab closed! • Stored on a Domain by Domain basis, window by window basis
  • 28. Session DEMO svcc.scribblings.com/ss.html! <script>! var count;! ! count = sessionStorage.svcc || 0;! count++;! sessionStorage.svcc=count;! document.writeln(count);! </script>!
  • 29. sessionStorage Uses • Good for storing status / tracking information between page loads! • Can have different information in different windows even for the same domain (unlike cookies).! • Information is local to the user, never sent over the wire.
  • 30. 6. localStorage • Can store any arbitrary string! • Persist between page reloads! • Persists when window closed! • Persists when browser quit! • Stored on a Domain by Domain basis
  • 31. Session DEMO svcc.scribblings.com/ls.html! <script>! var count;! ! count = localStorage.svcc || 0;! count++;! localStorage.svcc=count;! document.writeln(count);! </script>!
  • 32. sessionStorage Uses • Good for storing status / tracking information for a domain.! • Information is shared across multiple windows (same domain).! • Information is local to the user, never sent over the wire.! • Persists when Browser is quit.
  • 33. And Code / Data too • You can store any string….. thus! • You can store Code, data (JSON), CSS, lots of things…! • You could download all your JavaScript / CSS, store it and only update if you needed to.
  • 34. Store Code, Store Data Can store code! localStorage.myCode = ‘function HelloWorld() { alert(“Hello, World”); }’;! Can store data! localStorage.myData = ‘{Days: [“Sun”, “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”], Months: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]}’;!
  • 35. Store JS in localStorage $('script[src]').map( function(idx, val) { var url, name; ! url = $(val).attr('src'); name = url.replace(/[^a-zA-Z]/g,'-'); while (name[0] === '-') { name = name.slice(1); } ! $.get(url, function (code) { localStorage[name] = code; }); });
  • 36. 7. AppCache (Manifest) • Can store any resource! • JavaScript! • CSS! • Images! • HTML! • Any file you like….
  • 37. AppCache • Single “last modified” check can update lots of files! • Automatic fallback to the network! • Can work totally offline
  • 38. AppCache <html manifest="cache.manifest"> CACHE MANIFEST NETWORK: * CACHE: /favicon.ico /index.html /js/lib/jquery.min.js /js/lib/mylibs.js /css/mainStyles.css //ajax.googleapis.com/ajax/libs/jquery/2.1.1/ jquery.min.js ... You store any file you want…
  • 39. AppCache Update Control • You - sort of - control this one.! • Can have different behaviors on different pages! • You store and update only when you want to % touch cache.manifest
  • 40. AppCache References • www.html5rocks.com/en/tutorials/ appcache/beginner/! • alistapart.com/article/application-cache- is-a-douchebag! • www.whatwg.org/specs/web-apps/ current-work/multipage/ browsers.html#appcache
  • 42. Putting it all together • PHP ByteCode for PHP caching! • $_SESSION’s for application state! • CDN for quick access! • Leverage Browser Cache when you can! • sessionStorage for runtime data! • localStorage for static data / code /css! • AppCache for everything
  • 43. and… in the End Q &A