Skip to content

Instantly share code, notes, and snippets.

@rezan
Created Feb 19, 2021
Embed
What would you like to do?
Varnish VCL - cache misses get an instant 302 response and are fetched in the background
#
# Cache misses get an instant 302 response and are fetched in the background
# (Include this file in your VCL)
#
vcl 4.1;
import std;
import synthbackend;
import vha;
sub vcl_recv
{
unset req.http.miss-bgfetch;
}
sub vcl_miss
{
set req.http.miss-bgfetch = "true";
return (fetch);
}
sub vcl_backend_fetch
{
if (bereq.http.miss-bgfetch) {
set bereq.backend = synthbackend.from_string("");
return (fetch);
}
}
sub vcl_backend_response
{
if (bereq.http.miss-bgfetch) {
# Insert a stale 302 response
set beresp.status = 302;
set beresp.http.Location = bereq.url;
set beresp.http.Cache-Control = "private";
set beresp.http.Retry-After = "1";
set beresp.ttl = 0.001s;
set beresp.grace = 24h;
vha.set_insertion_time(now - 1s);
return (deliver);
}
}
sub vcl_deliver
{
if (req.http.miss-bgfetch) {
# Restart, cache hit on the 302, and trigger a bgfetch
std.rollback(req);
return (restart);
}
}
# EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment