SlideShare a Scribd company logo
NYC Varnish Cache
Introduction to Varnish Configuration Language by Pax Dickinson

8/14/2012
Our Sponsors

✤   Business Insider
    http://businessinsider.com

✤   Varnish Software
    http://varnish-software.com

✤   Our host, BuzzFeed
    http://buzzfeed.com
Varnish Resources

✤   Varnish Cache Website
    http://www.varnish-cache.org/

✤   The Varnish Book
    https://www.varnish-software.com/static/book/
    Designed as a classroom-led official training manual. It’s written like
    a schoolbook, but it’s good and up-to-date in a way that a lot of
    Varnish documentation out there isn’t.
Introduction to
Varnish Configuration Language
Where We Left Off

✤   At the last meetup I introduced Varnish, explained its architecture
    and how to install it and monitor it successfully.

✤   Tonight we’ll dive into Varnish Configuration Language and discuss
    how VCL defines Varnish’s policy for handling HTTP requests.

✤   I’ll be discussing Varnish 3.0 specific syntax, anyone using 2.1.5 or
    earlier should be aware that VCL has changed syntax somewhat
    between v2 and v3.
How Does Varnish Work?
Hits & Misses, Passes & Pipes

✤   A hit happens when a request comes in and the hash matches a
    response in the cache. The response is sent to the client and the
    backend never knows about it.

✤   A miss happens when a request is not present in the cache or is
    present but expired or banned. The request is sent to the backend and
    its response is saved in the cache.

✤   A pass happens when varnish is configured to bypass certain
    requests. They are never cached and don’t figure in hit rates.

✤   A pipe grants a direct passthrough to the backend. Used for media
    streams.
What Is VCL?

✤   A domain-specific language
    used to define the way Varnish
    handles & caches HTTP requests

✤   Has if statements & regexes
    but no user functions or loops

✤   C-like syntax

✤   Compiled to C by the server
    and linked dynamically
The VCL Engine

✤   VCL defines how each HTTP request is processed. Each request is
    processed independently.

✤   Varnish parses and verifies requests but all policy decisions about
    how requests are cached and routed depends on VCL code.

✤   Each predefined VCL function handles a particular phase of the
    request lifecycle, and ends with a return() statement that forwards the
    workflow to the next phase.
Built-In Functions & Keywords

✤   VCL includes some built-in functions to be used during request
    processing.

✤   regsub() and regsuball() allow a user to modify headers based on regex
    matching. There are some simpler methods using VMODs but it’s
    good to be comfortable writing complex regexes when implementing
    complicated logic in VCL.

✤   The set keyword is used to set headers on a request or response, and
    the remove or unset keywords can remove them. Setting headers is the
    only way to pass information between VCL subroutines.

✤   The ban() function allows you to remove entries from the cache.
Writing VCL

✤   Each VCL function has a default that will always run unless you
    override it. The default is appended to the end of any VCL function
    you include.

✤   If you include the same VCL function twice they’re appended in the
    order read.

✤   It’s possible to include other files using the
    include statement. Statements can be defined
    as subroutines for convenience and
    readability and executed later with the
    call statement.
Return Values in VCL

✤   Every VCL function has a set of possible return values that determine
    a request’s handling. error and restart are available in most functions.

✤   return(error) passes control to vcl_error().

✤   return(restart) increments the restart counter and begins again at
    vcl_recv().

✤   The default VCL code will run for a function if the user code does not
    return().
Data Objects in VCL

✤   VCL exposes global objects representing HTTP requests or responses
    that can be read and modified. Different objects are available in
    different VCL functions, e.g. beresp cannot be modified in vcl_recv
    because we don’t have a backend response yet.

✤   The five main objects are the request object (req), response object
    (resp), the backend request and response objects (bereq and beresp), and
    the cache object (obj).

✤   client and server are read-only objects that expose data about the client
    and the varnish server itself respectively.
Defining Backends & Probes

✤   Varnish forwards uncached
    requests to defined backends

✤   Probes ensure a backend is healthy

✤   To be considered healthy, backend
    must pass threshold probes out of
    the last window attempts.
Directors

            ✤   Directors are collections of
                backends

            ✤   They define which backends are
                chosen for a request

            ✤   Director types include random,
                client, hash, round-robin, DNS,
                and fallback.
Access Control Lists
 ✤   ACLs consist of lists of IP addresses

 ✤   ACLs can be matched against in VCL code to restrict access
Receiving Requests with vcl_recv

✤   vcl_recv happens to every request.

✤   Use it to check and add headers, perform bans and redirects,
    forward to proxies, and manage cookies.

✤   The req object is available
    here.

✤   Possible return values are
    pass, lookup, pipe, and error.
Default vcl_recv

✤   The vcl_recv default is important
    to understand in order to get
    good cache hit ratios.

✤   It won’t cache in the presence of
    cookies or authorization headers.

✤   You’ll generally need to use your
    own vcl_recv to strip cookies you
    don’t care about to have any
    caching at all.
Proper Passing via vcl_pass
✤   vcl_pass happens when a request is passed in vcl_recv, vcl_hit, or
    vcl_miss.

✤   A return(pass) in vcl_pass sends control to vcl_fetch.

✤   The default content is to simply return(pass).

✤   The req and the bereq objects are available.

✤   Possible return values are pass, restart, and error.
Heavenly Hashes with vcl_hash

✤   vcl_hash happens to any request calling return(lookup) in vcl_recv.

✤   Use it to add values to the hash. Any aspects of the request that
    affect the returned content should be
    included in the hash by calling hash_data().

✤   The req object is available.

✤   The only possible return value is hash.
Default vcl_hash

✤   The vcl_hash default includes the
    URL and the host or IP address.

✤   Anything that changes the HTML
    returned from the backend needs
    to be hashed on. Device types,
    login cookies, referers; depending
    on your application.

✤   It’s a good idea to strip any utm_source or other tracking query string
    elements to prevent unnecessarily fragmenting your cache.
Handling Hits in vcl_hit
✤   vcl_hit is executed when a hashed request is found in the cache.

✤   A return(pass) in vcl_hit sends control to
    vcl_pass.

✤   The default content is to simply
    return(deliver), which sends control to
    vcl_deliver().

✤   req and obj are exposed to vcl_hit.

✤   Possible return values are deliver, pass,
    restart, and error.
Manipulating Misses with vcl_miss
✤   vcl_miss is executed when a hashed request is not found in the
    cache.

✤   A return(pass) in vcl_miss sends control
    to vcl_pass.

✤   The default content is return(fetch),
    which sends control to vcl_fetch().

✤   req and bereq are exposed to vcl_miss.

✤   Possible return values are fetch, pass,
    restart, and error.
Fantastic Fetching in vcl_fetch
✤   vcl_fetch is executed after a backend request is made but before that
    response is stored in the cache. It happens either after vcl_miss
    returns fetch or vcl_pass returns pass.

✤   The req, bereq, and beresp objects
    are accessible in vcl_fetch.

✤   Possible return values are
    deliver, hit_for_pass, restart,
    and error.
Default vcl_fetch

✤   The vcl_fetch defaults to deliver unless the backend has set a cookie or
    a Vary header or the TTL is 0.

✤   hit_for_pass is a special condition that stores an object in the cache but
    sets a flag marking it as content that should be fetched fresh from the
    backend for as long as the flag exists.
Dynamic Delivery in vcl_deliver
✤   vcl_deliver is executed when varnish returns content to the client.

✤   The resp object is accessible,
    none of the other request or
    response objects are in scope.

✤   The default is to return(deliver).

✤   Possible return values are
    deliver, restart, and error.
Expectorate Errors using vcl_error
✤   vcl_error is executed when any VCL function returns error.

✤   The default uses the synthetic
    keyword to deliver a Guru
    Meditation error to the client.

✤   Possible return values are
    deliver and restart.
Other VCL functions
✤   vcl_pipe is executed when vcl_recv returns pipe. It’s used for
    streaming media and tells varnish to pipe that client directly to the
    backend for the duration of the HTTP connection. If you use this,
    you should explicitly close the connection from the backend when
    done piping with a Connection: close header.

✤   vcl_init and vcl_fini are functions that get called upon the loading
    and unloading of a VCL script, respectively. They’re used for
    initializing and cleaning up VMODs during startup and shutdown.
Using VMODs

✤   VMODs are varnish modules. They’re initialized with the import
    keyword and they export functions into VCL.

✤   vmod_std is packaged with
    Varnish and provides small
    useful functions.

✤   Other Varnish modules are available including geoIP lookups, Redis
    and Memcache clients, and custom VMODs can be written in C for
    use with Varnish.
Banning Basics

✤   You can use the built-in VCL ban() function to perform bans of cached
    content.

✤   Calling the ban() function adds your expression to the ban list, which
    is checked after a cache object is found. If the object matches a ban on
    the ban list, its considered a miss rather than a hit.

✤   ban(“req.url ==” + req.url); would ban any content from a URL
    matching req.url. Bans can be set to match on any request header, not
    just URL.
Active Banning

✤   It’s possible to write VCL that can accept ban requests from your
    backends. By doing this, it allows a backend to actively ban changed
    content from the varnish cache, ensuring clients get the most up to
    date version of the content.

✤   This example bans based on
    the URL, but it could have
    a more complex rule that
    matches a header set by the
    backend.
VCL Takeaways

✤   The Varnish website contains a lot of great examples of handy tricks
    you can use in your own VCL code, but it’s important to understand
    what you’re doing before you implement them.

✤   Know your HTTP protocol. Varnish is tightly tied to HTTP so it’s very
    helpful to understand the HTTP protocol and its intricacies, especially
    how basic HTTP caching headers are interpreted by browsers and
    other clients.

✤   Keep it simple at first, and iterate improvements. It’s tempting to
    write a huge VCL policy that has all the bells and whistles but a
    complex VCL can be difficult to debug. Start small and add
    complexity as you go.
A Closing Testimonial From Jay-Z

✤   “If you’re having scaling problems,
    I feel bad for you son...
    Clients sent 99 requests
    but my backend got one.”




                                          Photo by flickr user matthew_harrison
Til Next Time...

✤   Come back next month (date TBD) for another exciting adventure
    with Varnish...

                Advanced VCL Tricks
Sources & Links

✤   Detailed VCL flowchart
    https://www.varnish-cache.org/trac/wiki/VCLExampleDefault

✤   VMOD Library
    https://www.varnish-cache.org/vmods

✤   Upgrading from Varnish 2.1 to Varnish 3.0
    https://www.varnish-cache.org/docs/3.0/installation/upgrade.html

More Related Content

What's hot

Advanced cache invalidation
Advanced cache invalidationAdvanced cache invalidation
Advanced cache invalidation
Per Buer
 
HTTP caching with Varnish
HTTP caching with VarnishHTTP caching with Varnish
HTTP caching with Varnish
David de Boer
 
EWD 3 Training Course Part 34: QEWD Resilient Mode
EWD 3 Training Course Part 34: QEWD Resilient ModeEWD 3 Training Course Part 34: QEWD Resilient Mode
EWD 3 Training Course Part 34: QEWD Resilient Mode
Rob Tweed
 
Memcached Study
Memcached StudyMemcached Study
Memcached Study
nam kwangjin
 
Nginx - Tips and Tricks.
Nginx - Tips and Tricks.Nginx - Tips and Tricks.
Nginx - Tips and Tricks.Harish S
 
Next Generation DevOps in Drupal: DrupalCamp London 2014
Next Generation DevOps in Drupal: DrupalCamp London 2014Next Generation DevOps in Drupal: DrupalCamp London 2014
Next Generation DevOps in Drupal: DrupalCamp London 2014
Barney Hanlon
 
Streaming millions of Contact Center interactions in (near) real-time with Pu...
Streaming millions of Contact Center interactions in (near) real-time with Pu...Streaming millions of Contact Center interactions in (near) real-time with Pu...
Streaming millions of Contact Center interactions in (near) real-time with Pu...
Frank Kelly
 
ProxySQL for MySQL
ProxySQL for MySQLProxySQL for MySQL
ProxySQL for MySQL
Mydbops
 
Proxysql ha plam_2016_2_keynote
Proxysql ha plam_2016_2_keynoteProxysql ha plam_2016_2_keynote
Proxysql ha plam_2016_2_keynote
Marco Tusa
 
ProxySQL Tutorial - PLAM 2016
ProxySQL Tutorial - PLAM 2016ProxySQL Tutorial - PLAM 2016
ProxySQL Tutorial - PLAM 2016Derek Downey
 
Proxysql sharding
Proxysql shardingProxysql sharding
Proxysql sharding
Marco Tusa
 
Varnish Configuration Step by Step
Varnish Configuration Step by StepVarnish Configuration Step by Step
Varnish Configuration Step by Step
Kim Stefan Lindholm
 
Where is my cache architectural patterns for caching microservices by example
Where is my cache architectural patterns for caching microservices by exampleWhere is my cache architectural patterns for caching microservices by example
Where is my cache architectural patterns for caching microservices by example
Rafał Leszko
 
Introduction to .Net Driver
Introduction to .Net DriverIntroduction to .Net Driver
Introduction to .Net Driver
DataStax Academy
 
Cassandra as Memcache
Cassandra as MemcacheCassandra as Memcache
Cassandra as Memcache
Edward Capriolo
 
Extending functionality in nginx, with modules!
Extending functionality in nginx, with modules!Extending functionality in nginx, with modules!
Extending functionality in nginx, with modules!
Trygve Vea
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDB
Mydbops
 
Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...
Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...
Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...
Severalnines
 

What's hot (20)

Advanced cache invalidation
Advanced cache invalidationAdvanced cache invalidation
Advanced cache invalidation
 
HTTP caching with Varnish
HTTP caching with VarnishHTTP caching with Varnish
HTTP caching with Varnish
 
EWD 3 Training Course Part 34: QEWD Resilient Mode
EWD 3 Training Course Part 34: QEWD Resilient ModeEWD 3 Training Course Part 34: QEWD Resilient Mode
EWD 3 Training Course Part 34: QEWD Resilient Mode
 
Memcached Study
Memcached StudyMemcached Study
Memcached Study
 
Nginx - Tips and Tricks.
Nginx - Tips and Tricks.Nginx - Tips and Tricks.
Nginx - Tips and Tricks.
 
Next Generation DevOps in Drupal: DrupalCamp London 2014
Next Generation DevOps in Drupal: DrupalCamp London 2014Next Generation DevOps in Drupal: DrupalCamp London 2014
Next Generation DevOps in Drupal: DrupalCamp London 2014
 
Streaming millions of Contact Center interactions in (near) real-time with Pu...
Streaming millions of Contact Center interactions in (near) real-time with Pu...Streaming millions of Contact Center interactions in (near) real-time with Pu...
Streaming millions of Contact Center interactions in (near) real-time with Pu...
 
ProxySQL for MySQL
ProxySQL for MySQLProxySQL for MySQL
ProxySQL for MySQL
 
Proxysql ha plam_2016_2_keynote
Proxysql ha plam_2016_2_keynoteProxysql ha plam_2016_2_keynote
Proxysql ha plam_2016_2_keynote
 
ProxySQL Tutorial - PLAM 2016
ProxySQL Tutorial - PLAM 2016ProxySQL Tutorial - PLAM 2016
ProxySQL Tutorial - PLAM 2016
 
Proxysql sharding
Proxysql shardingProxysql sharding
Proxysql sharding
 
Varnish Configuration Step by Step
Varnish Configuration Step by StepVarnish Configuration Step by Step
Varnish Configuration Step by Step
 
Where is my cache architectural patterns for caching microservices by example
Where is my cache architectural patterns for caching microservices by exampleWhere is my cache architectural patterns for caching microservices by example
Where is my cache architectural patterns for caching microservices by example
 
Introduction to .Net Driver
Introduction to .Net DriverIntroduction to .Net Driver
Introduction to .Net Driver
 
Cassandra as Memcache
Cassandra as MemcacheCassandra as Memcache
Cassandra as Memcache
 
Extending functionality in nginx, with modules!
Extending functionality in nginx, with modules!Extending functionality in nginx, with modules!
Extending functionality in nginx, with modules!
 
Varnish –Http Accelerator
Varnish –Http AcceleratorVarnish –Http Accelerator
Varnish –Http Accelerator
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDB
 
Tomcatx performance-tuning
Tomcatx performance-tuningTomcatx performance-tuning
Tomcatx performance-tuning
 
Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...
Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...
Webinar slides: MySQL & MariaDB load balancing with ProxySQL & ClusterControl...
 

Similar to Introduction to Varnish VCL

Varnish Cache
Varnish CacheVarnish Cache
Varnish Cache
Mahbub E Elahi (Ron)
 
Varnish Cache Plus. Random notes for wise web developers
Varnish Cache Plus. Random notes for wise web developersVarnish Cache Plus. Random notes for wise web developers
Varnish Cache Plus. Random notes for wise web developers
Carlos Abalde
 
Varnish e caching di applicazioni Rails
Varnish e caching di applicazioni RailsVarnish e caching di applicazioni Rails
Varnish e caching di applicazioni Rails
Antonio Carpentieri
 
07 - Extending VQL and API in Velociraptor.pptx
07 - Extending VQL and API in Velociraptor.pptx07 - Extending VQL and API in Velociraptor.pptx
07 - Extending VQL and API in Velociraptor.pptx
matthewcybercentaurs
 
In-depth caching in Varnish - GOG Varnish Meetup, march 2019
In-depth caching in Varnish - GOG Varnish Meetup, march 2019In-depth caching in Varnish - GOG Varnish Meetup, march 2019
In-depth caching in Varnish - GOG Varnish Meetup, march 2019
GOG.com dev team
 
9th docker meetup 2016.07.13
9th docker meetup 2016.07.139th docker meetup 2016.07.13
9th docker meetup 2016.07.13
Amrita Prasad
 
Ecom 1
Ecom 1Ecom 1
Making Symofny shine with Varnish - SymfonyCon Madrid 2014
Making Symofny shine with Varnish - SymfonyCon Madrid 2014Making Symofny shine with Varnish - SymfonyCon Madrid 2014
Making Symofny shine with Varnish - SymfonyCon Madrid 2014
Barel Barelon
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
karthiksmart21
 
Supercharging Content Delivery with Varnish
Supercharging Content Delivery with VarnishSupercharging Content Delivery with Varnish
Supercharging Content Delivery with Varnish
Samantha Quiñones
 
Accelerate your web app with a layer of Varnish
Accelerate your web app with a layer of VarnishAccelerate your web app with a layer of Varnish
Accelerate your web app with a layer of Varnish
Jeremy Cook
 
Coldbox developer training – session 5
Coldbox developer training – session 5Coldbox developer training – session 5
Coldbox developer training – session 5Billie Berzinskas
 
Distributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and ScalaDistributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and Scala
Max Alexejev
 
Play Framework
Play FrameworkPlay Framework
Play Framework
Harinath Krishnamoorthy
 
cache concepts and varnish-cache
cache concepts and varnish-cachecache concepts and varnish-cache
cache concepts and varnish-cache
Marc Cortinas Val
 
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
sindhu991994
 
Web services Hand_Out
Web services Hand_OutWeb services Hand_Out
Web services Hand_Out
Kumar Gupta
 
Android MvRx Framework 介紹
Android MvRx Framework 介紹Android MvRx Framework 介紹
Android MvRx Framework 介紹
Kros Huang
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
Tanmoy Barman
 
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Gal Marder
 

Similar to Introduction to Varnish VCL (20)

Varnish Cache
Varnish CacheVarnish Cache
Varnish Cache
 
Varnish Cache Plus. Random notes for wise web developers
Varnish Cache Plus. Random notes for wise web developersVarnish Cache Plus. Random notes for wise web developers
Varnish Cache Plus. Random notes for wise web developers
 
Varnish e caching di applicazioni Rails
Varnish e caching di applicazioni RailsVarnish e caching di applicazioni Rails
Varnish e caching di applicazioni Rails
 
07 - Extending VQL and API in Velociraptor.pptx
07 - Extending VQL and API in Velociraptor.pptx07 - Extending VQL and API in Velociraptor.pptx
07 - Extending VQL and API in Velociraptor.pptx
 
In-depth caching in Varnish - GOG Varnish Meetup, march 2019
In-depth caching in Varnish - GOG Varnish Meetup, march 2019In-depth caching in Varnish - GOG Varnish Meetup, march 2019
In-depth caching in Varnish - GOG Varnish Meetup, march 2019
 
9th docker meetup 2016.07.13
9th docker meetup 2016.07.139th docker meetup 2016.07.13
9th docker meetup 2016.07.13
 
Ecom 1
Ecom 1Ecom 1
Ecom 1
 
Making Symofny shine with Varnish - SymfonyCon Madrid 2014
Making Symofny shine with Varnish - SymfonyCon Madrid 2014Making Symofny shine with Varnish - SymfonyCon Madrid 2014
Making Symofny shine with Varnish - SymfonyCon Madrid 2014
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
Supercharging Content Delivery with Varnish
Supercharging Content Delivery with VarnishSupercharging Content Delivery with Varnish
Supercharging Content Delivery with Varnish
 
Accelerate your web app with a layer of Varnish
Accelerate your web app with a layer of VarnishAccelerate your web app with a layer of Varnish
Accelerate your web app with a layer of Varnish
 
Coldbox developer training – session 5
Coldbox developer training – session 5Coldbox developer training – session 5
Coldbox developer training – session 5
 
Distributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and ScalaDistributed & Highly Available server applications in Java and Scala
Distributed & Highly Available server applications in Java and Scala
 
Play Framework
Play FrameworkPlay Framework
Play Framework
 
cache concepts and varnish-cache
cache concepts and varnish-cachecache concepts and varnish-cache
cache concepts and varnish-cache
 
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
 
Web services Hand_Out
Web services Hand_OutWeb services Hand_Out
Web services Hand_Out
 
Android MvRx Framework 介紹
Android MvRx Framework 介紹Android MvRx Framework 介紹
Android MvRx Framework 介紹
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
Implementing Micro Services Tasks (service discovery, load balancing etc.) - ...
 

Recently uploaded

Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 

Recently uploaded (20)

Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 

Introduction to Varnish VCL

  • 1. NYC Varnish Cache Introduction to Varnish Configuration Language by Pax Dickinson 8/14/2012
  • 2. Our Sponsors ✤ Business Insider http://businessinsider.com ✤ Varnish Software http://varnish-software.com ✤ Our host, BuzzFeed http://buzzfeed.com
  • 3. Varnish Resources ✤ Varnish Cache Website http://www.varnish-cache.org/ ✤ The Varnish Book https://www.varnish-software.com/static/book/ Designed as a classroom-led official training manual. It’s written like a schoolbook, but it’s good and up-to-date in a way that a lot of Varnish documentation out there isn’t.
  • 5. Where We Left Off ✤ At the last meetup I introduced Varnish, explained its architecture and how to install it and monitor it successfully. ✤ Tonight we’ll dive into Varnish Configuration Language and discuss how VCL defines Varnish’s policy for handling HTTP requests. ✤ I’ll be discussing Varnish 3.0 specific syntax, anyone using 2.1.5 or earlier should be aware that VCL has changed syntax somewhat between v2 and v3.
  • 7. Hits & Misses, Passes & Pipes ✤ A hit happens when a request comes in and the hash matches a response in the cache. The response is sent to the client and the backend never knows about it. ✤ A miss happens when a request is not present in the cache or is present but expired or banned. The request is sent to the backend and its response is saved in the cache. ✤ A pass happens when varnish is configured to bypass certain requests. They are never cached and don’t figure in hit rates. ✤ A pipe grants a direct passthrough to the backend. Used for media streams.
  • 8. What Is VCL? ✤ A domain-specific language used to define the way Varnish handles & caches HTTP requests ✤ Has if statements & regexes but no user functions or loops ✤ C-like syntax ✤ Compiled to C by the server and linked dynamically
  • 9. The VCL Engine ✤ VCL defines how each HTTP request is processed. Each request is processed independently. ✤ Varnish parses and verifies requests but all policy decisions about how requests are cached and routed depends on VCL code. ✤ Each predefined VCL function handles a particular phase of the request lifecycle, and ends with a return() statement that forwards the workflow to the next phase.
  • 10. Built-In Functions & Keywords ✤ VCL includes some built-in functions to be used during request processing. ✤ regsub() and regsuball() allow a user to modify headers based on regex matching. There are some simpler methods using VMODs but it’s good to be comfortable writing complex regexes when implementing complicated logic in VCL. ✤ The set keyword is used to set headers on a request or response, and the remove or unset keywords can remove them. Setting headers is the only way to pass information between VCL subroutines. ✤ The ban() function allows you to remove entries from the cache.
  • 11. Writing VCL ✤ Each VCL function has a default that will always run unless you override it. The default is appended to the end of any VCL function you include. ✤ If you include the same VCL function twice they’re appended in the order read. ✤ It’s possible to include other files using the include statement. Statements can be defined as subroutines for convenience and readability and executed later with the call statement.
  • 12. Return Values in VCL ✤ Every VCL function has a set of possible return values that determine a request’s handling. error and restart are available in most functions. ✤ return(error) passes control to vcl_error(). ✤ return(restart) increments the restart counter and begins again at vcl_recv(). ✤ The default VCL code will run for a function if the user code does not return().
  • 13.
  • 14. Data Objects in VCL ✤ VCL exposes global objects representing HTTP requests or responses that can be read and modified. Different objects are available in different VCL functions, e.g. beresp cannot be modified in vcl_recv because we don’t have a backend response yet. ✤ The five main objects are the request object (req), response object (resp), the backend request and response objects (bereq and beresp), and the cache object (obj). ✤ client and server are read-only objects that expose data about the client and the varnish server itself respectively.
  • 15. Defining Backends & Probes ✤ Varnish forwards uncached requests to defined backends ✤ Probes ensure a backend is healthy ✤ To be considered healthy, backend must pass threshold probes out of the last window attempts.
  • 16. Directors ✤ Directors are collections of backends ✤ They define which backends are chosen for a request ✤ Director types include random, client, hash, round-robin, DNS, and fallback.
  • 17. Access Control Lists ✤ ACLs consist of lists of IP addresses ✤ ACLs can be matched against in VCL code to restrict access
  • 18. Receiving Requests with vcl_recv ✤ vcl_recv happens to every request. ✤ Use it to check and add headers, perform bans and redirects, forward to proxies, and manage cookies. ✤ The req object is available here. ✤ Possible return values are pass, lookup, pipe, and error.
  • 19. Default vcl_recv ✤ The vcl_recv default is important to understand in order to get good cache hit ratios. ✤ It won’t cache in the presence of cookies or authorization headers. ✤ You’ll generally need to use your own vcl_recv to strip cookies you don’t care about to have any caching at all.
  • 20. Proper Passing via vcl_pass ✤ vcl_pass happens when a request is passed in vcl_recv, vcl_hit, or vcl_miss. ✤ A return(pass) in vcl_pass sends control to vcl_fetch. ✤ The default content is to simply return(pass). ✤ The req and the bereq objects are available. ✤ Possible return values are pass, restart, and error.
  • 21. Heavenly Hashes with vcl_hash ✤ vcl_hash happens to any request calling return(lookup) in vcl_recv. ✤ Use it to add values to the hash. Any aspects of the request that affect the returned content should be included in the hash by calling hash_data(). ✤ The req object is available. ✤ The only possible return value is hash.
  • 22. Default vcl_hash ✤ The vcl_hash default includes the URL and the host or IP address. ✤ Anything that changes the HTML returned from the backend needs to be hashed on. Device types, login cookies, referers; depending on your application. ✤ It’s a good idea to strip any utm_source or other tracking query string elements to prevent unnecessarily fragmenting your cache.
  • 23. Handling Hits in vcl_hit ✤ vcl_hit is executed when a hashed request is found in the cache. ✤ A return(pass) in vcl_hit sends control to vcl_pass. ✤ The default content is to simply return(deliver), which sends control to vcl_deliver(). ✤ req and obj are exposed to vcl_hit. ✤ Possible return values are deliver, pass, restart, and error.
  • 24. Manipulating Misses with vcl_miss ✤ vcl_miss is executed when a hashed request is not found in the cache. ✤ A return(pass) in vcl_miss sends control to vcl_pass. ✤ The default content is return(fetch), which sends control to vcl_fetch(). ✤ req and bereq are exposed to vcl_miss. ✤ Possible return values are fetch, pass, restart, and error.
  • 25. Fantastic Fetching in vcl_fetch ✤ vcl_fetch is executed after a backend request is made but before that response is stored in the cache. It happens either after vcl_miss returns fetch or vcl_pass returns pass. ✤ The req, bereq, and beresp objects are accessible in vcl_fetch. ✤ Possible return values are deliver, hit_for_pass, restart, and error.
  • 26. Default vcl_fetch ✤ The vcl_fetch defaults to deliver unless the backend has set a cookie or a Vary header or the TTL is 0. ✤ hit_for_pass is a special condition that stores an object in the cache but sets a flag marking it as content that should be fetched fresh from the backend for as long as the flag exists.
  • 27. Dynamic Delivery in vcl_deliver ✤ vcl_deliver is executed when varnish returns content to the client. ✤ The resp object is accessible, none of the other request or response objects are in scope. ✤ The default is to return(deliver). ✤ Possible return values are deliver, restart, and error.
  • 28. Expectorate Errors using vcl_error ✤ vcl_error is executed when any VCL function returns error. ✤ The default uses the synthetic keyword to deliver a Guru Meditation error to the client. ✤ Possible return values are deliver and restart.
  • 29. Other VCL functions ✤ vcl_pipe is executed when vcl_recv returns pipe. It’s used for streaming media and tells varnish to pipe that client directly to the backend for the duration of the HTTP connection. If you use this, you should explicitly close the connection from the backend when done piping with a Connection: close header. ✤ vcl_init and vcl_fini are functions that get called upon the loading and unloading of a VCL script, respectively. They’re used for initializing and cleaning up VMODs during startup and shutdown.
  • 30. Using VMODs ✤ VMODs are varnish modules. They’re initialized with the import keyword and they export functions into VCL. ✤ vmod_std is packaged with Varnish and provides small useful functions. ✤ Other Varnish modules are available including geoIP lookups, Redis and Memcache clients, and custom VMODs can be written in C for use with Varnish.
  • 31. Banning Basics ✤ You can use the built-in VCL ban() function to perform bans of cached content. ✤ Calling the ban() function adds your expression to the ban list, which is checked after a cache object is found. If the object matches a ban on the ban list, its considered a miss rather than a hit. ✤ ban(“req.url ==” + req.url); would ban any content from a URL matching req.url. Bans can be set to match on any request header, not just URL.
  • 32. Active Banning ✤ It’s possible to write VCL that can accept ban requests from your backends. By doing this, it allows a backend to actively ban changed content from the varnish cache, ensuring clients get the most up to date version of the content. ✤ This example bans based on the URL, but it could have a more complex rule that matches a header set by the backend.
  • 33. VCL Takeaways ✤ The Varnish website contains a lot of great examples of handy tricks you can use in your own VCL code, but it’s important to understand what you’re doing before you implement them. ✤ Know your HTTP protocol. Varnish is tightly tied to HTTP so it’s very helpful to understand the HTTP protocol and its intricacies, especially how basic HTTP caching headers are interpreted by browsers and other clients. ✤ Keep it simple at first, and iterate improvements. It’s tempting to write a huge VCL policy that has all the bells and whistles but a complex VCL can be difficult to debug. Start small and add complexity as you go.
  • 34. A Closing Testimonial From Jay-Z ✤ “If you’re having scaling problems, I feel bad for you son... Clients sent 99 requests but my backend got one.” Photo by flickr user matthew_harrison
  • 35. Til Next Time... ✤ Come back next month (date TBD) for another exciting adventure with Varnish... Advanced VCL Tricks
  • 36. Sources & Links ✤ Detailed VCL flowchart https://www.varnish-cache.org/trac/wiki/VCLExampleDefault ✤ VMOD Library https://www.varnish-cache.org/vmods ✤ Upgrading from Varnish 2.1 to Varnish 3.0 https://www.varnish-cache.org/docs/3.0/installation/upgrade.html

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n