Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Maximize your Cache for No Cash


Published on

There are seven levels of cache between your code and the users browser experience. You can take advantage of them all to provide a quicker, slicker, better user experience for the user and it won't cost you a dime to do it. You can use an OpCode Cache on the Server, a Content Development Network (for free), make use of the browser cache, setup an App Cache, use Session and Local Storage. They are all there, they are all free and this talk will go over all of them, the pros and the few downsides.

Published in: Software
  • Be the first to comment

Maximize your Cache for No Cash

  1. 1. Maximize your Cache for no Ca$h Yorick Phoenix slides: | @scribblings | |
  2. 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. 3. Cache Downsides • Stale Data / Update Problems.! • Cache Synchronization.! • The more you do, the more work it is to do it.
  4. 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. 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. 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! •
  7. 7. Install APC % pecl install APC % vi /etc/php.ini! % sudo apachectl restart #or! % sudo kill -SIGUSR2 ! `cat /usr/var/run/`
  8. 8. APC Status http:/localhost/apc.php
  9. 9. Storing non-code in APC apc_store($key, $value); apc_fetch($key); apc_inc($key); apc_dec($key); apc_delete($key);
  10. 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.! •
  11. 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. 12. Session Example <?php! session_start();! 2 if (!isset($_SESSION['count'])) {! $_SESSION['count'] = 0;! } else {! $_SESSION['count']++;! }! ! echo $_SESSION[‘count’];! ?>! 3
  13. 13. Session DEMO!
  14. 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. 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. 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. 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. 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> ! headers/ !
  19. 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. 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. 21. Browser Cache Updates • Unpredictable behavior! • Browser makes the decisions! • Don’t play the rename the file to update game
  22. 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. 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. 24. downloadSpeed: “fast” Cache your data & code as close to the user as you possibly can….
  25. 25. Lots of CDN’s Use a good CDN and all this will be handled for you….
  26. 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. 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. 28. Session DEMO! <script>! var count;! ! count = sessionStorage.svcc || 0;! count++;! sessionStorage.svcc=count;! document.writeln(count);! </script>!
  29. 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. 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. 31. Session DEMO! <script>! var count;! ! count = localStorage.svcc || 0;! count++;! localStorage.svcc=count;! document.writeln(count);! </script>!
  32. 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. 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. 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. 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. 36. 7. AppCache (Manifest) • Can store any resource! • JavaScript! • CSS! • Images! • HTML! • Any file you like….
  37. 37. AppCache • Single “last modified” check can update lots of files! • Automatic fallback to the network! • Can work totally offline
  38. 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 // jquery.min.js ... You store any file you want…
  39. 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. 40. AppCache References • appcache/beginner/! • is-a-douchebag! • current-work/multipage/ browsers.html#appcache
  41. 41. AppCache DEMO!
  42. 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. 43. and… in the End Q &A