AlgoViz

Varnish

medium 28 min

Varnish is an HTTP cache that stands in front of your web servers and answers repeated requests from memory.

Video lesson · Chapter 1 of 5

One expensive page, two visitors

0:00 / 3:41

Varnish in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Varnish is a caching reverse proxy for HTTP. A client asks Varnish, Varnish looks in its memory, and only when nothing usable is there does it ask your web server, called the backend.

It does one job. It is not a web server and runs no business logic. What it does have is VCL, a language in which you say what may be cached, for how long, under which key, and what to do when the backend is slow or broken.

Two names are in use today. Vinyl Cache is the community project that was called Varnish Cache until version 8.0. Varnish Cache is now a distribution of Vinyl Cache made by the company Varnish Software, with TLS and extra modules built in. The ideas and the VCL on this page belong to both.

Why it exists

Building a page can take hundreds of milliseconds of application and database time. Sending a finished copy from memory takes almost none. If many people ask for the same page, building it once is enough.

Application code often cannot be changed to send perfect caching headers. A cache with its own rules in front lets you correct headers, drop cookies that do not matter, and keep a site readable while the backend is down.

Reaching for it makes sense on the server side of the network, close to the application. A CDN does the same close to the user, and the two are often used together.

A short history

  1. 2006

    First commits and version 1.0. The Norwegian newspaper Verdens Gang started and paid for the project, with Poul-Henning Kamp as main author and the company Linpro handling the rest.

  2. 2018

    Version 6.0, the branch that was supported longest. Vinyl Cache ends its support on 15 April 2027, Varnish Software on 30 April 2027.

  3. September 2025

    The project announced it would change its name, because Varnish Software holds the rights to Varnish Cache. Version 8.0.0 was the last under the old name.

  4. March 2026

    Vinyl Cache 9.0.0. The main program is now called vinyld, and the tools vinyllog, vinylstat and so on. Varnish Software continued the old name as a distribution with the old program names.

  5. September 2026

    Varnish Cache 9.1.0 and Vinyl Cache 9.1.0. Both have made 9.1 their long-term branch.

Words to know

Backend
The web server that Varnish asks when it has no usable copy.
VCL
The configuration language. Your file is translated to C, compiled and loaded without a restart.
Object
One stored response with its headers and its lifetime.
Grace
Extra time after the lifetime in which an old object may be served while a new one is fetched.
Keep
Time after grace in which the object is only used to ask the backend whether it changed.
Pass
Forward this request to the backend and store nothing.
Purge and ban
Two ways to invalidate: remove one object, or declare a rule that old objects must not match.
VMOD
A module that adds functions to VCL.

How it works

Step through the idea, or press Play.

Step 1 of 3

Receive. VCL cleans the request and decides: look up, pass or refuse

Understand it

Start here

The postcard painter

Imagine a painter at the seaside who makes picture postcards. A painting takes an hour, a print of a finished painting takes a second. When should the painter pick up the brush?

Paint once, print often
READYA lighthouse?Nothing ready: paint it

The painter is the backend, the easel is the cache, and the rule of when to paint is VCL.

The name

Varnish Cache, Vinyl Cache and Varnish Enterprise

Three things with similar names, November 2026

NameWho runs itWhat it is
Vinyl CacheA voluntary association with a governing boardThe open source project that used to be called Varnish Cache. Programs: vinyld, vinyladm, vinyllog
Varnish CacheVarnish SoftwareAn open source distribution based on Vinyl Cache. Adds TLS in the process, JSON logs and packaged modules. Programs: varnishd, varnishadm, varnishlog
Varnish EnterpriseVarnish SoftwareThe commercial product
Both open source lines use the 2-clause BSD licence. Supported now: 9.1 (long term), 9.0 and, until April 2027, 6.0.

This page shows commands with the varnish names. With Vinyl Cache, start vinyld instead of varnishd and look in /etc/vinyl-cache instead of /etc/varnish. Older books and articles say Varnish for what is now Vinyl Cache.

The idea

Where it stands in a system

A cache between the balancer and the application

Browsers reach a load balancer inside our system over HTTPS. It sends requests to one of two Varnish machines, each with its own memory. Only misses go on to two app servers, which use one database.
Hits end at Varnish. Each Varnish machine has its own cache.
  • Answer from memory

    A hit costs three system calls in Varnish Cache, by the project's own count: read, poll, write.

  • One fetch for many

    Waiting requests for the same object share one backend request, without any setting.

  • Serve old, refresh behind

    Grace hides the refresh, and a long grace hides a broken backend.

  • Rules as code

    VCL can change headers, choose backends, and decide per request.

  • Exact invalidation

    Purge one URL, ban by rule, or use tags with the xkey module.

  • Logs without files

    Every request is logged to shared memory. Tools read it when you want it.

The hit ratio decides the backend load

backend=R (1−h)10000×0.05=50010000×0.01=100\text{backend} = R\,(1-h) \qquad 10000 \times 0.05 = 500 \qquad 10000 \times 0.01 = 100
R is requests per second, h is the hit ratio. Going from 95 to 99 percent sounds small, and it cuts the backend load to a fifth. Assumed traffic: 10,000 a second.

The ideas behind this have their own pages: caching, cache lifetimes, API caching and CDN invalidation. Here we look at how the product does it.

Inside

Processes, threads and storage

Inside one machine

One Varnish machine. Clients reach worker threads, which look up objects in memory storage and write log records into shared memory. What is missing in storage is fetched from the backend outside, and varnishlog reads the log records.
A manager process compiles VCL and watches the child process, which does all the work drawn here.
  1. 1

    Manager and child

    The manager compiles VCL, starts the child, and restarts it if it stops. The cache lives in the child, so a restart of the child empties it.

  2. 2

    Worker threads

    Each active request has a thread. By default there are 2 pools of at least 100 and at most 5,000 threads: 200 ready at the start, 10,000 at most.

  3. 3

    Waiting connections

    An idle client connection gives its thread back. A slow response keeps a thread busy, so slow backends use up threads.

  4. 4

    Storage

    malloc keeps objects in memory. file maps a file on disk. Neither survives a restart.

How much memory?

500000×20 KB=10 GB500000×1 KB=0.5 GB500000 \times 20\,\text{KB} = 10\,\text{GB} \qquad 500000 \times 1\,\text{KB} = 0.5\,\text{GB}
Assumed: half a million objects of 20 KB. The first part goes into -s malloc,10g. The second is about 1 KB per object outside it. Fragmentation can make the real use of malloc two to four times larger, says the documentation, so measure and leave room.

Request

The life of one request

From request to answer

Each step is a VCL subroutine that you can extend. Backend work runs in its own thread, which makes background refresh possible.

What the built-in rules do if you write nothing

SituationBuilt-in decision
GET or HEAD without Cookie or AuthorizationLook in the cache
GET with a Cookie headerPass: risky to cache
Request with AuthorizationPass
POST, PUT, PATCH, DELETEPass
Unknown method501, since version 8.0; earlier versions opened a pipe
Response with Set-CookieNot stored
Response with Cache-Control: private, no-store or no-cacheNot stored
Response with no lifetimedefault_ttl, 2 minutes
Your code runs first, then the built-in code. If you end a subroutine with return, the built-in part is skipped.

VCL

A small configuration

vcl
vcl 4.1;import std;backend default {    .host = "10.0.0.10";    .port = "8080";    .connect_timeout = 1s;    .first_byte_timeout = 10s;    .probe = { .url = "/health"; .interval = 5s; .timeout = 1s;               .window = 5; .threshold = 3; }}acl purgers { "localhost"; "10.0.0.0"/24; }sub vcl_recv {    if (req.method == "PURGE") {        if (client.ip !~ purgers) { return (synth(405, "Not allowed")); }        return (purge);    }    # tracking parameters do not change the page    set req.url = regsuball(req.url, "([?&])utm_[a-z]+=[^&]*&?", "\1");    set req.url = regsub(req.url, "[?&]$", "");    if (req.url !~ "^/(account|cart|admin)") {        unset req.http.Cookie;    }    if (std.healthy(req.backend_hint)) {        set req.grace = 10s;    }}sub vcl_backend_response {    if (bereq.url ~ "^/static/") {        unset beresp.http.Set-Cookie;        set beresp.ttl = 1d;    }    set beresp.grace = 24h;    if (beresp.status >= 500 && bereq.is_bgfetch) {        return (abandon);      # keep the old copy    }}sub vcl_deliver {    if (obj.hits > 0) { set resp.http.X-Cache = "HIT"; }    else              { set resp.http.X-Cache = "MISS"; }}
Every subroutine falls through to the built-in code, so private pages keep their safe defaults.
Shell
varnishd -C -f /etc/varnish/default.vcl > /dev/null && echo ok   # does it compile?varnishadm vcl.load v2 /etc/varnish/default.vcl                  # loadvarnishadm vcl.use v2                                            # switch, no restartvarnishadm vcl.list                                              # the old one stays: go back with vcl.use
Changing rules keeps the cache. Restarting the program empties it.

Freshness

Lifetime, grace and keep

The life of one object

Fresh and Grace are served. Keep is only material for a conditional request.

Three clocks that add up

ClockDefaultWhat a request gets
ttl2 min (default_ttl)The object, at once
grace10 s (default_grace)The old object at once, while one fetch runs behind
keep0 s (default_keep)Waits for the backend, which may answer 304 without a body

A request that arrives in grace

Nobody waits for the slow page. Without grace, the first client would wait 400 ms and the others would queue behind it.

A popular page is refreshed once per lifetime instead of once per visitor, so even a lifetime of a few seconds helps. The herd problem itself is explained in thundering herd.

The trap

Responses that cannot be cached

Suppose /profile cannot be stored. If requests for it queued behind each other as they do for a normal miss, every user would wait for all users before. Varnish therefore stores a small marker that says this key is not cacheable. For its lifetime, 2 minutes by default (uncacheable_ttl), requests go to the backend side by side. This is hit-for-miss. If a later response is cacheable, it is stored and the marker is gone.

Keep the marker

  • Let the built-in rules mark responses
  • Use return (pass) in vcl_recv for paths you know are private
  • Check that slow requests are not waiting in a queue

Break it

  • Set beresp.ttl = 0s and return early for private pages: no marker, so requests line up
  • Remove Set-Cookie from a login response to force a hit
  • Cache a page that shows a name

Key

What makes two requests the same

The default key is the URL and the host. If the response has a Vary header, one key holds several variants, for example one per language. Each distinct value makes another copy, so clean the header first.

Header in VaryWithout cleaningWith VCL
Accept-EncodingVarnish handles gzip itselfNothing to do
Accept-LanguageHundreds of different stringsReduce to the languages you have, such as en and fr
CookieOne copy per person: uselessPut one cookie value into its own header and vary on that
User-AgentThousands of stringsReduce to mobile and desktop

Invalidation

Purge, ban, tags

MethodRemovesCostUse it for
PurgeOne URL with all its variants, at onceVery lowOne article was edited
BanEverything older that matches an expressionTested on later hits and by a background threadAll pages of one section
xkey (a VMOD)All objects that carry a tagLow; needs tags in a response headerOne product that is shown on many pages
req.hash_always_missNothing: refreshes one objectOne fetchWarming: see cache warming
Shell
# one URL (needs the PURGE rule and ACL from the VCL above)curl -s -X PURGE -H "Host: shop.example" http://10.0.0.5/products/42# a rule; obj.* lets the background ban lurker do the workvarnishadm ban 'obj.http.x-section == news'varnishadm ban.list
A ban on req.* cannot be handled by the lurker, because there is no request. Such bans pile up.

Several Varnish machines do not tell each other anything. Send the purge to each of them, or keep lifetimes short. A CDN in front has its own copies and needs its own invalidation.

Pages

Parts with different lifetimes

Edge Side Includes let one page be built from fragments. The frame may live for an hour, the price list for ten seconds, and the greeting may be passed. Varnish reads the <esi:include> tags of responses for which you set beresp.do_esi = true.

One page, three lifetimes

Only the personal part reaches the backend.

Fragments are fetched through the cache like any other request. By default a failing fragment does not stop the rest of the page. The feature esi_include_onerror makes that stricter.

Operate

Scale, TLS and what to watch

When one machine cannot hold everything

Users reach a TLS balancer that spreads requests over two small front caches. Both front caches send a URL that they miss to one of two back caches, chosen by a hash of the URL. The back caches ask the app servers.
Front caches hold the hottest objects. A hash of the URL gives every other object one home in the back layer.

Watch these

NumberMeaningAct when
cache_hit, cache_miss, s_passThe hit ratio, and what is passedIt drops after a release: look for new cookies or parameters
n_lru_nukedObjects thrown out for spaceIt grows all the time
threads, thread_queue_lenBusy threads and requests waiting for oneThe queue is not empty: the backend is slow, or limits are too low
backend_fail, backend_unhealthyFailed connections, sick backendsAny lasting rise
varnishstat shows them. varnishtop -i BereqURL shows which URLs reach the backend most.
  1. 1

    TLS

    Varnish Cache 9.0 and later can end TLS itself (-a :443,https). Vinyl Cache documents HAProxy in front, with the PROXY protocol carrying the client's address.

  2. 2

    Cold start

    After a restart the cache is empty and the backend sees all traffic. Restart one machine at a time, and protect the backend with .max_connections.

  3. 3

    Sharding

    Two machines with independent caches each fetch every object. Route by URL hash to give each object one home; see consistent hashing.

  4. 4

    Versions

    Security fixes appear a few times a year. Stay on a supported branch. 6.0 ends in April 2027.

Decide

When to choose it, and when not

Choose it when

  • Many visitors read the same pages or API responses
  • You need caching rules that headers cannot express
  • Instant and exact invalidation matters
  • Old content is better than an error
  • You want to run the cache yourself

Look elsewhere when

  • Every response is personal
  • The problem is distance to the user: use a CDN
  • You want to cache database rows or sessions: use a data cache such as Redis
  • You need a web server as well and a small cache is enough: NGINX
  • Nobody can look after VCL

Neighbours

ProductAlikeDifferentChoose it for
NGINX with proxy_cacheReverse proxy with grace-like stale serving and a lockAlso serves files and TLS; cache on disk; simpler rules; no bans in the open source versionOne program for everything
HAProxyFast HTTP proxyA balancer with a deliberately small cache; its own manual points to Varnish for moreBalancing and TLS in front of Varnish
A CDNHTTP cache with purgeNear the user, many locations, run by othersDistance, very large traffic, attack protection
MemcachedMemory cacheStores values your code asks for, not whole responsesObjects inside the application

Strengths

  • Very cheap hits
  • Coalescing and grace without extra tools
  • Rules can be changed and rolled back without a restart
  • Detailed logs on demand

Costs

  • The cache is lost on restart and not shared between machines
  • VCL mistakes can leak private pages
  • One more layer to debug
  • Two product lines with different program names

Summary

The whole topic in one minute.

Varnish keeps finished responses in memory and answers from there. A miss is fetched once, however many clients wait for it. Grace lets it serve a slightly old copy during the refresh, and keeps a site up when the backend fails.

Most of the work is raising the hit ratio safely: remove cookies that do not matter, keep private pages out, choose lifetimes, and invalidate with purges or tags when content changes. Choose the product line on purpose, Vinyl Cache or Varnish Cache, because the program names and features differ.

  • Vinyl Cache is the renamed project; Varnish Cache is now Varnish Software's distribution of it.
  • Hits from memory, one fetch per missing object, old copies during refresh.
  • Cookies and Authorization mean pass, unless your VCL knows better.
  • Life of an object is ttl plus grace plus keep: 2 minutes, 10 seconds and 0 by default.
  • Purge one, ban by rule, tag with xkey, on every machine.
  • Restart means an empty cache: load new VCL instead.

Sources