How do I set a varnish response TTL dynamically?

Solution 1:

The vmod_std module has a function that should do what you're looking for.

import std; at the top of the VCL, then this should work:

sub vcl_fetch
{
    set beresp.ttl = std.duration(beresp.http.X-Cache-ttl, 1h);
}

..where the 1h is your default if the header isn't set.

Solution 2:

According to the Varnish documentation you can use the Cache-Control header.

Cache-Control

The 'Cache-Control' header instructs caches how to handle the content. Varnish cares about the max-age parameter and uses it to calculate the TTL for an object.

So make sure you issue a 'Cache-Control' header with a max-age header. You can have a look at what Varnish Software's Drupal server issues:

$ GET -Used http://www.varnish-software.com/|grep ^Cache-Control
Cache-Control: public, max-age=600

https://github.com/varnishcache/varnish-cache/blob/master/doc/sphinx/users-guide/increasing-your-hitrate.rst