Spread some Varnish on your site

Larry Garfield
17 Jan 2019
Thumbnail

HTTP itself includes fairly robust rules around caching of web requests. For most applications that’s completely fine, and the router built into every Platform.sh project includes an HTTP reverse proxy cache that can be easily configured for most situations.

Sometimes, though, you just need more power. When the caching gets tough, most developers today turn to Varnish, a highly configurable, high-performance proxy cache server. And as of today, you can add it to your Platform.sh projects.

Huzzah! How?

Varnish is configured similar to any other service, but with some caveats. Rather than sitting behind your application like your database does, it sits between the router and your application. You also need to provide a Varnish VCL file to configure it.

In practice that ends up being quite straightforward. First, you create a Varnish service in your services.yaml file and tell it to use your application as its back end:

# services.yaml

varnish:
    type: varnish:6.0
    relationships:
        application: 'app:http'
    configuration:
        vcl: !include
            type: string
            path: config.vcl

That snippet creates the service and gives it a single relationship named application, which points at the application container. You can also have Varnish front for multiple application containers at once, but you’ll then need to configure when to forward requests to each.

Second, tell the router to send requests to Varnish rather than to the application directly, and disable the router’s cache (as it’s redundant with Varnish):

# routes.yaml

"https://{default}/":
    type: upstream
    upstream: "varnish:http"
    cache: 
        enabled: false

Finally, you need to provide the VCL file for Varnish to use. Our system will auto-create a back end for each relationship so you don’t need to do so and, in fact, cannot declare a vcl_init() function. We take care of that for you. You also must include at least a single line of logic in your vcl_recv() function to determine what back end (relationship) to forward requests to.

Beyond that, it’s your VCL file. Make it as simple or complex as you need for your application.

We have much more detailed information in our documentation.

So should I use it?

That’s up to you, but not everyone needs to. If all you want is a reverse proxy cache for better performance of your site then the existing router cache we already provide will happily handle your needs and require fewer resources to do so. For most users, that’s more than ample.

However, if your application needs arbitrarily complex logic at the caching layer (such as partial page caching, conditional cookie handling, etc.), then you can now slap a layer of Varnish on your application and have it your way.

Happy caching!