Skip to content

Instantly share code, notes, and snippets.

@rezan
Created February 19, 2021 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rezan/790298ab86c47dcd3df41e272e9e377d to your computer and use it in GitHub Desktop.
Save rezan/790298ab86c47dcd3df41e272e9e377d to your computer and use it in GitHub Desktop.
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