Archive

Posts Tagged ‘varnish’

Varnish stops file download after 60 seconds

January 23, 2013 3 comments

Varnish Cache logoThe default installation of Varnish 3 on Debian-based system (including Ubuntu) will set a default timeout for sending files to users (i.e. for users files download) to 60 seconds.

To change this limit, it is necessary to update your default Varnish configuration, in /etc/default/varnish.

For example, if you have something like this:

DAEMON_OPTS="-a :80 \
             -T localhost:6082 \
             -f /etc/varnish/default.vcl \
             -S /etc/varnish/secret \
             -s malloc,256m"

make sure you add the send_timeout param, like this (see the -p line):

DAEMON_OPTS=”-a :80 \
-T localhost:6082 \
-f /etc/varnish/default.vcl \
-S /etc/varnish/secret \
-p send_timeout=900 \
-s malloc,256m”

This will obviously increase the maximum download time to 900 seconds (15 minutes), which will make it much more practical and less stressfull to download large files.

The logic behind this very short limit is that, if you’re optimizing your site with Varnish, you shouldn’t make it busy with handling one long-term connection with a large file like this (meanwhile, thousands of other connections could have been treated) and your large files should reside on a CDN or something like this.

Varnish: check your config before you restart!

September 27, 2012 Leave a comment

If you’re using Varnish cache, you will be familiar with the “service varnish restart” then the “oh, there’s a config error and now all my sites are down!”.

Fear no more: there’s a command to check your Varnish syntax before you restart. Just run:

$ varnishd -Cf /etc/varnish/default.vcl

And it will tell you what’s wrong (or at least where the error is). If it prints out all your default.vcl, you’re good!

Categories: English, Varnish Tags: ,

Un Varnish gracioso

August 13, 2012 1 comment

Varnish tiene una funcionalidad interesante llamada “grace” (gracia). Cuando se usa esta funcionalidad, el efecto es que, si el (o los) servidor web que está atrás de el no responden por unos segundos, Varnish puede responder al usuario una versión anterior de la página (si la tiene). Esto permite reducir altamente la cantidad de casos en los cuales un usuario se encuentra con una página tipo “Guru meditation”.

Para implementar esta funcionalidad, lamentablemente, no basta de simplemente poner req.grace = 30s o algo así, como la documentación básica de Varnish lo podría hacer pensar, sino es necesario implementar una configuración un poco más compleja. La página siguiente lo explica en muchos detalles: https://www.varnish-software.com/static/book/Saving_a_request.html

Principalmente, se trata de hacer algo de este tipo (es solo lo necesario, sabiendo que la parte del backend se declara para poder tener una noción de cuando consideramos que está enfermo – el objetivo de la sección .probe – asumiendo que el lector ya sabe de la configuración del módulo server-status de Apache, y estas cosas):

#1. Definición del backend
backend default {
  .host = "192.168.1.5";
  .port = "80";
  .probe = {
    .url = "/server-status";
    .interval = 3s;
    .window = 5;
    .threshold = 2;
  }
}
sub vcl_recv {
        #2. Definición del tiempo de grace cuando el backend está bien
        if (req.backend.healthy) {
                set req.grace = 10s;
        } else {
        #3. Definición del tiempo de grace cuando el backend no responde
                set req.grace = 10m;
        }
        # Activaremos lo siguiente luego
        #unset req.http.Cookie;
} 
#4. El tiempo de grace del backend mismo siempre debería ser 
# mayor o igual al tiempo de grace de Varnish. Este tiempo representa
# el tiempo durante el cual Varnish guarda una copia local de cualquier
# archivo, así que puede impactar mucho en uso de memoria. 
sub vcl_fetch { 
  set beresp.grace = 10m; 
}

Obviamente hay que entender bien lo que esto provoca para poder adaptarlo a cada caso de uso.

Aquí va un pequeño procedimiento de pruebas. Tengo una máquina Varnish local (192.168.1.4) y un servidor web (Apache, en 192.168.1.5) al cual llama el Varnish. Así estoy seguro de isolar los puntos de manera adecuada. Inicio sin niguna configuración particular de ttl en Varnish.

  1. Los dos sistemas (Varnish y Apache) están corriendo. Cargo una página de mi sitio. La veo. Todo bien.
  2. Apago el servidor web. Refresco la página (F5). Tengo un error Varnish (Guru meditation).

Ahora aplico los cambios sugeridos en vcl_recv y vcl_fetch (a parte de beresp.ttl que no defino) en mi configuración de Varnish:

  1. Cargo la página. Se ve.
  2. Apago el servidor web. Recargo (F5). Error. Re-inicio el servidor web. Se ve de nuevo.
  3. Agrego parámetros en Varnish para la gestión de Drupal (por si a caso).  Re-inicio Varnish.
  4. Cargo la página. Se ve.
  5. Apago el servidor web. Recargo (F5). Error. Re-inicio el servidor web. Se ve de nuevo.
  6. Agrego beresp.ttl = 1m; Reinicio Varnish.
  7. Cargo la página. Se ve.
  8. Apago el servidor web. Recargo (F5). Error. Re-inicio el servidor web. Se ve de nuevo.

Obviamente, es probable que Drupal esté afectando algo, ya que es dinámico. Probemos con algo más estático.

En el servidor web, me creo un archivo abc.html en la raíz.

  1. Cargo la página (estática abc.html). Se ve.
  2. Apago el servidor web. Recargo (F5). Error. Re-inicio el servidor web. Se ve de nuevo.

El problema es que los recursos que estamos pidiendo, los estamos pidiendo con Cookies activados. Esto depende de como está la configuración de Varnish acerca de los cookies, pero si, como yo, usan Drupal atrás, hay una serie de cosas que no van a funcionar simplemente porque tener un cookie implica que Varnish desconsidera poner estos recursos en “estado de gracia”. Por lo tanto, podemos hacer una prueba simple…

Dentro de la configuración de Varnish, vamos (para la prueba) a eliminar cualquier Cookie:

sub vcl_recv {
        #2. Definición del tiempo de grace cuando el backend está bien
        if (req.backend.healthy) {
                set req.grace = 10s;
        } else {
        #3. Definición del tiempo de grace cuando el backend no responde
                set req.grace = 10m;
        }
        unset req.http.Cookie;
}

Lo demás lo dejamos como indicado arriba. Ahora hacemos una prueba.

  1. Cargo la página (raíz del sitio, página dinámica). Se ve.
  2. Apago el servidor web. Recargo (F5). Se ve!!!

Esto lo logramos porque ninguna regla posterior invalida el caché de Varnish.

Ahora obviamente hay que afinar. El problema con Drupal es que, si uno lo deja, agrega un paquete de Cookies que se vuelve incontrolable. Para analizarlos, podemos usar Firebug, ponernos en la pestaña  de Cookies, y recargar la página. A todo lo que *no* sea drupal_uid, DRUPAL_UID o drupal_user (si usa authcache, puede ser un caso particular) puede ser eliminado.

Categories: Optimization, Spanish, Varnish Tags: ,

Drupal site with Varnish, returning page without style on CTRL+F5

I had serious problems with a Drupal website with many Varnish optimizations. It so occurs that one of them, a return(lookup) on images and css extensions, was really the one causing the problem:

if (req.url ~ “\.(png|jpg|jpeg|swf|css|ico)”) {
return(lookup);
}

Now I don’t remember precisely why I added this condition in the first place (lookup means you force Varnish to re-use the version it has in cache) but apparently in my case it doesn’t suit my purposes.

The most common actions you can decide to ask Varnish to execute in the vcl_fetch can be found here: https://www.varnish-cache.org/docs/2.1/tutorial/vcl.html#actions

In short:

pass
When you call pass the request and subsequent response will be passed to and from the backend server. It won’t be cached. pass can be called in both vcl_recv and vcl_fetch.
lookup
When you call lookup from vcl_recv you tell Varnish to deliver content from cache even if the request othervise indicates that the request should be passed. You can’t call lookup from vcl_fetch.
pipe
Pipe can be called from vcl_recv as well. Pipe short circuits the client and the backend connections and Varnish will just sit there and shuffle bytes back and forth. Varnish will not look at the data being send back and forth – so your logs will be incomplete. Beware that with HTTP 1.1 a client can send several requests on the same connection and so you should instruct Varnish to add a “Connection: close” header before actually calling pipe.
deliver
Deliver the cached object to the client. Usually called in vcl_fetch.
esi
ESI-process the fetched document.

Force caching for a specific page in Varnish

Just a self-reminder, in the vcl_recv section (before sending request to the backend), check the url you want to always serve from cache and tell it to return(lookup);

  if (req.url ~ “request_server.php$”) {
return(lookup);
}

Reload Varnish and get ready for a massive fall of your load if this bloody request_server.php was overloading your site uselessly…

Categories: English, Tech Crunch Tags: , ,