SlideShare a Scribd company logo
Varnish
Sumário Caching em HTTP
Varnish Workshop
Caching em HTTP Como funciona um “Acelerador Web” (Reverse Proxy Cache) Expiração (headers Cache-Control, Age e Expires)
Validação (headers Last-Modified, Etag, If-Modified-Since, If-None-Modified)
Browser -> Cache -> Backend
Expiração por tempo
 
 
Validação por controle
 
 
Combinando Expiração e Validação
 
 
 
Varnish workshop Elementos do vcl
Fluxo e objetos
Hash
Métodos HTTP
Misc: set/unset, regexp, ttl, headers de diagnóstico
Persistência: como funciona o grace
Ferramentas auxiliares: varnishlog, varnishncsa, varnishadm
Purge/Ban
Elementos do vcl Os elementos básicos do vcl são: Backend Aqui são especificados os parâmetros de comunicação com o backend e probe (healthcheck) – semelhante à um VIP  Subrotinas e módulos Subrotinas não retornam valores
Além das rotinas pré-definidas (que determinam o fluxo do Varnish) podem ser criadas subrotinas customizadas
Módulo pode retornar a localização geográfica de um endereço IP ou usar o varnish como um cliente HTTP e buscar cabeçalhos e corpo nos backends Acls Includes Inline C
backend backend ig { .host = "vip.be.infra";   .probe = {   .url = "/healthcheck.html";   .timeout = 34 ms;   .interval = 1s;   .window = 10;   .threshold = 8; } } director baz round-robin { { .backend = ig; } { .backend = com; } }
acl acl purge { "localhost"; "127.0.0.1"; "10.0.0.0"/8; } acl header { "localhost"; "200.200.100.100"; "10.0.0.0"/8; }
Include e sub include ”/etc/varnish/functions.inc"; --- sub normalize_user_agent { if(req.http.User-Agent ~ "iPhone|Android") { set req.http.User-Agent = "mobile"; } else {  remove req.http.user-agent; } }
Varnish: Fluxo e Objetos
 
Hash sub vcl_hash { if (req.http.user-agent ~ "mobile") {   hash_data(req.http.user-agent); } # Vital para virtualhosts hash_data(req.url); hash_data(req.http.host); return (hash); }

More Related Content

PPTX
Varnish
PDF
2016 W3C Conference #4 : ANGULAR + ES6
PDF
Shell Script Disk Usage Report and E-Mail Current Threshold Status
PDF
Troubleshooting PostgreSQL with pgCenter
PDF
Nine Circles of Inferno or Explaining the PostgreSQL Vacuum
PDF
Varnish presentation for the Symfony Zaragoza user group
KEY
Varnish @ Velocity Ignite
PDF
PostgreSQL Troubleshoot On-line, (RITfest 2015 meetup at Moscow, Russia).
Varnish
2016 W3C Conference #4 : ANGULAR + ES6
Shell Script Disk Usage Report and E-Mail Current Threshold Status
Troubleshooting PostgreSQL with pgCenter
Nine Circles of Inferno or Explaining the PostgreSQL Vacuum
Varnish presentation for the Symfony Zaragoza user group
Varnish @ Velocity Ignite
PostgreSQL Troubleshoot On-line, (RITfest 2015 meetup at Moscow, Russia).

What's hot (20)

PDF
Learning Dtrace
PPTX
June8 presentation
PDF
Varnish Web Accelerator
PDF
Deep dive into PostgreSQL statistics.
ODP
Caching and tuning fun for high scalability
PDF
Make Your Life Easier With Maatkit
PDF
톰캣 #04-환경설정
ODP
Caching and tuning fun for high scalability @ PHPTour
PPT
Find bottleneck and tuning in Java Application
PDF
Matteo Collina | Take your HTTP server to Ludicrous Speed | Codmeotion Madrid...
PDF
GitLab PostgresMortem: Lessons Learned
PDF
NetApp ontap simulator
PDF
Using Perl Stored Procedures for MariaDB
PDF
tokyo.vcl発表資料(varnish+squid)
PDF
BATTLESTAR GALACTICA : Saison 5 - Les Cylons passent dans le cloud avec Vert....
PDF
External Language Stored Procedures for MySQL
ODP
Varnish: Making eZ Publish sites fly
PDF
PostgreSQL Streaming Replication Cheatsheet
PDF
Managing PostgreSQL with PgCenter
PDF
Codified PostgreSQL Schema
Learning Dtrace
June8 presentation
Varnish Web Accelerator
Deep dive into PostgreSQL statistics.
Caching and tuning fun for high scalability
Make Your Life Easier With Maatkit
톰캣 #04-환경설정
Caching and tuning fun for high scalability @ PHPTour
Find bottleneck and tuning in Java Application
Matteo Collina | Take your HTTP server to Ludicrous Speed | Codmeotion Madrid...
GitLab PostgresMortem: Lessons Learned
NetApp ontap simulator
Using Perl Stored Procedures for MariaDB
tokyo.vcl発表資料(varnish+squid)
BATTLESTAR GALACTICA : Saison 5 - Les Cylons passent dans le cloud avec Vert....
External Language Stored Procedures for MySQL
Varnish: Making eZ Publish sites fly
PostgreSQL Streaming Replication Cheatsheet
Managing PostgreSQL with PgCenter
Codified PostgreSQL Schema
Ad

Similar to Varnish qconsp 2011 (20)

PDF
The Subtle Art Of Cache Invalidation (FOSSingapore 2024)
PDF
Varnish Enterprise - when you need the full power of caching
PDF
Varnish
PDF
Best practices for caching Plone with Varnish at large scale - PloneConf Bras...
PDF
Optimizing Varnish for Magento: Advanced Techniques for Performance and Scala...
PDF
Varnish Cache
PPTX
cache concepts and varnish-cache
PPT
Aspnet Caching
PDF
Varnish Cache Plus. Random notes for wise web developers
ODP
Caching and tuning fun for high scalability @ FOSDEM 2012
PDF
High Availability Content Caching with NGINX
PDF
Supercharging Content Delivery with Varnish
PPT
awergaezrg
PPT
sergaerwga
PPT
aergserga
PPT
sakdjfhaksjfhaskjh
PPT
aksdfhaskdjfhasdjkh
PPT
askldjfhaskdfj aslkdjfhaskdfhasjk askldf ashkdf
PPT
salkdjfhdjkghdfkjh
PPTX
Solving anything in VCL
The Subtle Art Of Cache Invalidation (FOSSingapore 2024)
Varnish Enterprise - when you need the full power of caching
Varnish
Best practices for caching Plone with Varnish at large scale - PloneConf Bras...
Optimizing Varnish for Magento: Advanced Techniques for Performance and Scala...
Varnish Cache
cache concepts and varnish-cache
Aspnet Caching
Varnish Cache Plus. Random notes for wise web developers
Caching and tuning fun for high scalability @ FOSDEM 2012
High Availability Content Caching with NGINX
Supercharging Content Delivery with Varnish
awergaezrg
sergaerwga
aergserga
sakdjfhaksjfhaskjh
aksdfhaskdjfhasdjkh
askldjfhaskdfj aslkdjfhaskdfhasjk askldf ashkdf
salkdjfhdjkghdfkjh
Solving anything in VCL
Ad

Recently uploaded (20)

PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
A Presentation on Artificial Intelligence
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Zenith AI: Advanced Artificial Intelligence
PPTX
Tartificialntelligence_presentation.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Hybrid model detection and classification of lung cancer
PDF
August Patch Tuesday
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
gpt5_lecture_notes_comprehensive_20250812015547.pdf
A Presentation on Artificial Intelligence
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Zenith AI: Advanced Artificial Intelligence
Tartificialntelligence_presentation.pptx
Encapsulation_ Review paper, used for researhc scholars
Hybrid model detection and classification of lung cancer
August Patch Tuesday
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Web App vs Mobile App What Should You Build First.pdf
Encapsulation theory and applications.pdf
Enhancing emotion recognition model for a student engagement use case through...
A comparative analysis of optical character recognition models for extracting...
NewMind AI Weekly Chronicles - August'25-Week II
Accuracy of neural networks in brain wave diagnosis of schizophrenia
1 - Historical Antecedents, Social Consideration.pdf
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Approach and Philosophy of On baking technology
SOPHOS-XG Firewall Administrator PPT.pptx
MIND Revenue Release Quarter 2 2025 Press Release

Varnish qconsp 2011

  • 4. Caching em HTTP Como funciona um “Acelerador Web” (Reverse Proxy Cache) Expiração (headers Cache-Control, Age e Expires)
  • 5. Validação (headers Last-Modified, Etag, If-Modified-Since, If-None-Modified)
  • 6. Browser -> Cache -> Backend
  • 8.  
  • 9.  
  • 11.  
  • 12.  
  • 14.  
  • 15.  
  • 16.  
  • 19. Hash
  • 21. Misc: set/unset, regexp, ttl, headers de diagnóstico
  • 23. Ferramentas auxiliares: varnishlog, varnishncsa, varnishadm
  • 25. Elementos do vcl Os elementos básicos do vcl são: Backend Aqui são especificados os parâmetros de comunicação com o backend e probe (healthcheck) – semelhante à um VIP Subrotinas e módulos Subrotinas não retornam valores
  • 26. Além das rotinas pré-definidas (que determinam o fluxo do Varnish) podem ser criadas subrotinas customizadas
  • 27. Módulo pode retornar a localização geográfica de um endereço IP ou usar o varnish como um cliente HTTP e buscar cabeçalhos e corpo nos backends Acls Includes Inline C
  • 28. backend backend ig { .host = "vip.be.infra"; .probe = { .url = "/healthcheck.html"; .timeout = 34 ms; .interval = 1s; .window = 10; .threshold = 8; } } director baz round-robin { { .backend = ig; } { .backend = com; } }
  • 29. acl acl purge { "localhost"; "127.0.0.1"; "10.0.0.0"/8; } acl header { "localhost"; "200.200.100.100"; "10.0.0.0"/8; }
  • 30. Include e sub include ”/etc/varnish/functions.inc"; --- sub normalize_user_agent { if(req.http.User-Agent ~ "iPhone|Android") { set req.http.User-Agent = "mobile"; } else { remove req.http.user-agent; } }
  • 31. Varnish: Fluxo e Objetos
  • 32.  
  • 33. Hash sub vcl_hash { if (req.http.user-agent ~ "mobile") { hash_data(req.http.user-agent); } # Vital para virtualhosts hash_data(req.url); hash_data(req.http.host); return (hash); }
  • 34. Métodos HTTP if (req.request ~ "(GET|HEAD)") { return(lookup); } # Se for um POST deixa passar sem fazer cache elsif (req.request == "POST") { return(pass); } ...cont
  • 35. Métodos HTTP elsif (req.request == "PURGE") { if (!client.ip ~ purge) { error 405 "opt Cache: Purge Not allowed."; } ban_url(req.url); error 200 req.url; } else { error 403 "opt Cache: Request not allowed."; }
  • 36. Misc (call, set, regexp) call normalize_accept_encoding; --- sub normalize_accept_encoding { if (req.http.Accept-Encoding) { if (req.http.User-Agent ~ "MSIE 6") { remove req.http.Accept-Encoding; } elsif (req.http.Accept-Encoding ~ "gzip") { set req.http.Accept-Encoding = "gzip"; } elsif (req.http.Accept-Encoding ~ "deflate") { set req.http.Accept-Encoding = "deflate"; } else { remove req.http.Accept-Encoding; } } }
  • 37. Misc (ttl, beresp) # se nao for 200, 301, 302 ou 304 = ttl de 5s if (beresp.status != 200 && beresp.status != 301 && beresp.status != 302 && beresp.status != 304) { set beresp.ttl = 5s; } # ttl minimo de 60s para os objetos com retorno 200, 301, 302 e 304 else { if (beresp.ttl < 60s) { set beresp.ttl = 60s; } }
  • 38. Persistência Persistência O grace mode permite ao varnish responder lookups mesmo quando um objeto expirou seu ttl enquanto o backend não estiver up ou lento Configuração necessária Em vcl_recv: set req.grace = 3d; Em vcl_fetch: set req.grace = 3d; Importante: É necessário ter o probe na configuração de backend para que o grace funcione.
  • 40. varnishlog com suporte a filtros de registros que correspondem múltiplas expressões
  • 43. varnishncsa com suporte de log com formatos personalizados
  • 44. varnishadm # varnishadm -T localhost:6082 &quot;ban req.url ~ /index.html && req.http.host == site.com.br&quot; CLI connected to localhost:6082 # varnishadm -T localhost:6082 &quot;vcl.list&quot; CLI connected to localhost:6082 available 887 boot available 7 1312244228_site.com.br active 382 1312261977_ajuste_site.com.br
  • 45. varnishlog $ varnishlog -o -i TxURL,TxHeader 102 TxHeader c Date: Sun, 11 Sep 2011 14:44:26 GMT 102 TxHeader c Last-Modified: Mon, 07 Feb 2011 20:40:38 GMT 102 TxHeader c Cache-Control: max-age=60 102 TxHeader c Expires: Sun, 11 Sep 2011 14:44:31 GMT 102 TxHeader c Vary: Accept-Encoding 102 TxHeader c Connection: keep-alive 102 TxHeader c X-Cache: HIT $ varnishlog -i TxURL,TxHeader -I '(TxURL|Host:)' 47 TxHeader - Host: www.sitea.com.br 47 TxHeader - Host: www.siteb.com.br 47 TxHeader - Host: vhost.sitea.com.br
  • 46. varnishstat $ varnishstat 123+18:16:25 Hitrate ratio: 10 44 48 Hitrate avg: 0.9750 0.09705 0.09718 client_conn 45687252 4.27 Client connections accepted client_drop 0 0.00 Connection dropped, no sess/wrk client_req 541868273 50.69 Client requests received cache_hit 522400064 48.87 Cache hits cache_hitpass 0 0.00 Cache hits for pass cache_miss 14239594 1.33 Cache misses backend_conn 2933231 0.27 Backend conn. success backend_unhealthy 753 0.00 Backend conn. not attempted backend_busy 0 0.00 Backend conn. too many backend_fail 0 0.00 Backend conn. failures backend_reuse 12523383 1.17 Backend conn. reuses backend_toolate 2387757 0.22 Backend conn. was closed backend_recycle 14911184 1.40 Backend conn. recycles backend_unused 0 0.00 Backend conn. unused
  • 47. varnishtop $ varnishtop -i RxHeader -C -I \^User-Agent -1 1240.00 RxHeader User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.220 Safari/535.1 765.00 RxHeader User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2
  • 48. Configuração dos Headers #Apache Header unset ETag ExpiresActive On ExpiresByType text/css &quot;now plus 10 years&quot; ExpiresByType text/html &quot;now plus 60 seconds&quot; ExpiresByType image/gif &quot;now plus 10 years&quot; ExpiresByType image/png &quot;now plus 10 years&quot; ExpiresByType image/jpeg &quot;now plus 10 years&quot; ExpiresByType application/javascript &quot;now plus 10 years&quot; ExpiresByType application/x-shockwave-flash &quot;now plus 10 years&quot; Header append Cache-Control public env=static-content
  • 49. Obrigado! Dúvidas ? iG – Internet Group Flavio Torres [email_address] @flavio_torres