Varnish - How can I set TTL in response header?

Solution 1:

Since Varnish 4, backend & client logic have been split up in separate threads. This split is also reflected in VCL.

At the client side of Varnish you have objects like req and resp to access request and response information. When you have to access the backend, the req object gets used to build the bereq object and the response is stored in the beresp object.

As you have noticed the beresp context is not available in vcl_deliver, because the delivery stage happens at the client side.

That's why it's better to set the X-TTL header at the backend side.

Here's the VCL code to do it:

sub vcl_backend_response {
    set beresp.http.X-TTL = "TTL (" + beresp.ttl +")";
}