A presentation at Devtalks in in Bucharest, Romania by Holger Bartel
Take Control of Cache-Control
Holger Bartel Designer/Developer Hong Kong Twitter: @foobartel
Fact A majority of the data on the internet is static and unlikely to change over time. Many of today’s web performance issues are related to images, fonts and video.
What is Cache?
Cache not Cash!
C n o i t a i c ) o e s H s C A A y C c ( n e a g v a r t e i r s e n o H r C o e f h T e r t n e Not!
Cache Is A Storage ✤ ✤ Store away in hiding or for future use. Helper memory enabling high-speed retrieval of data. https://en.oxforddictionaries.com/definition/cache
Origin Late 18th century: from French, from cacher ‘to hide’.
for ( i = 0; i < count( AllTheThings ); i++ ) { … }
Store a value in a variable for better performance.
let items = count( AllTheThings ); for ( i = 0; i < items; i++ ) { … }
Store a value in a variable for better performance.
Developers know caching best from $clients
F5! http://clearyourcache.com
Blame the Cache! http://www.commitstrip.com/en/2013/03/29/il-a-bon-dos-le-cache/
A good excuse ;) http://www.commitstrip.com/en/2013/03/29/il-a-bon-dos-le-cache/
The cache exists because of a basic assumption made by browser designers: The internet is slow.
Caching is a technique that stores a copy of a given resource and serves it back when requested.
Why Care?
The First Impression We always want to make a great first impression. A fast loading site does just that.
Photo: @helloanselm
The cache serves what you already have, as long as it’s fresh. Photo: @helloanselm
2ND Great Impression? How To Delight Our Users
WANTED ! CUSTOMER LOYALTY $$$ REWARD $$$ LOYAL USER == REPEAT VISITOR FOR ALL EXTRA PERFORMANCE BENEFITS
Average Bytes per Page by Content Type CSS 107Kb HTML 55Kb Images 2,076Kb Source Scripts 525Kb Fonts 137Kb Video 346Kb Other 10Kb Total 3272Kb
Cache Lifetime (Days) 100% 80% 60% 47% 40% 20% 0% Source 13% t=0 0 <= t <= 1 18% 17% 5% 1 <= t <= 30 30 <= t <= 365 t > 365
Cacheable Resources Over Last Year Over Last 6 Years
~50% of all traffic could be cached!
Global Internet Traffic ✤ ✤ 3.138.420 GB per Minute in 2018 Annual global IP traffic will reach 4.8 ZB per year by 2022
ZB (Zettabyte) 1 ZB Zettabyte = 1.099.511.627.776 GB
Responsible Design
Advantages ✤ ✤ Eases the load on the server; Improves performance, b/c it takes less time to transmit the resource.
How Does Caching Work?
Without Any Caching in Place All identical requests are going through to the server Source
Local (Private) Cache The first request of each client is going through to the server. Identical, subsequent requests are not even sent, but served by the local cache. Source
Shared Cache The first request of each client is going through to the server. Identical, subsequent requests are served by the shared cache. Source
Private Cache Shared Cache A private cache is dedicated to a single user. A shared cache can be reused by more than one user.
Empty Cache Primed Cache The browser makes the first request to the page. The browser has a cached version of the page.
Cache Hit Cache Miss A requested resource is found in cache. A resource is not found in cache and has to be fully requested from its origin.
Fresh Stale When a resource is fresh, it can be served from cache. A stale resource has expired and will not be served anymore.
Disk Cache Memory Cache Lifetime: Restart Lifetime: Render Process, Browser Tab Disk cache is RAM memory Fast! Located on the CPU chip Faster!
TIME It’s To Take Control
History of HTTP Protocol ✤ HTTP/0.9 – The one-line protocol ✤ HTTP/1.0 – Building extensibility ✤ HTTP/1.1 – The standardized protocol
Chrome DevTools
Headers
Pragma: no-cache Pragma is a HTTP/1.0 header and not a reliable replacement for the general HTTP/1.1 CacheControl header.
Expires: Fri, 30 Oct 2019 14:19:41 GMT The Expires header contains the date/time after which the response is considered stale.
If there is a Cache-Control header with the max-age or s-maxage directive in the response, the Expires header is ignored.
The Cache-Control HTTP/1.1 general-header field is used to specify directives for caching mechanisms in both requests and responses.
Cache-Control Directives Source
cache-control: public The response may be cached by any cache, even if the response would normally be non-cacheable.
cache-control: private The response is intended for a single user and must not be stored by a shared cache. A private cache may store the response.
cache-control: max-age=86400 Response can be cached by browser and any intermediary caches (“public”) for up to 1 day.
cache-control: private, max-age=600 Response can be cached by the client’s browser only for up to 10 minutes (60 seconds x 10 minutes).
cache-control: no-cache Forces the cache to validate the request before releasing a cached copy.
cache-control: no-store ✤ Response is not allowed to be cached ✤ Must be fetched in full on every request.
cache-control: max-age=0 A max-age of 0 equals no-store.
cache-control: s-maxage=<seconds> ✤ ✤ Takes precedence over max-age or the Expires header, but only applies to shared caches (e.g., proxies) ; Ignored by a private cache.
cache-control: no-transform No transformations or conversions should be made to the resource. The Content-Encoding, Content-Range, Content-Type headers must not be modified by a proxy.
cache-control: must-revalidate If a resource has become stale, a cache must not use the response without successful validation.
cache-control: immutable Indicates that the response body will not change over time.
Build Your Caching Strategy And An Invalidation Strategy
Cache Invalidation Terms ✤ Hashing ✤ Cachebusting ✤ Revving
Cachebusting Options ✤ /assets/css/styles.css?v1.2 ✤ /assets/16415ef98913c2bcb2c/default.css ✤ /assets/js/main.16415ef9891.js
Apache - .htaccess Header set Cache-Control “max-age=31536000, public”
Apache - .htaccess <filesMatch “.(jpg|jpeg|png|gif|ico)$”> Header set Cache-Control “max-age=31536000, public, immutable” </filesMatch> <filesMatch “.(css|js)$”> Header set Cache-Control “max-age=31536000, public” </filesMatch>
PHP header()
<?php header(“Cache-Control: no-cache, must-revalidate”); header(“Cache-Control: Sat, 26 Jul 1997 05:00:00 GMT”); ?>Nginx - configuration file location ~* .(js|css|png|jpg|jpeg|gif|ico)$ { add_header Cache-Control “public, no-transform”; }
Cache As Much As You Can
cache-control: public, max-age=31536000 ✤ ✤ For files that won’t change, you can add aggressive caching; Likely for images, CSS and JavaScript.
cache-control: public, immutable ✤ More aggressive; ✤ CSS and JavaScript; ✤ Don’t forget your invalidation strategy!
<FilesMatch “^(never-changing—icon.svg)$”> Header set Cache-Control “max-age=31536000, public, immutable” </FilesMatch>
Summary
✤ We can limit traffic and spare sending lots of bytes ✤ Reward your loyal repeat visitors ✤ Improve overall web performance
✤ Create your invalidation/cachebusting strategy ✤ Ensure that the server provides an ETag ✤ Which resources can be cached publicly or private? ✤ Determine the best cache lifetime for your resources ✤ How aggressively can you cache your assets?
Thank You! Visit foobartel.com or Twitter: @foobartel
Over recent years we have seen many ways how to improve web performance and create faster websites. Yet, one easily and often overlooked way for optimisation is Cache-Control. A good caching strategy can drastically decrease the number of HTTP requests, downloads and save valuable bandwidth, especially for loyal repeat visitors. In this talk you’ll learn when & how to cache your assets and leverage the full potential of Cache-Control to create faster and more responsible websites.