Come ho risolto un alto tasso di miss su Varnish e sconfitto gli scraper a costo zero
14 agosto 2025

Come ho risolto un alto tasso di miss su Varnish e sconfitto gli scraper a costo zero
Problemi con un alto tasso di cache miss su Varnish? Ecco come ho risolto questo classico problema su un backend Drupal sotto attacco da scraper aggressivi—senza spendere nulla e senza bloccare i bot legittimi come Googlebot o Bingbot.
La Strategia: 4 Passi Mirati
1. Categorizzazione URL in VCL
Categorizza le URL per applicare regole mirate:
sub vcl_recv {
if (req.url ~ "^/$") {
set req.http.X-Page-Type = "HOME";
} elsif (req.url ~ "^/category" || req.url ~ "^/search") {
set req.http.X-Page-Type = "LISTING";
} elsif (req.url ~ "^/article") {
set req.http.X-Page-Type = "ARTICLE";
} elsif (req.url ~ "\\.(css|js|png|jpg|gif|svg)$") {
set req.http.X-Page-Type = "STATIC_FILES";
}
# ... resto della logica
}
2. Lista VIP: Whitelist dei Buoni Bot
Crea una ACL in Varnish per i bot consentiti. Automatizza l’aggiornamento con uno script Bash e cron.
Script Bash: update-bot-acl.sh
#!/bin/bash
set -e
ACL_FILE="/etc/varnish/botallowed.acl"
TMP_FILE="/tmp/botallowed.acl.new"
# Scarica gli IP di Googlebot e Bingbot
curl -s https://developers.google.com/search/apis/ipranges/googlebot.json | jq -r '.prefixes[].ipv4Prefix' > /tmp/googlebot_ips.txt
curl -s https://www.bing.com/toolbox/bingbot.json | jq -r '.prefixes[].ipv4Prefix' > /tmp/bingbot_ips.txt
# Format per ACL di Varnish
{
echo "acl botallowed {"
cat /tmp/googlebot_ips.txt /tmp/bingbot_ips.txt | grep -v '^$' | awk '{print " "$1 ";"}'
echo "}"
} > "$TMP_FILE"
# Aggiorna solo se ci sono differenze
if ! cmp -s "$TMP_FILE" "$ACL_FILE"; then
mv "$TMP_FILE" "$ACL_FILE"
systemctl reload varnish
fi
rm -f /tmp/googlebot_ips.txt /tmp/bingbot_ips.txt "$TMP_FILE"
Aggiungi al crontab (esecuzione notturna):
0 3 * * * /path/to/update-bot-acl.sh
3. Rate Limiting Intelligente con vsthrottle
Aggiungi al tuo VCL (richiede il VMOD vsthrottle):
import vsthrottle;
# Includi la ACL
include "/etc/varnish/botallowed.acl";
sub vcl_recv {
# ... categorizzazione URL come sopra
if (req.http.X-Page-Type ~ "HOME|LISTING|ARTICLE") {
if (!client.ip ~ botallowed) {
if (vsthrottle.is_denied(client.ip, 10, 4s, 60s)) {
return (synth(429, "Too Many Requests"));
}
}
}
}
4. Risultati
- ✅ Hit-rate di Varnish alle stelle
- ✅ Carico CPU del backend crollato
- ✅ Esperienza utente migliorata
- ✅ Costo totale: zero
Sentiti libero di copiare, adattare e usare questi script e configurazioni!