Varnish
medium 28 minVarnish is an HTTP cache that stands in front of your web servers and answers repeated requests from memory.
See it run
One request, many at once, an old copy, a private page, and taking content back.
Operations
Miss, then hit
The same public page is asked for twice.
Step 1 of 5
Receive
A GET without cookie or Authorization. The rules say: look it up.
Step 1: Receive
def handle(req): if decide(req) == "pass": return fetch(req) obj = cache.lookup(req.url, req.host) if obj: return obj resp = fetch(req) if cacheable(resp): cache.store(resp) return resp- Backend work
- 1 fetch
- Where state lives
- One object
Look at the X-Cache header of your own pages.
In the real world
The same varnish doing real jobs. Pick one and step through it.
24 hours of grace, capped at 10 seconds while the probe is healthy.
Step 1 of 4
Healthy
Old copies are served for at most 10 seconds.
Step 1: Healthy
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Forcing a hit on private pages
criticalRemoving Set-Cookie from a personal response stores it for everyone.
Wrongsub vcl_backend_response { unset beresp.http.Set-Cookie; set beresp.ttl = 10m;}Rightsub vcl_backend_response { if (bereq.url ~ "^/static/") { unset beresp.http.Set-Cookie; }}Purge open to everyone
criticalAnyone can empty the cache and push the full traffic to the backend.
Wrongif (req.method == "PURGE") { return (purge); }Rightif (req.method == "PURGE") { if (client.ip !~ purgers) { return (synth(405)); } return (purge);}No storage limit
majormalloc without a size may grow until the machine runs out of memory.
Wrongvarnishd -a :80 -f d.vcl -s mallocRightvarnishd -a :80 -f d.vcl -s malloc,10gSkipping the built-in code
majorAn early return skips the rules for cookies and Authorization.
Wrongsub vcl_recv { return (hash); }Rightsub vcl_recv { if (req.url ~ "^/static/") { unset req.http.Cookie; }}Restarting for new rules
minorThe cache is empty afterwards.
Wrongsystemctl restart varnishRightvarnishadm vcl.load v2 /etc/varnish/default.vclvarnishadm vcl.use v2
Interview tips
How to explain it
- Finished responses in memory.
- One fetch for many waiting clients.
- Old copy now, new copy behind.
Raise the hit ratio
- Remove cookies that do not matter.
- Remove tracking parameters.
- Clean headers named in Vary.
Reach for it when
- Many people read the same page.
- Pages are slow to build.
- Reading must survive failures.
Before production
- Two machines, a size limit, an ACL.
- Compile and test VCL.
- Alarm on hit ratio and queue.