http caching with varnish
TRANSCRIPT
HTTPcaching
withVarnish
DPC,June27th2015
DavidBuchmann&DaviddeBoer
ThisthingcalledVarnish
# apt-get install varnish
Edit/etc/default/varnish
Replaceport6081with80
# service varnish restart
Webserveronport8080
# service apache2 restart
Whatcouldpossiblygo
wrong?
Nothinggetscached
Toomuchgetscached
Editorsseenochanges
Cachesgetmixedup
Let’stakeastepback
HTTPissimple
GET /path
HTTP/1.1 200 OKContent-Type: text/html
...
Defaultbehaviour
OnlyGETandHEADarecached
Cachefor2minutes
RequestswithCookie/Authorizationarenotcached
ResponseswithSet-Cookiearenotcached
Cachecontrolheaders
Cache-Control: s-maxage=3600, max-age=900Expires: Sat, 27 June 2015 09:58:00 GMT
Cachecontrolheaders
Settheminyourapp,notinVarnish
Cache-Control: s-maxage=3600, max-age=900Expires: Sat, 27 June 2015 09:58:00 GMT
Donotcache
Cache-Control: s-maxage=0, private, no-cache
Cachevalidation
ETag
Uniqueresourcefingerprint
ClientsendsETag
Stillthesame?304Not-Modified
PreferETagoverLast-Modified
curl -o /dev/null -sD - http://fos.lo/path
curl -o /dev/null -sD - http://fos.lo/path
HTTP/1.1 200 OKDate: Fri, 22 Jun 2015 19:23:02 GMTCache-Control: s-maxage=30Vary: Accept-EncodingContent-Type: application/jsonAge: 23ETag: 4423466221248
PlainPHP
header('Cache-Control: s-maxage=600, max-age=60');header('Etag: ' . sha1($data));
PlainPHP
Dothisbeforeanyoutputissenttotheclient
header('Cache-Control: s-maxage=600, max-age=60');header('Etag: ' . sha1($data));
Symfony
// DefaultController::indexAction$response = $this->render('::index.html.twig');$response->setSharedMaxAge(600);$response->setMaxAge(60);$response->setEtag(sha1($response->getContent()));
return $response;
Symfony
Addaboveorannotationtoeveryaction
// DefaultController::indexAction$response = $this->render('::index.html.twig');$response->setSharedMaxAge(600);$response->setMaxAge(60);$response->setEtag(sha1($response->getContent()));
return $response;
FOSHttpCacheBundle
app/config/config.yml:
match: path: "^/articles"headers: cache_control: s_maxage: 600 max_age: 60 etag: true
Overview
VCL
Invalidation
Tagging
VCL
Cookies
sub vcl_recv { if (req.http.Authorization || req.http.Cookie) { return (pass); }
return (hash);}
Removecookies
Removecookies
sub vcl_recv { if (req.http.Cookie) { if (req.url ~ "^/static") { unset req.http.Cookie; } }}
Removecookies
Addstodefaultbehaviour
sub vcl_recv { if (req.http.Cookie) { if (req.url ~ "^/static") { unset req.http.Cookie; } }}
Invalidation
Thereareonlytwohardthingsincomputerscience:
Cacheinvalidation
Namingthings
Offbyoneerrors
Invalidation
Activelyremoveresponsefromcache
LongTTL
Morehits
Invalidation
Activelyremoveresponsefromcache
LongTTL
Morehits
Remember:bustyourassets!
Invalidationflavours
Purge:URLandvariants
Refresh:exactrequest,warmcache
Ban:batchwithregularexpressions
Invalidationflavours
Purge:URLandvariants
Ban:batchwithregularexpressions
Purge
ConfigureVarnish
acl invalidators { "localhost";}
vcl_recv { if (req.method == "PURGE") { if (!client.ip ~ invalidators) { return (synth(405, "Not allowed")); } return (purge); }}
FOSHttpCache
$cacheInvalidator->invalidatePath('/my/path');...$cacheInvalidator->flush();
Ban
Banispowerful
Regularexpressions
URL
Andanyrequestheader
CustomVarnishconfiguration
CachetaggingCachetagging
Settags
Whencomment-1changes:
BANrequestforX-Cache-Tagsthatmatchon:comment-1(,.+)?
X-Cache-Tags: comment-1, comment-2
Invalidatetags
sub vcl_recv { # ... ban("obj.http.x-cache-tags ~ " + req.http.x-cache-tags ); # ...}
FOSHttpCacheBundle
$tagHandler->addTag(['comment-1', 'comment-2']);
$tagHandler->invalidateTags(['comment-1']);
use FOS\HttpCacheBundle\Configuration\Tag;
class CommentController extends Controller { /** * @Tag({"comments", "'comment-'~id"}) */ public function commentAction($id) {
Wrap-up
IncreaseyourhitsIncreaseyourhits
Removecookieswherepossible
Cacheauthenticatedcontent
IncreaseTTL
Inspectcachemisses:
varnishtop -i BereqURL
FOSHttpCache
Well-testedVarnishintegrationforPHPapps
Providestestingtools
Cacheauthenticatedcontentbygroup
AlsoforNginx&SymfonyHttpCache
Extensivedocumentation
Symfonybundle
Version2.0:PSR-7,VCLfunctions
KISSVCL
Applicationperformance
Frontendperformance
Questions,input,feedback?Twitter:
@dbu@ddeboer_nl
https://joind.in/14240
Varnish4
Client/backendseparation
SimplerVCL
FinallytakesCache-Controlseriously
Usercontextcaching
Cacheauthenticatedresponses
Cacheforgroupsofusers
Letbackenddecideongroups
ESI
<html> <body> Main body. <esi:include src="/esi-fragment.php" /> </body></html>
Content-negotation
Needtokeepvariantsapart
Request:
Response:
Accept: application/json
Vary: Accept