Varnish http cache

65
HTTP Cache + Varnish Web sites performance optimization

Transcript of Varnish http cache

Page 1: Varnish http cache

HTTP Cache + Varnish

Web sites performance optimization

Page 2: Varnish http cache

Desarrollador PHP desde

septiembre de 2007

Buscando curro!!!

@desarrolla2

Page 3: Varnish http cache

GWT: Asegura que mi sitio es lento On average, pages in your site take 2.2 seconds to load (updated on Mar 21, 2012). This is faster than 63% of sites.

¿Por qué?

Page 4: Varnish http cache

HTTP Cache

Web sites performance optimization

Page 5: Varnish http cache

"Es (posiblemente) el sistema de cache que más eficaz y fácil de

implementar."- Daniel González

¿Por qué?

Page 6: Varnish http cache
Page 7: Varnish http cache
Page 8: Varnish http cache

"Nunca generar la misma respuesta dos

veces."- Alguien

Objetivo

Page 9: Varnish http cache

"Es un protocolo de cache que debería ser respetado por todas las capas intermedias y

por los navegadores."

HTTP Cache

Page 10: Varnish http cache

"En la mayoría de los casos es la mejor estrategia de cache."

HTTP Cache: Freshness

Page 11: Varnish http cache
Page 12: Varnish http cache
Page 13: Varnish http cache

Cache-ControlPublic, PrivateNo-Cache, No-storemax-age, s-maxagemust-revalidate// ..

Cache-Control: Public, s-maxage:3600, must-revalidate

ExpiresExpires Tue, 20 Mar 2012 11:21:13 GMT

HTTP Cache: Freshness

Page 14: Varnish http cache

PragmaPragma: Private, max-age:3600

HTTP Cache: Freshness

Page 15: Varnish http cache

$response->setMaxAge(15 * 60); $response->setExpires(new \DateTime('now + 15 minutes'));// ..

HTTP Cache: Freshness

Page 16: Varnish http cache

header("Cache-Control:...");header("Pragma:...");// ..

HTTP Cache: Freshness

Page 17: Varnish http cache

<meta http-equiv="Cache-Control" content="max-age=3600, private">

HTTP Cache: Freshness

Page 18: Varnish http cache

<filesMatch "\.(js|css)$">Header set Cache-Control "private, max-age=7200"

</filesMatch>

HTTP Cache: Freshness

Page 19: Varnish http cache

"Cuando no puedes predecir la frecuencia

con la que cambian tus recursos."

HTTP Cache: Validation

Page 20: Varnish http cache
Page 21: Varnish http cache
Page 22: Varnish http cache

Last-ModifiedLast-Modified: Tue, 15 Nov 1994 12:45:26 GMT

EtagETag: "3e86-410-3596fbbc"

HTTP Cache: Validation

Page 23: Varnish http cache

HTTP Cache: Validation

$response->setLastModified(new \DateTime('2000-01-01'));$response->setEtag(md5($response->getContent()));// .. $response->setCache(array());

Page 24: Varnish http cache

HTTP Cache: Validation

<filesMatch ".(gif|jpg|jpeg|png|mpg|avi)$">Header set Last-modified "Mon, 03 Jan 2011 13:02:54

GMT"</filesMatch>

Page 25: Varnish http cache

HTTP/1.1 200 OKDate: Fri, 30 Oct 1998 13:19:41 GMTCache-Control: public, s-maxage=3600Expires: Fri, 30 Oct 1998 14:19:41 GMTLast-Modified: Mon, 29 Jun 1998 02:28:12 GMTETag: "3e86-410-3596fbbc"// ..

HTTP Cache

Page 26: Varnish http cache
Page 27: Varnish http cache
Page 28: Varnish http cache
Page 29: Varnish http cache
Page 30: Varnish http cache

HTTP Cache: Friendly URL's

http://misite.com/es/home-user/welcome/ http://misite.com/welcome.php/?country=es&usertype=home-user

Page 31: Varnish http cache

<esi:include src="http://misite.com/header.php" /> ● include_partial()● {% render %} http://www.w3.org/TR/esi-lang

ESI

Page 32: Varnish http cache

ESI

Page 33: Varnish http cache
Page 34: Varnish http cache

Puede ser ignorado

Una cache en cada cliente

Invalidar la cache

Estandar no es claro

Page 35: Varnish http cache

http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html

Page 36: Varnish http cache

Varnish

HTTP Accelerator

Page 37: Varnish http cache

"Varnish is a web application

accelerator. You install it in front of your web application and it will

speed it up significantly."

¿Por que?

Page 38: Varnish http cache

"Rápido, Flexible y

Escalable"

¿Por que?

Page 39: Varnish http cache

Varnish: http cache

Page 40: Varnish http cache
Page 41: Varnish http cache

Reverse Proxy

Proxy Cache

¿Que es?

Page 42: Varnish http cache

Fail Over System

Load Balancer

¿Que es?

Page 43: Varnish http cache

Obedece cabeceras HTTP Cache

Cache de recursos estáticos

Modifica las cabeceras y las cookies de

peticiones y respuestas

Caracteristicas

Page 44: Varnish http cache

¿Quien?

Page 45: Varnish http cache

¿Cómo?

Page 46: Varnish http cache

sudo apt-get install varnishsudo vim /etc/varnish/default.vcl

backend default {.host = "127.0.0.1";.port = "8080";

}

Instalación

sudo vim /etc/apache2/ports.confListen 8080

Page 47: Varnish http cache

sudo vim /etc/default/varnishSTART=yes // DAEMON_OPTS="-a :8080 \ // puerto -T localhost:6082 \ -f /etc/varnish/default.vcl \ // vlc script -S /etc/varnish/secret \ //cli autentication -s file,/var/lib/varnish/$INSTANCE/varnish_storage.bin,1G" //storage, malloc mantendría los objetos en memoria

Instalación

https://www.varnish-cache.org/docs/2.1/installation/install.html

Page 48: Varnish http cache

<FilesMatch "\.(flv|gif|jpg|jpeg|png|ico|swf)$"> Header set Cache-Control "max-age=2592000"</FilesMatch><FilesMatch "\.(css|js)$"> Header set Cache-Control "max-age=604800"</FilesMatch>

Varnish: assets

$ ab -n 2000 -c 100 http://sfm.desarrolla2.com/bundles/sfmwebsite/images/titulo-symfony-madrid.png

Page 49: Varnish http cache
Page 50: Varnish http cache

Subroutines

vcl_recv / vcl_fetch / vcl_deliver / vcl_hash / vcl_miss / vcl_hit / vcl_error / ...

Actions

pass / lookup / pipe / deliver

Objects

req / beresp / obj

Varnish Configuration Language

Page 51: Varnish http cache
Page 52: Varnish http cache

sub vcl_recv { if (req.request == "GET" && req.url ~ "\.(jpg|jpeg|gif|png)$") { unset req.http.Cookie; return(lookup); }} sub vcl_fetch {

if (req.url ~ "\.(jpg|jpeg|gif|png)$") {unset beresp.http.set-cookie;

}}

Varnish: cookies

Page 53: Varnish http cache

sub vcl_fetch { if (!beresp.cacheable) { return (pass); } set beresp.http.Server = "SFM Server 1.0" ; return (deliver); }

Varnish: Headers

Page 54: Varnish http cache

sub vcl_deliver {if (obj.hits > 0) {

set resp.http.X-Cache = "HIT " obj.hits;} else {

set resp.http.X-Cache = "MISS";}return (deliver)

}

Varnish: Headers

$ curl - I http://sfm.desarrolla2.com/bundles/sfmwebsite/images/titulo-symfony-madrid.png

Page 55: Varnish http cache
Page 56: Varnish http cache

Varnish: invalidar la caché

acl purge{ "localhost"; "192.168.55.0"/24;} if (req.request == "PURGE") {

if (!client.ip ~ purge) {error 405 "Not allowed.";

}}

Page 57: Varnish http cache

Varnish: invalidar la caché

sub vcl_hit { if (req.request == "PURGE") { set obj.ttl = 0s; error 200 "Purged"; }}

sub vcl_miss { if (req.request == "PURGE") { error 404 "Not purged"; }}

Page 58: Varnish http cache

Varnish vs Memcached

En el momento en el que el recurso ha caducado. publico.es

Page 59: Varnish http cache

Symfony2 Reverse Proxy

Page 60: Varnish http cache

Varnish: invalidar la caché

<?php require_once __DIR__.'/../app/bootstrap.php.cache';require_once __DIR__.'/../app/AppKernel.php';//require_once __DIR__.'/../app/AppCache.php'; use Symfony\Component\HttpFoundation\Request; $kernel = new AppKernel('prod', false);$kernel->loadClassCache();//$kernel = new AppCache($kernel);$kernel->handle(Request::createFromGlobals())->send();

Page 61: Varnish http cache

"con HTTP Cache + Varnish el rendimiento de tu sitio mejorará

notablemente"

Conclusiónes

Page 62: Varnish http cache

"HTTP Cache + Varnish por si solo son insuficiente, necesitas utilizar

otras técnicas, como carga asincrona de recursos, minimización, ect..."

Conclusiónes

Page 63: Varnish http cache
Page 64: Varnish http cache
Page 65: Varnish http cache