Date post: | 12-Apr-2017 |
Category: |
Software |
Upload: | yorick-phoenix |
View: | 624 times |
Download: | 1 times |
Maximize your Cache for no Ca$h
Yorick Phoenixslides: slidesha.re/1vQDbOv
about.me/yorickphoenix | @scribblings | github.com/yphoenix | [email protected]
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 Cache1. 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`
Storing non-code in APCapc_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
Browser
Server
/tmp/sess_SessionID
Page Request (send sessionID)
Page Response (receive sessionID)
Save Session InfoGet Session Info
1
23
4
Session Example<?php!session_start();!if (!isset($_SESSION['count'])) {! $_SESSION['count'] = 0;!} else {! $_SESSION['count']++;!}!!
echo $_SESSION[‘count’];!?>!
2
3
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
<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/
Enabling Apache Cache
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
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 DEMOsvcc.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 DEMOsvcc.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.
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 Code, Store Data
$('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; }); });
Store JS in localStorage
• Can store any resource!
• JavaScript!
• CSS!
• Images!
• HTML!
• Any file you like….
7. AppCache (Manifest)
• Single “last modified” check can update lots of files!
• Automatic fallback to the network!
• Can work totally offline
AppCache
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 References
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