By default, Varnish Cache, a popular HTTP accelerator, is designed to cache content to improve performance by reducing the number of requests made to the backend server. However, the caching behavior can sometimes lead to unexpected results, such as caching POST requests.
Why are POST requests cached?
In Varnish, the caching behavior is determined by the VCL (Varnish Configuration Language) configuration. By default, Varnish caches requests based on the request method, URL, and headers. The default VCL configuration that comes with Varnish is designed to be a good starting point, but it may not cover all edge cases.
In the default VCL configuration, the vcl_recv subroutine is responsible for determining whether a request should be cached or not. The default implementation does not explicitly check the request method, so it will cache requests regardless of the method, including POST.
Shouldn't they let them through?
You're right; POST requests are typically not idempotent, meaning that making the same request multiple times can have different effects on the server. Caching POST requests can lead to unexpected behavior, such as:
Multiple identical POST requests being served from cache, instead of being processed by the backend server.
Potential security issues, as cached POST requests can be served to unauthorized users.
To avoid caching POST requests, you should explicitly configure Varnish to do so. You can modify the vcl_recv subroutine to check the request method and pass POST requests directly to the backend server, without caching.
Here's an example:
vcl
sub vcl_recv {
if (req.method == "POST") {
return (pass);
}
# ... other configuration ...
}
By adding this check, you're telling Varnish to pass POST requests directly to the backend server, without caching the response.
Best practice
To ensure that Varnish behaves as expected, it's recommended to:
Review your VCL configuration to understand how it's handling different request methods.
Explicitly configure Varnish to pass non-idempotent requests (like POST, PUT, and DELETE) directly to the backend server.
Test your configuration thoroughly to ensure it meets your specific use case requirements.
By doing so, you'll be able to take advantage of Varnish's caching capabilities while ensuring that your application behaves correctly.