Created
February 19, 2021 14:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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